You are on page 1of 224

Aspen Custom Modeler 11.1

Modeling Language
Reference
Version 11.1

September 2001
Copyright 2001 by Aspen Technology, Inc. All rights reserved.

AspenTech product names that are mentioned in this manual, e.g., Aspen Custom Modeler™, Aspen Dynamics™,
Plantelligence and Enterprise Optimization and the aspen leaf logo 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 manual 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 agreement. Users are solely responsible for the proper use of the
software and the application of the results obtained.

Although AspenTech has tested the software and reviewed the documentation, the sole warranty for the software may
be found in the applicable license agreement between AspenTech and the user. ASPENTECH MAKES NO
WARRANTY OR REPRESENTATION, EITHER EXPRESSED OR IMPLIED, WITH RESPECT TO THIS
DOCUMENTATION, ITS QUALITY, PERFORMANCE, MERCHANTABILITY, OR FITNESS FOR A
PARTICULAR PURPOSE.

Corporate
Aspen Technology, Inc.
Ten Canal Park
Cambridge, MA 02141-2201
USA
Phone: (1) (617) 949-1000
Toll Free: (1) (888) 996-7001
Fax: (1) (617) 949-1030
URL: http://www.aspentech.com/

Division
Design, Simulation and Optimization
AspenTech Ltd.
Sheraton House
Castle Park
Cambridge CB3 0AX
United Kingdom
Phone: +44 (0) 1223 819700
Fax: +44 (0) 1223 366980
URL: http://www.aspentech.com/
Contents
Introduction v
About This Manual.............................................................................................................. v
What You Need To Use This Manual ................................................................................. v
Associated Manuals............................................................................................................ vi
For More Information........................................................................................................ vii
Online Help ........................................................................................................... vii
Printing Portable Document Format Files (PDFs) ................................................ vii
World Wide Web .................................................................................................viii
Technical Support ................................................................................................viii

1 Modeling Language Concepts 1-1


Statements ........................................................................................................................1-2
Type Definitions...............................................................................................................1-3
Declaration Statements.....................................................................................................1-4
Assignments .....................................................................................................................1-5
Assigning Array Elements................................................................................................1-8
Assignment Lists ..............................................................................................................1-9
Assignments using WITHIN and ENDWITH..................................................................1-9
Naming Conventions......................................................................................................1-10
Duplicate Names: BLOCK and STREAM.....................................................................1-11
Parameters ......................................................................................................................1-12
Sets .................................................................................................................................1-13
Set Arithmetic ................................................................................................................1-15
Arrays .............................................................................................................................1-17
Atomic Type Conversions..............................................................................................1-19
Inheritance ......................................................................................................................1-20
Type Relatives................................................................................................................1-21
Built-In Type Definitions ...............................................................................................1-24
Built-In Parameter Types ...................................................................................1-25
Built-In Solved Type ......................................................................................................1-27
Other Built-In Types...........................................................................................1-28

2 Modeling Language for Simulations 2-1


Using Units of Measurement............................................................................................2-2
Specifying a Physical Quantity for Variables.......................................................2-3

Modeling Language Reference Contents • i


Defining Physical Quantities, Units of Measurement, and Conversions .............2-4
Defining Tasks ...............................................................................................................2-15
Callable Tasks ....................................................................................................2-18
Tasks and Rewinding Simulations .....................................................................2-20
Tasks and Opening Simulations.........................................................................2-20
Using Task Statements ...................................................................................................2-21
Assigning a Value to a Variable in Tasks ..........................................................2-21
Defining a Conditional Equation on the Value of a
Simulation Variable in Tasks .............................................................................2-22
Ramping the Value of a Simulation Variable in Tasks ......................................2-22
Suspending and Restarting a Task......................................................................2-24
Creating Snapshots in Tasks ..............................................................................2-27
Executing Tasks in Parallel ................................................................................2-27
PRINT Statements in Tasks ...............................................................................2-28
Pausing a Simulation from a Task......................................................................2-29
Invoking a Script from a Task............................................................................2-29
Defining an Estimation Simulation ................................................................................2-31
Defining Estimated Variables ............................................................................2-32
Defining Steady-State Estimation Experiments .................................................2-32
Defining Dynamic Estimation Experiments.......................................................2-34
Resetting Estimation Experiments .....................................................................2-37
Accessing Results of Estimation Simulations................................................................2-38
Accessing Estimated Variables' Values .............................................................2-38
Accessing Standard Errors .................................................................................2-39
Testing for Standard Error Results.....................................................................2-39
Accessing Individual Correlation Results ..........................................................2-40
Accessing the Correlation Matrix ......................................................................2-41
Testing for the Correlation Matrix .....................................................................2-42
Defining an Optimization Simulation ............................................................................2-43
Optimization Simulation Example.....................................................................2-45
Defining Constraints ..........................................................................................2-46
Defining a Homotopy Simulation ..................................................................................2-47
Example Homotopy Section...............................................................................2-48

3 Modeling Language for Types 3-1


Defining Variable Types ..................................................................................................3-2
Defining Parameter Types................................................................................................3-4
Defining Port Types .........................................................................................................3-5
Defining Model Types......................................................................................................3-6
Defining Stream Types.....................................................................................................3-8
Defining Generic Types ...................................................................................................3-9
Defining Physical Properties Types ...............................................................................3-11
Defining Properties System Data .......................................................................3-11
Validating Component Lists...............................................................................3-13
Using the ComponentList Property....................................................................3-13

ii • Contents Modeling Language Reference


Using More Than One Component List in Models............................................3-15
Atomic Types .................................................................................................................3-16
Defining Solver Properties .............................................................................................3-16
Defining External Procedures ........................................................................................3-18
Defining Model Folders .................................................................................................3-22

4 Modeling Language for Models 4-1


Declaring Variables in Models.........................................................................................4-2
Declaring Ports in Models................................................................................................4-5
Using Port Properties ...........................................................................................4-6
Using the IsMatched Attribute of Variables.........................................................4-7
Using Multiports ..................................................................................................4-8
Writing Equations in Models .........................................................................................4-11
Mathematical Operators in Equations ................................................................4-12
Equations with Array Variables .....................................................................................4-13
Conditional Equations ....................................................................................................4-15
Using Sets in Conditional Expressions ..........................................................................4-18
FOR Loops .....................................................................................................................4-19
ForEach Operator ...........................................................................................................4-21
Equations that Call Procedures ......................................................................................4-23
Equations that Refer to Port Variables ...........................................................................4-24
CONNECT Keyword .....................................................................................................4-25
CONNECT Restrictions.....................................................................................4-27
LINK Keyword...............................................................................................................4-29
LINK Restrictions ..............................................................................................4-29
Connectivity Rules .........................................................................................................4-32
Using SIGMA.................................................................................................................4-33
Using SIGMA for Multidimensional Arrays and Multiports .............................4-34
Using the SIZE Function................................................................................................4-36
Assigning Specifications in Models ...............................................................................4-37
Referring to Sub-Models in a Model Definition ............................................................4-39
Using External Properties to Write Sub-Models............................................................4-41
Example of Using External Properties to Write Sub-Models ............................4-41
Changing the Default Mapping For External Properties....................................4-43
Notes and Restrictions on Writing Sub-Models.................................................4-44
Using Virtual Types in Sub-Models...............................................................................4-44
Example of Using Virtual Types in Sub-Models ...............................................4-44
Restrictions on Using Virtual Types ..................................................................4-46
Using SWITCH ..............................................................................................................4-46

5 Modeling PDE Systems 5-1


About PDE Modeling.......................................................................................................5-2
Creating a Custom PDE Model........................................................................................5-3
Example of Custom PDE Modeling.....................................................................5-3
Using Domains with PDE Modeling................................................................................5-5

Modeling Language Reference Contents • iii


Declaring Domains for PDE Modeling ................................................................5-6
Using Discretization Methods for PDE Modeling ...............................................5-9
Specifying Domain Length.................................................................................5-11
Specifying Element Spacing Preference.............................................................5-12
Using Domain Sections......................................................................................5-14
Number and Location of Discretization Nodes ..................................................5-16
Declaring Distributions for Distributed Variables .............................................5-18
Declaring Distributed Variables that do not Require Partial Derivatives ..........5-21
Referring to Domains in Distributed Variable Declarations ..............................5-21
Using an Array of Distributions .........................................................................5-22
Referencing Domains and Distributions in Sub-Models....................................5-22
About PDAE Models .....................................................................................................5-23
Partial Differential Equations (PDEs) ................................................................5-24
Writing PDEs in Models ....................................................................................5-25
Using Boundary and Initial Conditions for PDE Modeling ...............................5-30
Boundary Conditions Containing Second-Order Derivatives ............................5-33
Open Domains for PDE Modeling .....................................................................5-35
Closed Domains for PDE Modeling...................................................................5-35
Using Domain Slices for PDE Modeling ...........................................................5-35
Using Method of Lines for the Solution of PDEs .........................................................5-36
Finite Difference Methods: General...................................................................5-37
Discretization Methods: Finite Element Methods..............................................5-40
PDE Modeling Glossary.................................................................................................5-42

6 Modeling Language for Flowsheets 6-1


Defining Flowsheets.........................................................................................................6-2
Declaring Blocks ..............................................................................................................6-4
Defining the Connectivity of Blocks................................................................................6-5
Making Flowsheet Assignments ......................................................................................6-5
Specifying Variable Properties.........................................................................................6-7
Defining Flowsheet Constraints .......................................................................................6-8

7 Modeling Language Conventions 7-1


Modeling Language Conventions.....................................................................................7-2
Adding Comments................................................................................................7-2
General Modeling Language Conventions ...........................................................7-2
Text Conventions .............................................................................................................7-3

Index

iv • Contents Modeling Language Reference


Introduction

This chapter describes:


• The contents of this manual
• Associated manuals
• Where to find further information

About This Manual


This manual describes the modeling language in detail, giving
examples and definitions where necessary. The following topics
are covered:
• Concepts
• Simulations
• Types
• Models
• PDE modeling
• Flowsheets
• Conventions

What You Need To Use This Manual


To use this book, you need Aspen Custom Modeler™ installed on
PC or PC file server running Windows 2000 or Windows NT. For
information on how to do this, read the Installation Guide supplied
with the product, or contact your system administrator.

Modeling Language Reference Introduction • v


Associated Manuals
Aspen Custom Modeler™ also comes with the following manuals
in PDF file format.

Manual Title Description


Getting Started Tutorials Contains basic hands-on
tutorials to help you become
familiar with Aspen Custom
Modeler
Examples Contains more complex and
extensive examples of using
Aspen Custom Modeler
Library Reference Contains reference information
on control models, property
procedure types, utility routines,
port types, and variable types
Aspen Modeler Reference 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
SPEEDUP® 5 Source Contains information on
Converter processing a SPEEDUP 5 input
file and generating a new input
file (.acmf) for use in Aspen
Custom Modeler
Using DMCplus® Controllers Contains information on using
DMCplus with Aspen Custom
Modeler or Aspen Dynamics™

vi • Introduction Modeling Language Reference


For More Information
You can obtain information on Aspen Modeler products by:
• Accessing the comprehensive online Help system
• Reading the printed manuals supplied with your product
• Printing the Portable Document Format (PDF) files supplied
on the installation CD
• Accessing Aspen Technology's web page
If you need more detailed assistance than that provided in the
online Help and the PDF files, you can contact Technical Support.
This section explains how to use the online help, print PDF files,
find Aspen Technology on the web, and contact Technical Support.
Online Help To access online Help:
• From the Help menu, click Help Topics and then do one of
the following:
To Do this

Display a hierarchy of topics by Click the Contents tab


category
Display an index of all Help topics Click the Index tab and then type
the word you require
Search for words or phrases within Click the Find tab and then type
the Help topics the word or phrase you require

Tip To display Help on buttons, fields, menu commands, and


other screen elements, click the What's This button: or , at the
top of the window, and then click the element.

Printing Online Help


To display information on how to print online Help:
1. Open your Aspen Modeler product and from the Help menu,
click Help Topics.
2. On the Contents tab, double-click Using Help and then
double-click Print Help Topics.
Printing Portable To print these manuals you must have Adobe Acrobat Reader
Document Format installed on your machine.
Files (PDFs) Tip If you do not have the Adobe Acrobat Reader, you can
download a free copy from the Adobe web site at:
http://www.adobe.com.
Note Adobe and Acrobat are trademarks of Adobe Systems,
Incorporated.

Modeling Language Reference Introduction • vii


After you have installed the Adobe Acrobat Reader, you can open
the files to view and print the manuals. To do this:
• From the Start menu, point to Programs, then AspenTech,
Aspen Engineering Suite, Product Name 11.1,
Documentation, and then click the name of the manual you
want to access.
World Wide Web For additional information about AspenTech products and services,
check the AspenTech World Wide Web home page on the Internet
at: http://www.aspentech.com/
Technical Support AspenTech customers with a valid license and software
maintenance agreement can register to access the Online Technical
Support Center at http://support.aspentech.com.
This web support site allows you to:
• Access current product documentation
• Search for tech 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 are used to proactively alert users to
important technical support information such as:
• Technical advisories
• Product updates
• Service Pack announcements
• Product release announcements
Customer support is also available by phone, fax, and email for
customers with a current support contract for this product. For the
most current contact information, please see the Online Technical
Support Center at http://support.aspentech.com.

viii • Introduction Modeling Language Reference


Operating Hours

North 8:00 – 20:00 Eastern Time


America
South 9:00 – 17:00 Local time
America
Europe 8:30 – 18:00 Central European time
Asia and 9:00 – 17:30 Local time
Pacific
Region

Phone Numbers

North 1-888-996-7100 Toll-free from U.S., Canada, Mexico


America 1-281-584-4357 North America Support Center
(52) (5) 536-2809 Mexico Support Center
South (54) (11) 4361-7220 Argentina Support Center
America (55) (11) 5012-0321 Brazil Support Center
(0800) 333-0125 Toll-free to U.S. from Argentina
(000) (814) 550- Toll-free to U.S. from Brazil
4084
8001-2410 Toll-free to U.S. from Venezuela
Europe (32) (2) 701-95-55 European Support Center
Country specific toll-free numbers:
Belgium (0800) 40-687
Denmark 8088-3652
Finland (0) (800) 1-19127
France (0805) 11-0054
Ireland (1) (800) 930-024
Netherlands (0800) 023-2511
Norway (800) 13817
Spain (900) 951846
Sweden (0200) 895-284
Switzerland (0800) 111-470
UK (0800) 376-7903
Asia and (65) 395-39-00 Singapore
Pacific (81) (3) 3262-1743 Tokyo
Region

Modeling Language Reference Introduction • ix


Fax Numbers

North 1-617-949-1724 (Cambridge, MA)


America 1-281-584-1807 (Houston, TX: both Engineering and
Manufacturing Suite)
1-281-584-5442 (Houston, TX: eSupply Chain Suite)
1-281-584-4329 (Houston, TX: Advanced Control Suite)
1-301-424-4647 (Rockville, MD)
1-908-516-9550 (New Providence, NJ)
1-425-492-2388 (Seattle, WA)
South (54) (11) 4361-7220 (Argentina)
America (55) (11) 5012-4442 (Brazil)
Europe (32) (2) 701-94-45
Asia and (65) 395-39-50 (Singapore)
Pacific (81) (3) 3262-1744 (Tokyo)
Region

E-mail

North support@aspentech.com (Engineering Suite)


America atmdsupport@aspentech.com (Aspen ICARUS products)
mimi.support@aspentech.com (Aspen MIMI products)
pims.support@aspentech.com (Aspen PIMS products)
aspenretail.support@aspentech.com (Aspen Retail products)
acs.support@aspentech.com (Advanced Control products)
AMS.support@aspentech.com (Manufacturing Suite)
Gabriela.Torres@aspentech.com (Mexico)
South info@tecnosolution.com.ar (Argentina)
America tecnosp@aspentech.com (Brazil)
Europe atesupport@aspentech.com (Engineering Suite)
AMS.support@aspentech.com (All other suites)
cimview@aspentech.com (CIMVIEW products)
Asia and atasupport@aspentech.com (Singapore: Engineering Suite)
Pacific SG_support@aspentech.com (Singapore: All other suites)
Region atjsupport@aspentech.com (Tokyo: Engineering Suite)
TK_Support@aspentech.com (Tokyo: All other suites)

x • Introduction Modeling Language Reference


1 Modeling Language Concepts

This chapter describes the following general concepts behind the


modeling language:
• Statements
• Type definitions
• Declaration statements
• Assignments
• Assigning array elements
• Assignment lists
• Assignments using WITHIN and ENDWITH
• Naming conventions
• Duplicate names: BLOCK and STREAM
• Parameters
• Sets
• Set arithmetic
• Arrays
• Conversions of atomic types
• Inheritance
• Type relatives
• Built-in type definitions

Modeling Language Reference Modeling Language Concepts • 1-1


Statements
Use statements to make assignments of value, equations,
declarations and connections.
Statements that include one of the syntax elements shown in the
following table must end with the ; (semi-colon) character.

Element Type of Assignment

: Value assignments
= Equation assignments
AS Declaration assignments
CONNECT AND Connection assignments
LINK AND Link assignments

Statement Examples
All the following examples are statements and must end with ;
(semi-colon), as shown.
The following example assigns a value to the message output level:
PRINTLEVEL: 2 ;
The following example assigns a value to a variable and states that
the variable is known:
Feed.Temperature: 75.0, Fixed ;
The following example equates two variables in a model:
FlowIn = FlowOut ;
The following example creates an instance of a model in a
flowsheet, or in a model description:
FeedValve AS Valve ;
The following example makes a connection of an input to a
flowsheet terminator:
CONNECT FeedValve.Input1 ;
The following example makes a connection between the input and
output of two blocks:
CONNECT Pump1.Output1 AND Valve2.Input1 ;
The following example makes a connection between the port of a
sub-model and the port of the containing model:
LINK Tank5.Output1 AND MultiOutput1 ;

1-2 • Modeling Language Concepts Modeling Language Reference


Type Definitions
Type definitions introduce and describe new types for models,
streams, variables, procedures, ports, properties, parameters, and
options. You can also use a generic type to introduce types that
cannot be described by the modeling language.
For further information on types, see Modeling Language for
Types. Chapter 3.
Type Definition Syntax
The syntax for all type definitions is of the form:

TypeKeyword Identifier
CLASS ClassString
USES TypeName
ROLE RoleString

DefinitionBody

END

TypeKeyword...................One of these keywords: MODEL, STREAM,


VARIABLE, STRUCTURE, QTYPE, PROCEDURE,
CONTROLLER, PORT, PROPERTIES, TYPE,
PARAMETER, SNAPSHOT, OPTIONS
Identifier ...........................The name of the type being defined. This name must be
unique within the scope in which the definition is made.
ClassString ......................A string of text that identifies a class used to implement
this definition. If you do not use the CLASS keyword, the
parser uses a default implementation.
TypeName ........................The name of a type (which has been previously defined),
from which this type inherits properties
RoleString ........................A string of text that describes the role of a type within the
language. Only required when a generic type is described
to the compiler.
DefinitionBody.................The content of the definition. This varies depending on
the object that is defined. The definition body can be one
of the types listed in Chapter 3. In the simplest case, the
definition body is just a list of the declarations or
assignments of the type’s properties.

Modeling Language Reference Modeling Language Concepts • 1-3


Type Definition Example
In the following example, the keyword VARIABLE introduces a
new variable type. The name given to the type is Temperature. This
type defines the properties of all variables that are temperatures.

VARIABLE Temperature
Value : 1.0 ;
Upper : 300.0 ;
Lower : -40.0 ;
Spec : Free;
Scale : 10.0 ;
Description : "Temperature in Celsius";
PhysicalQuantity : "Temperature";
END

Declaration Statements
A declaration introduces a property by giving it a name and
describing its type. The syntax for all declarations has the
following form:

Identifier , Identifier ... AS FlagList TypeName (AssignmentList);

Identifier ........................... The name of the property being declared


FlagList ............................ A list of qualifiers, separated by commas, that can apply
to a property. These qualifiers affect the implementation
of the property and are optional. For example, the valid
direction(s) of a port is defined in the FlagList
TypeName ........................ The name of the type of which Identifier is an instance.
The type name may identify any previously defined
type.
AssignmentList ............... A comma-separated list of assignments of values to
properties of the type identified by TypeName. The
assignments apply to all the properties declared in the
statement. The assignments in the list are of the form
PropertyName:Value. However, if the type of the value
unambiguously identifies the property, you can omit
PropertyName.

Declaration Statement Remarks


Note that not all declarations are valid for a particular type. For
example, you cannot declare a port in a variable type.

1-4 • Modeling Language Concepts Modeling Language Reference


Declaration Statement Example
In the following example, the keyword MODEL introduces a new
model type. The model is called Heater. This definition describes a
heater that contains a variable called T, where T is a temperature.

MODEL Heater
T AS Temperature;
T.Value : 100.0;
END
The line T as Temperature; is called a declaration. A declaration
is used to add properties to types. In this example a variable T is
added to the model type Heater. The variable T has the properties
of the variable type Temperature, for example, Value, Upper,
Lower, and so on. These properties can then be modified. The
property value has the real number 100.0 assigned to it in this
example.

Assignments
Assignments that involve expressions are treated as constraints by
the compiler. This means that if an expression occurs on the right
side of an assignment then that expression is re-evaluated
whenever the value of any term within it changes. The result is
then assigned to the property on the left side.

Assignment Syntax
The modeling language uses : (a colon) as its assignment operator:

Object.Property : PropertyValue;...

Object ...................... A variable or parameter


Property ................... A property of the variable or parameter,
which can be one of the following:
Value, Upper, Lower, Scale, IsConnected,
Description, PhysicalQuantity, and Spec.
Note If you do not specify a property, Value
is assumed.
PropertyValue.......... The first guess value

Modeling Language Reference Modeling Language Concepts • 1-5


Assignment Remarks
You can assign values to properties of variables in many places in
the language, for example, in variable types, models, and
flowsheets. You can later change these values without using the
modeling language. The following list shows the order of
precedence in which the variable properties are changed, from the
highest priority, to the lowest:
• Variable property changes made in the following ways are
made immediately and overwrite any previous assignment:
− Interactive changes, for example, using a table, using
the automation interface, running a script, or applying
a snapshot with Use
− Solving a simulation
− Opening a simulation which restores a previous
solution
• These are of equal priority and the last activity always takes
effect. No other assignment can prevent these changes from
occurring or change these values unless you Reset the
variable to its default value.
• Assignments written into the Flowsheet and not within the
Constraints section are applied above all other assignments
in the language. This type of assignment can only be written
into the Flowsheet in a saved language file (.acmf) using a
text editor.
• Assignments written into the Flowsheet Constraints sections
are applied above all other language assignments you can
make by editing types, for example, models and variable
types.
• Assignments made in a block due to instancing a model
takes place in simple top-down series of assignments.
Changing a parameter after placing the block on the
flowsheet can cause an IF to switch and then cause one or
more model assignments to be made. This only happens if
the variable values are still at their default values. A model
assignment cannot override a flowsheet value assignment,
an interactive change, or a solution value (unless it is still at
the default value).
• Assignments made in a block due to a parent model take
precedence over those due to child models in a hierarchy.
• Assignments made in a block due to a derived model take
precedence over those due to the base model in inheritance.
• Assignments made in a variable type are the lowest in the
order of precedence. The lowest precedence of all is given to
an assignment made in a base variable type which other
variable types inherit and modify.

1-6 • Modeling Language Concepts Modeling Language Reference


Assignment Examples
The following example specifies that the numerical value 5 is
assigned to the property, Value, of the variable x. If another
numerical value is subsequently assigned to x, it replaces the
value 5:

x : 5.0;
The following examples specify the numerical values for the
properties Lower and Upper, for the variable, x:

x.Lower : -10;
x.Upper : 20;
The following example specifies that the string "Cylinder" is
assigned to the property, Value, of the parameter Geometry:

Geometry : "Cylinder";
The following example specifies that the logical True is assigned to
the property, Value, of the parameter, PressureDriven:

PressureDriven : True;
The following example assigns to the property, Value, an
expression, 5/60, for the variable, Lag:

Lag : 5/60;
For further examples of assignments, see Defining Specifications
in Models Examples and Defining Specifications in Flowsheets
Examples.

Modeling Language Reference Modeling Language Concepts • 1-7


Assigning Array Elements
You can assign values to array elements individually.
Assigning Array Elements Syntax

ArrayVariable(Index) : Value ;

ArrayVariable ................... Variable defined as an array


Index................................. The index of the array, defined by a Set element
Value ................................ The value you assign to the variable element

Assigning Array Elements Example


The following example shows the values of a set assigned
individually:

Components AS
StringSet(["H2O","H2+","Zn++","Ca++"]);
mw(Components) AS MoleWeight;
mw("H2O"):18;
mw("Ca++"):40.1;
Note The name Components is defined as a set. Therefore, when
you use this name, you do not need to use the [ ] characters to
define the set. Also, when you want to refer to individual elements
of the set, you do not need to use the [ ] characters.
You need to use [ ] to define a set only when you use a list of set
elements.
For example, the array variable mw in the above example could
have been defined:

mw(["H2O","H2+","Zn++","Ca++"]) AS MoleWeight;

1-8 • Modeling Language Concepts Modeling Language Reference


Assignment Lists
You can use assignment lists in variable assignments to avoid
repeating path names.
Assignment List Syntax

Property : Assignment, Assignment, ... ;

Property............................ Object such as a variable in a block


Assignment...................... Value assigned to the Property

Assignment List Example


The following example assigns 25 to the value property and
FIXED to the specification property of the variable Tank.Q. If a
value being assigned identifies a particular property, you can omit
the property name.

Tank.Q : 25.0, FIXED;


Tank.Q.LOWER:-10.0 ;
In this example, a real number without a keyword is identified as
the value of the variable, and a text string is identified as the
specification of the variable. You need to include the keyword for
the lower and upper bounds, and for other properties of a variable.

Assignments using WITHIN and


ENDWITH
If you want to make several assignments to the same variable, you
can reduce the amount of typing by using the WITHIN and
ENDWITH keywords.
WITHIN and ENDWITH Syntax

WITHIN BlockName.VariableName
PropertyAssignmentList
ENDWITH

BlockName....................... The name of a block


VariableName .................. The name of a variable in a model

WITHIN / ENDWITH Remarks


You can use WITHIN / ENDWITH statements when assigning
sub-model variables in a Model definition, or when you define a
Flowsheet using a text editor.

Modeling Language Reference Modeling Language Concepts • 1-9


WITHIN / ENDWITH Example
The following example shows how using WITHIN and ENDWITH
enables you to make multiple specifications on the same variable:

WITHIN Tank.Q
Value : 25.0 ;
Spec : FIXED ;
Lower : 0.0 ;
Upper : 100.0;
ENDWITH
Alternatively, you can type each specification explicitly:

Tank.Q.Value : 25.0 ;
Tank.Q.Spec : FIXED ;
Tank.Q.Lower : 0.0 ;
Tank.Q.Upper : 100.0;

Naming Conventions
You use names when you:
• Define a type
• Add a property to a type
Important Do not create a type which has the same name as a
built-in type. This can have undesirable results.
Because you use names to identify objects from external programs
such as Microsoft® Visual Basic® or Microsoft Excel, you should
apply the naming rules for Visual Basic.
Make sure that the names you choose:
• Conform to the rules imposed by the external programs
• Are unique, because each name identifies a particular object
• Include only characters from a restricted set. The set is all
the alphanumeric characters plus the _ (underscore)
character.
• Start with an alphabetic character, not a numeric one
• Do not begin with am_

1-10 • Modeling Language Concepts Modeling Language Reference


Duplicate Names: BLOCK and
STREAM
Within a definition, the names you use for all properties must be
unique. However, you can use a special syntax to give blocks and
streams the same name on the flowsheet. This syntax can be used
to give block outlet streams on a flowsheet the same names as the
blocks to which they are attached.
You can use the same syntax both in input files and in Microsoft®
Visual Basic®. When you use this syntax, the flowsheet and the
Simulation Explorer display only the part of the name that is
between the quotation marks (" and "). Elsewhere, the full syntax
is used to refer to the block or stream.
BLOCK Syntax

BLOCKS("BlockName").VariableName

STREAM Syntax

STREAMS("StreamName").VariableName

BLOCKS ........................... Block keyword


STREAMS......................... Stream keyword
BlockName....................... Name of a block in the flowsheet
StreamName .................... Name of a stream in the flowsheet
VariableName .................. Name of a variable in the block or stream
definition

BLOCK Keyword Example


If block and stream names are not unique, you can use qualifiers to
distinguish the different objects. To use a qualifier, add a keyword
to the path name of the object:

Blocks("B1") AS Heater;
Streams("B1") AS MaterialStream;

BLOCKS("B1").Temperature =
STREAMS("B1").Temperature;
BLOCK and STREAM are reserved words and cannot be used to
name definitions.

Modeling Language Reference Modeling Language Concepts • 1-11


Parameters
Use parameters to define values that are fixed for the whole
simulation, such as acceleration due to gravity, or the gas constant.
You can use parameters for fixed physical quantities such as the
number of trays in a column.

Parameters Syntax

ParameterName AS ParameterType (Value) ;

ParameterName............... Name of the parameter


ParameterType ................ Can be IntegerParameter, RealParameter,
StringParameter, or LogicalParameter, or a user-
defined parameter.
Value ................................ Assign a value to the parameter

Parameters Remarks
The distinction between variables and parameters is that variables
are solved for by the solution routines, whereas parameters control
which variables and equations define a particular instance of a
model. Like variables, parameters are declared within types and
they can be treated as properties of instances of types in the same
way as variables.
Parameters may be of type INTEGERPARAMETER,
STRINGPARAMETER, LOGICALPARAMETER,
REALPARAMETER. These four types are built in to the language.
In addition, you can refine these parameter types by defining new
parameter types that inherit properties from these built-in
parameter types. To define new parameter types, use the
PARAMETER keyword. Use inheritance to ensure that the new
type is derived from one of the built-in parameter types.
You can test parameters in the condition part of IF ... ENDIF
statements to define structural variations within models.

1-12 • Modeling Language Concepts Modeling Language Reference


Parameters Example
In the following example, the model Column has a parameter
NStages. This parameter is used to define an array of Tray models
called Stages. Within the column, the parameter has a default value
of 10. This means that if a column was declared, its NStages
parameter would have a value of 10 and therefore it would have 10
trays. In the example, a column, C101, is declared within the
flowsheet, but the value of NStages for C101 is assigned a new
value of 20. This means that C101 in this flowsheet has 20 trays
and not 10.

MODEL Column

NStages AS IntegerParameter(10);
Stages([1:NStages]) AS Tray;
.
.
.
END

FLOWSHEET

C101 AS Column(NStages:20);

END

Sets
You can define sets to create array variables, control the operation
of FOR loops, define component lists, and build flexible models. A
set is a collection of objects that has no duplicate values and is not
in any specific order. Aspen Custom Modeler™ uses sets in the
same way as a mathematical set. To manipulate sets in Aspen
Custom Modeler, you use set functions, such as union, intersection,
and difference.
Arrays are indexed by the contents of a set. For information on
arrays, see Arrays.

Sets Syntax

SetName AS SetType (SetContents) ;

SetName........................... The name you give for this set


SetType Can be IntegerSet or StringSet
SetContents An optional list of the contents of the set

Modeling Language Reference Modeling Language Concepts • 1-13


Sets Remarks
You can define the set contents at the same time as you define the
set properties. Alternatively, you can define the set contents later in
your simulation description.
The set contents are defined by a list of objects enclosed between [
and ] (brackets), or a named set.
You can only define a set of integers (IntegerSet) or a set of strings
(StringSet).
An IntegerSet is a set whose members are integers, for example,
1:10.
A StringSet is a set whose members are strings, for example,
component names.

Sets Examples
In the following example, the set MySet is defined as containing
objects that are of integer values. The contents of the set are not yet
defined.
MySet AS IntegerSet;
In the second example, MySet is defined as containing integer
objects. However, the set is immediately defined as an empty set.
This set has no contents:
MySet AS IntegerSet( [] ) ;
In the third example, MySet contains four integer objects of the
value 1, 2, 3, and 4:
MySet AS IntegerSet( [ 1, 2, 3, 4 ] ) ;
The fourth example shows the same definition of MySet as the
previous example, but uses : (a colon) to define the contents as all
integers from 1 to 4:
MySet AS IntegerSet( [1:4] ) ;
In the fifth example, MySet contains the same values as the
previous example, but not in the same order:
MySet AS IntegerSet( [ 1, 3, 2, 4 ] ) ;
In the last example, MySet is defined as a set containing the strings
"Yes" and "No":
MySet AS StringSet( [ "Yes", "No" ] ) ;

1-14 • Modeling Language Concepts Modeling Language Reference


Set Arithmetic
The symbols available for the manipulation of sets are:

Symbol Function Argument

+ UNION Two sets


– DIFFERENCE Two sets
* INTERSECTION Two sets
none SYMDIFF Two sets
Sets Arithmetic Notes
The UNION of two sets is the set of elements that are in both sets
but without duplicates.
The DIFFERENCE of two sets is the set of elements in the first set
but not in the second set.
The INTERSECTION of two sets is the set of elements that are
common to both sets.
The SYMDIFF of two sets is the set of the elements that are in one
set but not in the other. This can be defined as the difference
between the union and the intersection of the two sets.

Set Arithmetic Function Syntax


You can use the symbol or the function name for set arithmetic.

SetExpression SetFunctionSymbol SetExpression ;

SetExpression ................. Either a named set or a set definition enclosed by [ ]


(brackets)
SetFunctionSymbol......... One of the following set function symbols: + – *
or

SetFunctionName ( SetExpression, ... ) ;

SetExpression ................. Either a named set or a set definition enclosed by [


] (brackets)
SetFunctionName............ One of the set function names, such as UNION,
INTERSECTION, etc.

Modeling Language Reference Modeling Language Concepts • 1-15


Sets Arithmetic Example
Define SetA and SetB:
SetA AS IntegerSet( [ 1, 2, 3, 4 ] );
SetB AS IntegerSet( [ 3, 4, 5, 6 ] );
The union of SetA and SetB is [ 1, 2, 3, 4, 5, 6 ]:
SetA + SetB
or
UNION (SetA, SetB) ;
The intersection of SetA and SetB is [ 3, 4 ]:
SetA * SetB
or
INTERSECTION (SetA, SetB) ;
The difference of SetA and SetB is [ 1, 2 ]:
SetA - SetB
or
DIFFERENCE (SetA, SetB) ;
The symmetric difference of SetA and SetB is [ 1, 2, 5, 6 ]:
SYMDIFF ( SetA, SetB )
The UNION of two sets is the set of elements that are in both sets
but without duplicates.

DIFFERENCE Note
The DIFFERENCE of two sets is the set of elements in the first set
but not in the second set.

INTERSECTION Note
The INTERSECTION of two s~ets is the set of elements that are
common to both s~ets.

SYMDIFF Note
The SYMDIFF of two s~ets is the set of the elements that are in
one set but not in the other. This can be defined as the difference
between the union and the intersection of the two s~ets.

1-16 • Modeling Language Concepts Modeling Language Reference


Arrays
An array is a collection of objects indexed by either an integer set
or by a string set. An array is defined as being indexed by one or
more sets, depending on the number of dimensions of the array.
You can use arrays to define a collection of variables, a collection
of ports, a collection of blocks, a collection of parameters, or a
collection of streams.
Note. Global arrays are not supported in ACM v11.1.

Arrays Remarks
Because an array is defined by a set, the index of the array may not
take consecutive integer values. You can define an array that is
indexed by an integer set that has some of the integer numbers
“missing”. This is useful for modeling trays in a distillation
column, where you may want to use a different model for a feed
tray, for example.
As arrays can be indexed by a string of text, you can define an
array indexed by component names. For more information, see
Chapter 3, Using the ComponentList Property.

Arrays Examples
The following line defines an array variable. The variable
SectionTemp is indexed explicitly as having integer elements from
1 to 10:
SectionTemp( [1:10] ) AS Temperature ;
The variable FeedMolFrac is indexed to the set called
Components, which contains three string elements:
Components AS StringSet(["N2", "O2", "CO2"])
FeedMolFrac( Components ) AS MolFraction ;
The variable SectionMolFrac is defined as a two dimensional
array. The first dimension is defined as the set Components and the
second dimension is explicitly stated as integer elements from
1 to 10:
SectionMolFrac ( Components,[ 1: 10 ] ) AS
MolFraction ;

Modeling Language Reference Modeling Language Concepts • 1-17


The following example defines an array of model instances:
MODEL Tray
.
.
END
MODEL FeedTray
.
.
END

MODEL Column

NTrays AS IntegerParameter(10);
NFeedTray AS IntegerParameter(5);

Stage( [1:NTrays] - NFeedTray ) AS Tray ;


FeedStage AS FeedTray ;
.
.
END
In this example, the model Column uses a previously defined
model Tray. The parameter NTrays is used to define an array of
instances of the Tray model within the Column model. The number
of the feed tray is defined as an integer parameter. Set arithmetic is
used to create an array of Trays called Stage without Stage(5)
existing.
The definition for Stage is:
Stage([1, 2, 3, 4, 6, 7, 8, 9, 10])

1-18 • Modeling Language Concepts Modeling Language Reference


Atomic Type Conversions
The CONVERTTO operator enables you to convert a string or the
first element in a set of strings to the integer value that it
represents.
You can also use CONVERTTO to convert a REAL, INTEGER, or
LOGICAL value to a string. For example, you could use
CONVERTTO in a task, to print out variable values (because the
PRINT statement in a task allows only strings).
CONVERTTO Syntax
Use the following syntax for CONVERTTO:

CONVERTTO '('ResultType', 'Expression')';

ResultType ....................... Can be INTEGER or STRING


Expression....................... If ResultType is INTEGER, Expression must be of
type STRING or STRINGSET
If ResultType is STRING, Expression must be REAL,
INTEGER, or LOGICAL

Example of Using CONVERTTO


The following example shows how to use CONVERTTO to
convert to integer values:

myset as stringset(["5", "7", "9"]);


x_int as IntegerParameter(CONVERTTO(INTEGER,
"3")); //initializes x_int with the integer value
3
x_int: CONVERTTO(INTEGER, myset); //assigns the
integer value of the first element in myset (5)
to x_int

The following example shows how to use CONVERTTO to


convert to a string:

task MyTask
s2 as StringParameter;
s2 : CONVERTTO(string, v); // where V is a
variable accessible to the task
print "variable v is "+s2;
//print CONVERTTO(string, v); // Note that
CONVERTTO cannot be used directly in a print
statement.
end

Modeling Language Reference Modeling Language Concepts • 1-19


Inheritance
The modeling language supports inheritance to enable you to re-
use previous type definitions. You describe an inheritance
relationship between two type definitions with the keyword USES.
Inheritance Syntax

Type TypeName USES TypeName


Statements
END

Type .................................. One of the TYPE types in the modeling language


TypeName ........................ Name of a type definition
Statements....................... Statements which extend the definition of the inherited type

Inheritance Remarks
Inheritance enables you to extend a type definition by adding extra
properties to the type definition. Inheritance enables you to refine
the definition only by changing the default values of existing
properties. However, you cannot change the types of inherited
properties in a derived type.
All types are defined by inheritance. If you define a type using
inheritance, the type inherits all the properties of the type from
which it inherits. If you define a type without using inheritance, the
compiler defines a default inheritance relationship for that type.
For each type that you can define, you inherit properties from a
built-in type.
Note Icons are not inherited between models.

Inheritance Example
In the following example, the variable definition ColdTemp
inherits all the properties and defaults from the variable definition
Temperature, but it overrides the default value for the property
UPPER. Because UPPER is not declared within the ColdTemp, it
must have been declared within Temperature or within a definition
from which Temperature is derived.

VARIABLE ColdTemp USES Temperature


UPPER: 273 ;
END

1-20 • Modeling Language Concepts Modeling Language Reference


In the following two examples, the model HeatedTray is derived
explicitly from the model Heater. The model Tray is derived from
the built-in type GenericModel. GenericModel is the type from
which all model types are derived.

MODEL HeatedTray USES Heater


.
.
END
MODEL Tray
.
END

Type Relatives
The inheritance relationship enables you to define a family of
related types that can be substituted for each other.
For example, in a procedure definition, you list the types of the
input and output variables expected in a procedure call. Using
inheritance, you can define new variables that inherit properties
from the type you have named in the procedure call argument list.
You can use these new variable types in the same procedure,
because they are recognized as descendants of the variable types
you named in the procedure call list.
You can use related types to determine which ports can be
connected, using custom streams. You cannot connect instances of
different port types, unless the two port types are related types. One
of the port types must be related to the other port type through
inheritance. If you use the built-in Connection stream, any two
ports can be connected. In this case, variables in the ports being
connected are matched by name.

Modeling Language Reference Modeling Language Concepts • 1-21


Type Relatives Example
The first example shows how two ports are created using
inheritance. These two related ports can be connected together in
the flowsheet.

PORT Material
Flow AS Flow_Vol_Liq;
END
PORT NewMaterial USES Material
Temp AS Temperature;
END
MODEL Tank1
.
Out1 AS OUTPUT NewMaterial;
.
END
MODEL Tank2
.
In1 AS INPUT Material;
.
END
STREAM MaterialStream;
In1 AS InputMaterial;
Out AS OutputMaterial;
In1.Flow = Out.Flow;
END
FLOWSHEET
S1 AS MaterialStream;
T1 AS Tank1;
T2 AS Tank2;
CONNECT T1.Out1 AND T2.In1 WITH s1;
END
The port Material carries flow rate, and the port NewMaterial
carries flow rate and temperature values. The two ports can be
connected, as they are related by inheritance. However, the
temperature value carried from the first tank T1 is not passed to the
second tank T2.

1-22 • Modeling Language Concepts Modeling Language Reference


In the following example, the procedure TotalMassCalc is written
to accept a variable of type Liquid Density as an input argument.
However, the same argument can accept a variable of a type related
to LiquidDensity. In this case the variable type VaporDensity is
related by inheritance to LiquidDensity. A variable of type
VaporDensity can be an argument to the procedure call too.
VARIABLE LiquidDensity
Value: 1000.0 ;
Lower: 10.0 ;
Upper: 1.0e5 ;
PhysicalQuantity: "Density";
END

VARIABLE VaporDensity USES LiquidDensity


Value: 1.0 ;
Lower: 1.0e-2 ;
Upper: 100.0 ;
PhysicalQuantity: "Density";
END
.
.

PROCEDURE TotalMassCalc
.
.
INPUTS : Area, Length, LiquidDensity;
OUTPUTS : Mass;
END

MODEL Tank

TankArea AS Area ;
TankHeight AS Length ;
RhoLiq AS LiquidDensity ;
RhoVap AS VaporDensity ;
TotalMass AS Mass ;

Phase AS PhaseParameter("Liquid");

IF Phase == "Liquid" THEN


CALL (TotalMass) = TotalMassCalc(TankArea,
TankHeight, RhoLiq) ;
ENDIF

IF Phase == "Vapor" THEN


CALL (TotalMass) = TotalMassCalc(TankArea,
TankHeight, RhoVap) ;
ENDIF

END

Modeling Language Reference Modeling Language Concepts • 1-23


Built-In Type Definitions
Aspen Custom Modeler™ provides a number of built-in type
definitions in the library, called SystemLibrary. These definitions
are the basis for your own variables, models, and streams.
You create your own definitions of variables, models, and streams
by inheriting the values of the built-in type definitions and
modifying these to suit your needs. All types in an Aspen Custom
Modeler simulation are originally derived from these built-in types.
Important Do not create a type which has the same name as a
built-in type. This can have undesirable results.
The built-in types are:

Built-In Model Types


• AngleDomain
• Distribution1D
• Distribution2D
• Distribution3D
• Domain
• LengthDomain

Built-In Parameter Types


• RealParameter
• IntegerParameter
• StringParameter
• LogicalParameter
• LengthParameter
• AngleParameter

Built-In Solved Type


• RealVariable

Other Built-In Types


• GenericModel
• GenericStream
• GenericPort
• GenericConnection
• GenericControlSignal
• ControlPort
• ConnectionPort
• SlackVariable
• PartialDerivative

1-24 • Modeling Language Concepts Modeling Language Reference


Built-In Parameter The value types represent types that hold information in addition to
Types the actual value, such as a description. Use the PARAMETER
keyword for all the different parameter types in your simulation.
Aspen Custom Modeler™ determines the parameter type from the
built-in type from which the parameter type is derived.
The four built-in parameter types are:
• StringParameter
• IntegerParameter
• RealParameter
• LogicalParameter
Built-In StringParameter Syntax
The syntax for the built-in type StringParameter is:

PARAMETER StringParameter
Description AS String("");
Value AS String("");
END

Description ...................A string of text that contains summary or help information


on the string parameter
Value..............................A string of text that contains the default value of the string
parameter

Built-In IntegerParameter Syntax


The syntax for the built-in type IntegerParameter is:

PARAMETER IntegerParameter
Description AS String("");
Value AS Integer(0);
Upper AS Integer(32767);
Lower AS Integer(-32767);
END

Description ...................... A string of text that contains summary or help


information on the integer parameter
Value................................. The default value of the integer parameter
Upper................................ The upper bound for the integer parameter
Lower................................ The lower bound for the integer parameter

Modeling Language Reference Modeling Language Concepts • 1-25


Built-In RealParameter Syntax
The syntax for the built-in type RealParameter is:

PARAMETER RealParameter
Description AS String("");
Value AS Real(0.0);
Upper AS Real(1.0e37);
Lower AS Real(-1.0e37);
PhysicalQuantity AS String("");
Tag AS String;
END

Description ...................... A string of text that contains summary or help


information on the real parameter
Value ................................ The default value of the real parameter
Upper................................ The upper bound for the real parameter
Lower ............................... The lower bound for the real parameter
PhysicalQuantity ............. A string of text that contains the name of the physical
quantity definition used by the real parameter
Tag.................................... Label for use in interfaces to online applications

Built-In LogicalParameter Syntax


The syntax for the built-in type LogicalParameter is:

PARAMETER LogicalParameter
Description AS String("");
Value AS Logical("TRUE");
END

Description ...................... A string of text that contains summary or help


information on the parameter
Value ................................ The default value of the logical parameter

1-26 • Modeling Language Concepts Modeling Language Reference


Built-In Solved Type
The built-in type RealVariable represents variables that can be
solved for in a simulation.

Built-In Solved Type Syntax

VARIABLE RealVariable
Value AS Real(1.0);
Upper AS Real(1.0e37);
Lower AS Real(-1.0e37);
Scale AS Real(1.0);
Derivative AS Real;
IsConnected AS Logical("FALSE");
IsMatched AS Boolean;
Description AS String("");
PhysicalQuantity AS String("");
Units AS String;
ULagrange AS Real;
LLagrange AS Real;
Spec AS SpecType("FREE");
Tag AS String;
Record AS Boolean;
END

Value ....................... The default value of the real variable


Upper....................... The upper bound for the real variable
Lower ...................... The lower bound for the real variable
Scale........................ The scaling factor for the real variable
Derivative ................ The rate of change of the value with respect to time
IsConnected............ The logical property for testing whether the real
variable is connected in the flowsheet
IsMatched ............... Used to test whether connected ports have
equivalent variable names
Description ............. A string of text that contains summary or help
information on the real variable
PhysicalQuantity .... A string of text that contains the name of the
physical quantity definition used by the real variable
Units ........................ Current UOM symbol
ULagrange .............. Upper Lagrange
LLagrange............... Lower Lagrange
Tag........................... Label for use in interfaces to online applications
Record..................... Controls recording of history for a variable
Spec ........................ A string of text that contains the default
specification for the real variable.

Modeling Language Reference Modeling Language Concepts • 1-27


Built-In Solved Type Remarks
Only variables derived from the RealVariable type (also Slack
variables and PartialDerivatives) can be solved for in equations.
Parameters cannot be solved for in a simulation.
Other Built-In Types The other built-in types are:
• GenericModel
• GenericStream
• GenericPort
• GenericConnection
• GenericControlSignal
• ControlPort
• ConnectionPort
• SlackVariable

Built-In Model Type


The built-in model type GenericModel is the basis for each model
type you define. The definition of the built-in model type is:

MODEL GenericModel
Description AS String("");
Default_Form AS String("");
Current_Icon AS String("");
InputSignal AS INPUT ControlPort;
OutputSignal AS OUTPUT ControlPort;
ComponentList AS ComponentListName("Default");
END

Description .............. A string of text that contains summary or help


information on the model
Default_Form........... A string of text that contains the name of the
default form for the model
Current_Icon ........... A string of text that contains the name of the
current icon for the model
InputSignal .............. A port for use with manipulated variables in the
model
OutputSignal ........... A port for use with measured variables in the
model
ComponentList........ The default component list name for the model

1-28 • Modeling Language Concepts Modeling Language Reference


Built-In Stream Type
The built-in stream type GenericStream is the basis for each stream
type you define. The definition of the built-in stream type is:

STREAM GenericStream
Description AS String("");
Default_Form AS String("AllVariables");
Current_Icon AS String("System");
InputSignal AS INPUT ControlPort;
OutputSignal AS OUTPUT ControlPort;
ComponentList AS ComponentListName("Default");
END

Description .............A string of text that contains summary or help


information on the stream
Default_Form ..........A string of text that contains the name of the default
form for the stream
Current_Icon...........A string of text that contains the name of the current
icon for the stream
InputSignal .............A port for use with manipulated variables in the stream
OutputSignal...........A port for use with measured variables in the stream
ComponentList.......The default component list name for the stream

Built-In Connection Stream Type


The built-in stream type Connection is used for connecting ports
when you do not specify a stream. Connection is derived from the
built-in connection stream type GenericConnection.
The definition of the built-in connection stream type is:

STREAM GenericConnection
Description AS String("");
Default_Form AS String("AllVariables");
Current_Icon AS String("System");
Source AS INPUT ConnectionPort;
Dest AS OUTPUT ConnnectionPort;
END

Description ...........A string of text that contains summary or help


information on the stream
Default_Form ........A string of text that contains the name of the default
form for the stream
Current_Icon.........A string of text that contains the name of the current icon
for the stream
Source...................An input connection port
Dest .......................An output connection port

Modeling Language Reference Modeling Language Concepts • 1-29


Built-In ControlSignal Stream Type
The built-in stream type ControlSignal is used for connecting
variables through control ports. The built-in ControlSignal stream
type has no properties that are accessible from the modeling
language.

Built-In Port Type


The built-in port type, GenericPort is the basis for each port type
you define. The definition of the built-in port type is:

PORT GenericPort
Description as String("");
IsConnected AS LogicalParameter("FALSE");
ComponentList AS ComponentListName("Default");
END

Description .............. A string of text that contains summary or help


information on the port
IsConnected ............ The logical property for testing whether the
port is connected in the flowsheet
ComponentList........ The default component list name for the stream

Built-In Control Port Type


All blocks and streams have built-in control ports which become
available for connections when you declare a variable as an input,
an output, or both an input and output variable. You do not need to
define a control port yourself.
The definition of the built-in control port type is:

PORT ControlPort
Description AS String("");
IsConnected AS LogicalParameter("FALSE");
END

Description .............. A string of text that contains summary or help


information on the control port
IsConnected ............ The logical property for testing whether the
control port is connected in the flowsheet

1-30 • Modeling Language Concepts Modeling Language Reference


Built-in ConnectionPort Type
A connection port is used to connect to any other port that is not a
control port.
The definition of the built-in connection port type is:

PORT ConnectionPort
Description AS String("");
IsConnected AS LogicalParameter("FALSE");
Direction AS Integer(0);
END

Description ............. A string of text that contains summary or help


information on the control port
IsConnected............ The logical property for testing whether the
connection port is connected in the flowsheet
Direction ................. The integer value for direction

SlackVariable Type
The built-in type SlackVariable represents variables that can be
applied as constraints to other variables and expressions. The lower
bound of SlackVariable is zero and so slack values in an
expression can never become negative.
The syntax for the built-in slack variable type is:

VARIABLE SlackVariable
Value AS Real(1.0);
Description AS String("");
LLagrange AS Real;
Tag AS String;
END

Value ........................ The default value of the real variable


Description .............. A string of text that contains summary or help
information on the real variable
LLagrange................ Lower Lagrange.
Tag............................ Label for use in interfaces to online
applications

Modeling Language Reference Modeling Language Concepts • 1-31


1-32 • Modeling Language Concepts Modeling Language Reference
2 Modeling Language for
Simulations

This chapter describes the following:


• Using units of measurement
• Defining tasks
• Using task statements
• Defining an Estimation simulation
• Defining an optimization simulation
• Defining a homotopy simulation
For information on defining types, models, and flowsheets, see
Chapters 3 to 5 respectively. Modeling Language for Types,
Modeling Language for Models, and Modeling Language for
Flowsheets.

Modeling Language Reference Modeling Language for Simulations • 2-1


Using Units of Measurement
You can define any number of units of measurement (UOM), and
conversions between the different units of measurement. You can
group together units of measurement in sets and make these sets
available automatically when you start a simulation session or load
a new simulation.
Simulation calculations are based on the base units of
measurement. Consequently, you must ensure that the base units of
measurement are consistent for all model equations. Tasks always
work in the base units of measurement.
Important When you write your own variable types and models,
you are implicitly defining the base units of measurement.
The user interface converts between the current UOM and the base
units of measurement. This means that plots and tables are
displayed in the chosen UOM and input values are converted to the
base units of measurement.
To determine the current units of measurement, you can either
select a unit of measure set or set the Units attribute of individual
variables. You can also use scripts and automation to work through
the conversion process.
The base units of measurement symbol is defined by a physical
quantity, and units of measurement conversions are associated with
a physical quantity. A variable type is associated with a physical
quantity by assigning the name of the quantity to the Physical
Quantity attribute in the variable type definition. Variables are
displayed in base units if no conversion is available for its
specified physical quantity.
The Modeler library works in Metric base units. Sets of
conversions to other units of measurement are available for you to
use. You can edit these conversion sets, or add your own
completely new UOM set. To perform these operations, you must
use automation methods from a script. The methods you use are:

2-2 • Modeling Language for Simulations Modeling Language Reference


Automation Method Description

AddUomSet Adds a unit of measure set


AddPhysicalQuantity Adds a physical quantity to the system and
specifies its units of measurement
DefineConversion Defines a conversion between base units and a
unit of measure
DefaultDisplayUOM Defines the units of measurement in which a
physical quantity is displayed, for an existing
units of measurement set
SelectUomSet Enables you to select an existing unit of measure
set
ConvertToBaseUom Converts a value from your current unit of
measure to your base unit of measure
ConvertFromBaseUom Converts a value from your base unit of measure
to your current unit of measure

Note A units of measurement set is a named collection of


conversions between defined units and base units.
Specifying a Physical To specify the physical property that a variable uses, you can
Quantity for Variables assign a string of text to the variable type property
PhysicalQuantity. You can also assign a string of text to
PhysicalQuantity for a real parameter type. The physical quantity:
• Defines the base unit of measure symbol used by the
variable
• Has associated with it the relevant unit of measure
conversions

Syntax for Defining a Physical Quantity


The syntax for defining a physical quantity for a variable or
parameter is:

PhysicalQuantity : "PhysQuanName";

PhysQuanName............... Name of a physical quantity

Physical Quantity Examples

The following example shows how the physical quantity for the
variable type Temperature is assigned "Temperature".

Modeling Language Reference Modeling Language for Simulations • 2-3


VARIABLE Temperature
Value : 25.0;
Lower : -273.15;
Upper : 400;
PhysicalQuantity : "Temperature";
END
The following example shows how to define the physical quantity
for a parameter that represents a distillation column tray spacing:
PARAMETER TraySpacing USES RealParameter
Value : 0.75;
PhysicalQuantity : "Length";
END
MODEL Column
TS AS TraySpacing;
.
.
END
Defining Physical You can define physical quantities and different sets of units of
Quantities, Units of measurement, so that you can, for example, convert between SI,
Measurement, and metric, English, and your own sets of units of measurement. You
Conversions define the physical quantities, units of measurement, and the
conversions between them by writing a Visual Basic® script. The
Visual Basic Script you write uses the Automation interface to
create the physical quantities, units of measurement, and associated
conversions.

Defining the Variables for the UOM Sets


Before you start to create the physical quantities and define the
conversions, you need to define two variables in the Visual Basic®
script. These variables are used with the UOM utility methods and
properties and you can name them as you choose.
Syntax for Defining Variables

DIM xUom
SET xUom = ActiveDocument.uom

xUom ................................ A Visual Basic variable. You can choose to call this
variable whatever you want.
ActiveDocument .............. The current simulation path in the automation
interface
ActiveDocument is equivalent to the path Application.Simulation,
so alternatively you could write:

DIM xUom
SET xUom = Application.Simulation.uom

2-4 • Modeling Language for Simulations Modeling Language Reference


Defining Physical Quantities
To use units of measurement, you need to define the physical
quantities used in your simulation.

Syntax for Defining Physical Quantities


The syntax for defining a physical quantity is:

AnyVar = xUom.AddPhysicalQuantity("PhysicalQuantityName",
"BaseUnitSymbol", AspenPlusQuantity, AspenPlusUnit)

AnyVar, xUom.................. Previously defined Visual Basic® variables. Can be


any name you choose.
PhysicalQuantityName.... The name of the physical quantity
BaseUnitSymbol.............. The symbol for the base units of measurement for this
physical quantity
AspenPlusQuantity ......... The integer number of the corresponding physical
quantity in Aspen Plus®, as entered in the Aspen Plus
file rcunits.dat.
AspenPlusUnit................. For the given Aspen Plus physical quantity, this is the
integer number of the Aspen Plus unit that matches the
base units for the physical quantity.
Note AspenPlusQuantity and AspenPlusUnit are optional and are
only used if you export models from Aspen Custom Modeler for
use in Aspen Plus.

Physical Quantity Example


The following example adds physical quantities for length and
temperature with base units of measurement of meters and degrees
Celsius respectively.

AnyVar = xUom.AddPhysicalQuantity("Length", "m")


AnyVar = xUom.AddPhysicalQuantity("Temperature",
"C")

Defining Conversions between the Units of Measurement


After defining the physical quantities and base units used in your
simulation, you need to define additional units of measurement. A
unit of measure consists of a symbol and a conversion to base
units.

Modeling Language Reference Modeling Language for Simulations • 2-5


Syntax for Defining Conversions between Units of
Measurement
The syntax for defining the conversion is:

AnyVar = xUom.DefineConversion("PhysicalQuantityName",
"UomSymbol", Multiplier, Offset)

AnyVar, xUom.................. Previously defined Visual Basic® variables. Can be


any name you choose
PhysicalQuantityName.... Name of a previously defined physical quantity
UomSymbol ..................... The symbol of the UOM to which you are making
the conversion from the base UOM
Multiplier .......................... The factor by which you need to multiply the UOM
value to convert to the base UOM value
Offset................................ The difference you need to make to the UOM value
to convert to the base UOM value

The conversion is made using the Multiplier and Offset in the


following equation:
BaseUnit = Multiplier * UomSetNameUnit + Offset

Units of Measurement Conversion Remarks


The conversion definition determines the conversion between the
base unit of measure for the physical quantity, and the declared
units of measurement. The conversion is associated with a variable
by the physical quantity specified in the variable's type definition.

Units of Measurement Conversion Example


The following example defines conversions for the physical
quantities Temperature and Length. The base units of measurement
defined in the physical quantity definitions are "C" for temperature,
and "m" for length.
AnyVar = xUom.DefineConversion("Temperature", "K",
1.0, -273.15)
AnyVar = xUom.DefineConversion("Temperature", "F",
0.5556, -17.7778)
AnyVar = xUom.DefineConversion("Length", "ft",
0.3048, 0.0)

2-6 • Modeling Language for Simulations Modeling Language Reference


Creating Units of Measurement Sets
Units of measurement sets enable you to group together related
units of measurement. The automation method AddUomSet
enables you to add a new UOM set name to your simulation. You
can create a new UOM set using the following syntax in a Visual
Basic® script:

Dim xUom, AnyVar


AnyVar = xUom.AddUomSet("UomSetName")

AnyVar, xUom .................. Previously defined Visual Basic® variables.


UomSetName................... The name you give to a UOM set

Creating Units of Measurement Sets Example


The following example creates three different units of
measurement sets: for SI units, metric units, and English units.
After these UOM sets are defined, you can define the conversions
between the units of measurement.
AnyVar = xUom.AddUomSet( "SI" )
AnyVar = xUom.AddUomSet( "Metric" )
AnyVar = xUom.AddUomSet( "Eng" )
Note You can use the full path for the Uom utility instead of
defining a local Visual Basic® variable. For example:
AnyVar = Application.Simulation.Uom.AddUomSet(
"SI" )
or
AnyVar = ActiveDocument.Uom.AddUomSet( "SI" )
If you define xUom once, you can save typing the full path each
time.

Defining the Displayed Units of Measurement for the Units of


Measurement Set
After you have created a units of measurement set, you can choose
a units of measurement symbol for each physical quantity. These
are the units of measurement symbols that will be displayed when
the units of measurement set is selected.

Modeling Language Reference Modeling Language for Simulations • 2-7


Syntax for Defining the Displayed Units of Measurement
The syntax for defining the displayed units is:

AnyVar = xUom.DefaultDisplayUOM( "UOMSet",


"PhysicalQuantityName", "UomSymbol")

AnyVar, xUom.................. Previously defined Visual Basic® variables. Can


be any name you choose.
UomSet............................. The name you gave to a previously defined UOM
set
PhysicalQuantityName.... The name of the previously defined physical
quantity
UomSymbol ..................... The symbol of the UOM (for the physical quantity)
that you want to display for the UOM set
Note If a default display unit of measure is not specified for a
UOM set and physical quantity, then that physical quantity will be
displayed in the base units for that UOM set.

Defining the Displayed Units of Measurement Example


The following example shows how to define the displayed units:
AnyVar = xUom.DefaultDisplayUOM( "Eng", "Length",
"ft" )

Selecting a Units of Measurement Set for the Simulation


You can select the units of measurement set for your simulation in
three ways:
• In a Visual Basic® script:

xUom.SelectUomSet("UomSetName")

• In the OPTIONS definition:

OPTIONS
CurrentUomSet : "UomSetName";
.
END

• From the Tools menu in the GUI

2-8 • Modeling Language for Simulations Modeling Language Reference


Selecting a Units of Measurement Set Examples
The following example shows how to switch to the English units
of measurement set, using a Visual Basic® script:
xUom.SelectUomSet("Eng")
The following example shows an OPTIONS definition that
determines the current UOM set for the simulation:
OPTIONS
PrintLevel : None ;
CurrentUomSet : "Eng" ;
.
.
END

Running the Units of Measurement Script Automatically


You can ensure that the Visual Basic® units of measurement script
runs automatically each time you start a simulation session or load
a new simulation. This means you can write a script that defines all
the units of measurement sets and conversions you need and ensure
that the conversions are available each time you run a simulation.
To create a UOM script that runs automatically, you need to save
the script text to a file called:
OnNewDocumentScript.vb
You must place this file in the bin directory of your installation.
For example:
C:\Program Files\AspenTech\Aspen Custom Modeler
11.1\bin

Converting Between Units of Measurement


You can convert values in Microsoft® Visual Basic® scripts
between your base units of measurement and your current units of
measurement.
Syntax for Converting Between Units of Measurement
Use the following syntax in your Visual Basic Scripts:

xUom.ConvertToBaseUom (BaseUomText, CurrentUomValue)

and

xUom.ConvertFromBaseUom (BaseUomText, BaseUomValue)

BaseUomText .................. The base unit of measure text, in quotes


CurrentUomValue............ The value of the variable in the currently selected unit
of measurement
BaseUomValue ................ The value of the variable in the base unit of measure

Modeling Language Reference Modeling Language for Simulations • 2-9


Converting Between Units of Measurement Example
In this Microsoft® Visual Basic® script example, the current
UOM set is English units and the base UOM set is metric. A value
of temperature of 60 Celsius is converted to the current
temperature unit of measure, Fahrenheit. A value of length of 5280
feet is converted to the base unit of measure, meters.

Dim TempInF, LengthInMeters, xUom


Set xUom = Application.Simulation.Uom
TempInF = xUom.ConvertFromBaseUom( "C", 60.0)
LengthInMetres = xUom.ConvertToBaseUom( "m",
5280.0)

Using the Units of Measurement of a Control Variable


You can define a variable to take the units of measurement of a
variable from a different block on the flowsheet, connected to the
current block by a control variable.
Variables that can take any unit of measure can automatically be
assigned a unit of measure depending on what variable unit of
measure is connected to a control variable.
You can use the units of measurement of another variable in a
model definition or a flowsheet constraints definition.

Syntax for Using the Units of Measurement of a Control


Variable
Use the following syntax:

MODEL
VariableName1 AS VariableType1;
VariableName2 AS VariableType2 (..., UseUOMOf
:"VariableName1");

END

2-10 • Modeling Language for Simulations Modeling Language Reference


Example of Using the Units of Measurement of a Control
Variable
This example shows how other variables in a controller model can
take the units of measurement of a variable in a different block that
is connected to a control variable.

MODEL PI_Controller
.
Pv AS INPUT Control_Signal;
PvMin AS Control_Signal (Fixed, UseUOMOf : "Pv");
PvMax AS Control_Signal (Fixed, UseUOMOf : "Pv");
.
END
In this example, if a variable of type Temperature is connected to
the input control variable Pv with the built-in ControlSignal stream
type, the variables Pv, PvMin and PvMax are all displayed with the
same units as the variable of type Temperature.

Accessing Variable Values in Alternative UOMSets


You can access the values of variables in alternative UOMSets
from the current UOMSet through automation.
This means you can access variable values in a Microsoft® Visual
Basic® Script in a different unit of measure and use the alternative
unit of measure for intermediate calculations or results output.
Syntax
The syntax for a script at Flowsheet level is:

BlockName.VariableName.Value("UOMName")

The syntax for the script at Model level is:

VariableName.Value("UOMName")

BlockName....................... Name of a block on your flowsheet


VariableName .................. Name of a block variable
Value ................................ Value property of a variable
UOMName ........................ A string qualifier that can take the following options:
The

BaseUnits Returns the value with the unit of


measure defined as the
BaseUOMSet
CurrentUnits Returns the value with the unit of
measure defined as the
CurrentUOMSet or the
SelectUOMSet
"UnitName" Name given to a unit of measure

Modeling Language Reference Modeling Language for Simulations • 2-11


Examples of Accessing Variable Values in Alternative
UOMSets
For a Visual Basic Script at Flowsheet level:

Application.PrintToMessageWindow "Temperature in
base units is " + B1.Out1.Temp("BaseUnits")
Application.PrintToMessageWindow "Temperature in
current units is " + B1.Out1.Temp("CurrentUnits")
Application.PrintToMessageWindow "Temperature in
Celsius is " + B1.Out1.Temp("C")
Application.PrintToMessageWindow "Temperature in
Fahrenheit is " + B1.Out1.Temp("F")
If the BaseUOMSet is metric and the CurrentUOMSet is US units,
the output from the script is:

Temperature in base units is 22.2222


Temperature in current units is 72
Temperature in Fahrenheit is 72
Temperature in Celsius is 22.2222

Advanced Use of the UseUOMOf Property


The UseUOMOf property is used to declare that one variable uses
the same units of measurement of another variable. For
introductory information on the UseUOMOf property, see Using
the Units of Measurement of a Control Variable on page 2-10. The
UseUOMOf property is also capable of more complex
associations.

Using Variables whose UOM is Produced from the UOMs of


Other Variables
You can use the UseUOMOf property for a variable whose UOM
is a product or division of the UOMs of other variables.

2-12 • Modeling Language for Simulations Modeling Language Reference


Example of Using Variables whose UOM is Produced from the
UOMs of Other Variables
The following example is a control model that calculates the ratio
and product of two inputs:
Model RatioBlock
input1 as input RealVariable(fixed, UseUOMOf:
"input2");
input2 as input RealVariable(fixed, UseUOMOf:
"input1");

ratio as output RealVariable(UseUOMOf:


"input1/input2");
prod as output RealVariable(UseUOMOf:
"input1*input2");

ratio*input2 = input1;
prod = input1*input2;
End

Notes
• Input1 is declared as using the UOM of input2, and vice
versa. This is allowed so that whichever of input1 or input2
is connected the appropriate units will come from that
connection.
• The 'ratio' variable is declared as using the UOM of input1
divided by input2. If, for example, input1 is connected to a
temperature variable displaying in Fahrenheit and input2 to
a length variable displaying in feet, the display units of
measurement will be Fahrenheit/ft. Note that in this case the
conversion for display units to base units (Centigrade/meter)
will not include the offset between Fahrenheit and
Centigrade: only the scaling is applied.
• The 'prod' variable is handled in a similar way to the ratio
variable except in this case a "*" is used to reflect the
multiplication operation.

Modeling Language Reference Modeling Language for Simulations • 2-13


Applying only Scaling to a Variable
You can use UseUOMOf to apply scaling only to a variable.

Example of Applying only Scaling to a Variable


The following example is control model that calculates the
difference between two variables:

Model RatioBlock
input1 as input RealVariable(fixed);
input2 as input RealVariable(fixed);

diff as output RealVariable(UseUOMOf: "ScaleOf:


input1");

diff = input1 - input2;

End

In this example, if the 'diff' variable was simply declared to use the
UOM of input1 then when converting to display units, the
conversion offset would be inappropriately applied (for example, a
zero Centigrade temperature difference would be converted to 32.0
in Fahrenheit). To ensure that only the scale is applied, this
example uses the "ScaleOf:" qualifier before the name of the
variable.

2-14 • Modeling Language for Simulations Modeling Language Reference


Defining Tasks
A task is a set of instructions that you create in Aspen Custom
Modeler™. You can use tasks to define a sequence of actions that
take place during a dynamic simulation. For example, you can use
tasks to:
• Define disturbances in feed conditions and discontinuities
that modify a fixed variable during a dynamic run
• Trigger events when certain conditions are met. For
example, you can use a task to provide basic level control in
a tank by closing an output valve when the fluid level falls
below a certain value.
You can define two kinds of tasks:

Task Type Started By Explorer Icon

Event-driven A conditional expression

Callable Being called from other tasks, either


an event-driven task or another
callable task.
Does not have a start condition.

Important To use callable tasks, your simulation must contain at


least one event-driven task.
There are three locations where you can define a task:

Location Can be Event-Driven Can be Callable

Model Yes Yes


Flowsheet Yes Yes
Library Task folder No Yes
You can use event-driven tasks to define a model’s response to an
event in a simulation. Event-driven tasks are associated with a
defined event and execute when that event occurs. You can
associate tasks with events arising from the solution of a
simulation, such as variables reaching particular values or with
events triggered as the solver takes actions to solve the simulation.

Modeling Language Reference Modeling Language for Simulations • 2-15


The events with which a task may be associated are:

Event Example

A logical expression involving tank.level >= 2.5


variable values
A logical expression involving time Time==20.0

Model variables can appear on both sides of the conditional.


Constants must be on the right hand side of a conditional
expression.

The allowable comparison operators are >=, >, ==, <, <=, <>.
For time expressions you can use only >=, > or = =.
<> means not equal to.

Event-Driven Task Syntax


The syntax for an event-driven task is:

TASK TaskName RUNS ONCE WHEN Condition


TaskStatements
end

TaskName ........................ Name of the task


Condition ......................... A logical expression testing the value of simulation
variables (including time)
ONCE Optional keyword (see following Remarks)
TaskStatements............... The sequence of task statements that are executed
when the task is triggered.
You can also use the following system generated events to trigger
your tasks:-
• BEFORE INITIALIZATION
• AFTER INITIALIZATION
• BEFORE STEP
• AFTER STEP
• AFTER ERROR

The associated task triggers when the system generated event


occurs. That is; before or after simulation initialization, before or
after a dynamic run takes a step, or when any error occurs.

Note You cannot define an event-driven task to take call


parameters.

2-16 • Modeling Language for Simulations Modeling Language Reference


Event-Driven Tasks Remarks
A task without the optional keyword ONCE always remains active.
This means that whenever the RUNS WHEN condition changes
from false to true, the task is started.

If you include the ONCE keyword in the task activation condition,


the task is activated only once during the simulation. This means
you can model irreversible events.

Note You can also use a SWITCH statement in a model


definition to model an irreversible process.

Examples of Event-Driven Tasks


In the first example, at time 5.0, the flow to a vessel is set to zero.
The tank empties until the fluid level is below 0.01, when the inlet
flow is resumed.
TASK test1 RUNS WHEN TIME ==5.0
Input1.Flow : 0.0;
WAIT FOR Level <= 0.01;
Input1.Flow : 5.0;
END

In the second example, the inlet flow is set to 3.0 when the level is
below 0.01. This can happen at any time in the simulation. In the
first example, the inlet flow can only be set to 3.0 after the time
conditional has been met.
TASK test2A RUNS WHEN TIME == 5.0
Input1.Flow : 0.0;
END
TASK test2B RUNS WHEN Level <= 0.01
Input1.Flow : 3.0;
END

In the following example, the event-driven task is defined to run


once only. In this case a bursting disk is modeled so that once the
burst pressure is exceeded, the disk remains open:
TASK Burst RUNS ONCE WHEN Tank.Press > 9.0
Valve.CV : 1.0E6 ;
END
Finally, in this example, the associated task triggers after an
initialization occurs.
Task mytask RUNS AFTER INITIALIZATION
Input.Flow : 5.0;
END

Modeling Language Reference Modeling Language for Simulations • 2-17


Callable Tasks Callable tasks are called by other tasks instead of being triggered
by an event. You can optionally define callable tasks with
parameter call lists, with the calling task passing the parameter
values.
You can make calls to tasks within models, to tasks in a task
folder, or other tasks in your flowsheet. You cannot call a task in a
model from a flowsheet task, and you cannot call tasks in the
flowsheet from a task in a model or task folder.

Callable Task Syntax


The syntax for a callable task is:

TASK TaskName ( ParameterList )


TaskStatements
end

TaskName ........................ The name of the task. The name must be unique in
the scope in which the task is defined.
ParameterList .................. An optional list of the parameters passed to this
task from the expression that calls the task.
TaskStatements............... The task statements that are executed when the
task is run.
Use a CALL statement to call another task.

CALL Statement Syntax


The syntax for the CALL statement is:

CALL TaskName (ParameterList);

TaskName ........................ The name of the task being run


ParameterList .................. An optional list of assignments to local task
parameters

2-18 • Modeling Language for Simulations Modeling Language Reference


Example of a Callable Task
The following example shows two callable tasks being called from
an event-driven task:

TASK SubTaskA
Input1.Flow : 4.0;
END
TASK SubTaskB
Input1.Flow : 1.0;
END
TASK Test RUNS WHEN Time == 1.0
Input1.Flow : 5.0;
WAIT FOR Level >= 3.0;
CALL SubTaskB;
WAIT FOR Level <= 0.4;
CALL SubTaskA;
END

Callable Task Parameter Lists


You can pass parameters from a task to a callable task, so that any
variable names or calculated values can be passed from one task to
another. This means that you can call tasks down many levels and
retain information from one task to another. Typically you can use
parameterized tasks to create generic tasks that are not dependent
on a particular block name and pass information that is specific to
a block to that generic task.
Parameterized Task Syntax
The ParameterList described in Callable Tasks takes the following
syntax:

(Parameter AS Parameter; Variable AS RealVariable; ...)

Note To make sure callable tasks work correctly in all


circumstances, remember to use unique parameter and variable
names in the tasks in the hierarchy.

Callable Task Parameters Example


The example shows how you can write a callable task that takes
parameters from the task calling the callable task. The information
passed to the callable task in this case is the name of a variable to
be ramped, the target value of the ramp, the duration the ramp
takes to attain the target value and the type of ramp used. The task
GenericRamp can be called from any model task or from a
flowsheet task.

Modeling Language Reference Modeling Language for Simulations • 2-19


TASK GenericRamp ( VarName AS RealVariable;
Target AS RealParameter; Period AS RealParameter;
RampType AS StringParameter)
IF RampType == "Linear" THEN
RAMP ( VarName, Target, Period );
ENDIF
IF RampType == "Scurve" THEN
SRAMP ( VarName, Target, Period );
ENDIF
END
TASK DoTheRamp RUNS WHEN B4.Level >= 10.0
TargetValue AS RealParameter(0.0);
RampDuration AS RealParameter(0.1667);
RampType AS StringParameter("Scurve");
CALL GenericRamp(VariableName, TargetValue,
RampDuration, RampType);
WAIT FOR B4.Level <= 1.0;
TargetValue: 4.25;
RampDuration: 0.2;
RampType: "Linear";
CALL GenericRamp(B1.Inlet.Flow, TargetValue,
RampDuration, RampType);
END
Tasks and Rewinding Rewinding or restarting your dynamic simulation affects the status
Simulations of your active tasks. If a task is triggered before the beginning of
the rewind time, it is not triggered again if you run the simulation
from the rewind time. If you restart or rewind the simulation to
time zero, it is as if no tasks have been triggered.
Tasks can run in two ways. They can:
• Run and complete
• Remain running for an interval of time
Tasks that remain running for a time include tasks with WAIT
statements, or ramps, for example.
When you rewind a simulation, avoid rewinding into periods where
tasks were running over intervals of time. You will find that these
tasks will restart, so ramps will ramp once more from their starting
point, and WAITs will not proceed logically from the history of a
WAIT sequence.
Tasks and Opening The history of the sequence of events is not restored when you
Simulations open a previously saved simulation after a dynamic simulation.
This means that a task designed to run once may run again, even if
it ran in dynamic simulation during the previous session. It also
means that the state of tasks which run over many time intervals
due to waits and ramps will not be restored to their previous state.
Allow tasks to complete before saving dynamic simulations, or
explicitly deactivate unwanted tasks when you open a simulation,

2-20 • Modeling Language for Simulations Modeling Language Reference


before you run it. Alternatively, restart and rerun your simulation to
regenerate the true event history of your simulation.
An active task is restored from a binary document (.acmd) save
when you open a previously saved simulation in which the task
was active at the time of the save. An active task is not restored
from a language (.acmf) file.

Using Task Statements


A task statement can be any of the statements that perform the
following tasks:
• Assigning a value to a variable
• Defining a conditional equation on the value of a simulation
variable
• Ramping the value of a simulation variable
• Suspending and restarting a task
• Creating snapshots
• Executing parallel tasks
• Printing
• Suspending a simulation
• Invoking a script from a task
You can use tasks to make input disturbances, pause the simulation
depending on simulation variables, and build in a level of
intelligence to a model.
Assigning a Value to You can define parameters and sets that are local to a particular
a Variable in Tasks task. The syntax is the same for defining parameters and sets in
models.
The local variables and sets you can create within a task are:
• IntegerParameter
• RealParameter
• LogicalParameter
• StringParameter
• IntegerSet
• StringSet
For local parameters and model parameters, you can assign values
to local parameters, model parameters, and model variables using
the : (colon) assignment operator.
Note A task in a model can assign values to variables that do not
appear in a model equation. Because these variables are not active,
they do not appear in the AllVariables table.

Modeling Language Reference Modeling Language for Simulations • 2-21


Example of Assigning a Value to a Variable
The following example shows how a value is assigned to a
variable:

TASK Test3 RUNS WHEN h < 0.001

Flowin.flow: 10.0;
Flowin.temp: 50.0;
END

Defining a You can define a conditional equation on the value of a simulation


Conditional Equation variable or a task parameter. To do this, use the IF statement to
on the Value of a define a test on the value of a variable or parameter and to describe
Simulation Variable in alternative execution paths.
Tasks
Example of Defining a Conditional Equation
The following example shows defining a conditional equation on
the value of a simulation variable:

TASK Test3 RUNS WHEN h < 0.001


IF Flowin.flow <=0.1 THEN
Flowin.flow: 10.0;
ELSE
Flowin.flow: 1.0;
ENDIF
END
Ramping the Value of The task language supports two built-in ramp functions that you
a Simulation Variable can use to change the value of a variable over a period of time.
in Tasks
Ramp Function Syntax

RAMP(variable, target, period, ramptype);


SRAMP(variable, target, period, ramptype);

variable............................. The name of the variable whose value is to be altered.


This must be a variable whose specification is fixed.
target ................................ The value to which the variable’s value is to be
changed
period ............................... The amount of time over which the ramp operates
ramptype .......................... Can be either DISCRETE or CONTINUOUS.
DISCRETE ramps are re-calculated at communication
points only.
CONTINUOUS ramps are re-calculated whenever the
integrator moves its time. Continuous ramps incur a
performance penalty, but may be considerably more
accurate when used with a variable step integrator.
The ramptype may be omitted; the default ramptype is
DISCRETE.

2-22 • Modeling Language for Simulations Modeling Language Reference


Modeling Language Reference Modeling Language for Simulations • 2-23
RAMP is a linear ramp function whereas SRAMP is a sinusoidal
ramp, which gives an S-shaped curve for the ramped variable. With
SRAMP, if the ramp is decreasing the value of a variable then the
ramp follows the shape of a sinusoidal curve between 0 and pi. If
the target is an increase then the curve follows the shape of a
sinusoidal curve between pi and 2pi.
Note The period of a discrete ramp must be greater than the
Communication Interval for the dynamic simulation. The
Communication Interval is the interval at which results are
updated. If you set a ramping period less than the Communication
Interval, the ramping function is ignored.

Example of Ramping the Value of a Variable


The following example shows the use of ramping:
TASK Task4 RUNS WHEN TIME == 4.0
RAMP (Input1.flow, 5.0, 2.0);
/* Flow changes to 5.0 linearly over a period of
2 time units */
SRAMP (Input1.temp, 15.0, 3.0);
/* Temperature changes with an S-shaped curve to
15.0 over a period of 3 time units */

Suspending and You can suspend the execution of a task until a particular condition
Restarting a Task is met. You can use the following statements to suspend a task:

Statement Use

WAIT real-expression Suspends the execution of task statements


for the number of time units represented by
real-expression. You can also use a WAIT
FOR statement.
WAIT FOR condition Suspends the execution of task statements.
When the WAIT FOR condition is met, the
task continues with the statement following
the WAIT FOR statement.
RESTART AFTER real- Suspends the execution of a task for the
expression number of time units represented by real-
expression. You can also use a RESTART
WHEN statement.
RESTART WHEN condition Suspends the execution of a task. When the
RESTART WHEN condition is met, the
task starts again with the first statement in
the task.

2-24 • Modeling Language for Simulations Modeling Language Reference


WAIT Syntax
The syntax for the WAIT statement is:

WAIT real-expression;

real-expression................ The number of time units for which to wait (that is, a
relative time)

WAIT FOR Syntax


The syntax for the WAIT FOR statement is:

WAIT FOR condition;

condition .......................... A logical expression that describes the condition


that enables the task to continue from the
statement after the WAIT FOR statement

RESTART AFTER Syntax


The syntax for the RESTART AFTER statement is:

RESTART AFTER real-expression;

real-expression................ The number of time units after which to restart the


task (that is, a relative time)

RESTART WHEN Syntax


A task can schedule itself to run again when a certain condition
occurs. The condition could test the value of a variable or it could
test simulation time. A task which schedules itself to run at fixed
intervals can be used to control a cycle. The syntax for the
RESTART WHEN statement is:

RESTART WHEN condition;

condition .......................... A logical expression that describes the condition that


restarts the task from the first task statement
Notes
• You can use RESTART WHEN in an event-driven task
only. You cannot use RESTART WHEN in a callable task.
• If a RESTART WHEN statement is called, no statements
below the RESTART WHEN statement can be processed.
Typically, a RESTART WHEN statement is the last
statement in a task definition.

Modeling Language Reference Modeling Language for Simulations • 2-25


Examples of Suspending and Restarting Tasks
The first example shows how to use a WAIT statement to suspend
a task:
TASK TurnOffFeeds RUNS WHEN TIME == 10
valve1.position: 0.0;
WAIT 0.2;
valve2.position: 0.0;
END
The following example shows the use of a WAIT FOR statement
that causes the task to pause until a condition becomes true.
The task starts when a fluid volume in a vessel falls below a certain
value. The feed flow rate to the task is immediately increased to
10.0 until the fluid volume in the tank reaches a certain value, at
which point the feed flow rate is returned to its original value:

TASK WaitForTest RUNS WHEN Tank1.Vol =< 0.5


OriginalFlow AS RealParameter;
OriginalFlow : Tank1.Input1.Flow;
Tank1.Input1.Flow : 10.0;
WAIT FOR Tank1.Vol >= 1.0;
Tank1.Input1.Flow : OriginalFlow
END
The next example shows how to use the RESTART AFTER
statement:

TASK BatchCycle RUNS WHEN TIME == 1


CALL ChargeReactor;
CALL ShutOffFeed;
CALL AgeReactor;
CALL DrainVessel;
RESTART AFTER 2;
END

The following example shows the use of a RESTART WHEN


statement.
The task starts running at a certain time. The feed flow rate ramps
up and the feed component molefractions are changed. Once a
certain level of ethanol is reached in the tank, the feed
compositions are changed and the flow rate ramps down. The task
now restarts, based on the level of ethanol in the tank. The cycle
carries on repeating.

2-26 • Modeling Language for Simulations Modeling Language Reference


TASK RestartWhenTest RUNS WHEN TIME == 10.0
RAMP ( Tank1.Input1.Flow, 10.0, 5.0 ) ;
Tank1.Input1.x("Water") : 0.1;
Tank1.Input1.x("Glucose") : 0.9;
WAIT FOR Tank1.Output1.x("Ethanol") >= 0.6;
Tank1.Input1.x("Water") : 1.0;
Tank1.Input1.x("Glucose") : 0.0;
RAMP ( Tank1.Input1.Flow, 1.0, 3.0 ) ;
RESTART WHEN Tank1.Output1.x("Ethanol") <= 0.05;
END
Creating Snapshots You can use a task to create a snapshot of the current values of the
in Tasks variables in the dynamic simulation.
You can use Snapshots to record the simulation values when a
certain process condition is reached.

CREATE SNAPSHOT Syntax


The syntax for creating snapshot is:

CREATE SNAPSHOT SnapshotName;

SnapshotName ................ The name of the snapshot that appears with the
automatically generated snapshot contained in the
snapshot file

Creating Snapshots Example


The following example shows how to create a snapshot at the
moment a process condition is reached. You can now rewind or
apply the values of all the variables in the simulation at the point
when the process condition is achieved.
TASK Task2 RUNS WHEN Time == 10.0
Flowin.flow : 5.0;
WAIT FOR Level >= 2.5;
CREATE SNAPSHOT "Task-Created Snapshot #1";
END
Executing Tasks in You can group together Call statements within a task and execute
Parallel the task Calls in parallel using the PARALLEL and
ENDPARALLEL construct. Each action is executed until it
completes. The parallel section completes when all actions in it are
complete.

Modeling Language Reference Modeling Language for Simulations • 2-27


PARALLEL Syntax
The syntax for grouping actions in parallel is:

PARALLEL
CALL Task1;
CALL Task2;
.
.
CALL Taskn;
ENDPARALLEL;

Taskn................................ The callable sub-task called in parallel

Example of Executing Tasks in Parallel


The following example shows how to use of PARALLEL /
ENDPARALLEL to call three sub-tasks simultaneously:

TASK P1
RAMP(Input1.Flow, 2.5, 4.0);
END
TASK P2
RAMP(Input2.Flow, 0.5, 5.0);
END
TASK P3
RAMP(Input3.Flow, 5.5, 3.0);
END
TASK Task1 RUNS WHEN TIME == 1.25
PARALLEL
CALL P1;
CALL P2;
CALL P3;
ENDPARALLEL;
Input4.Flow : 0.0;
END
All three Ramps start at time 1.25. The last task to finish is Task
P2, which completes at 6.25, at which time the flow rate of input4
changes to 0.0 instantaneously.
PRINT Statements in You can print a message from a task to the Simulation Messages
Tasks window.

PRINT Syntax

PRINT "Message to Simulation Messages Window"

2-28 • Modeling Language for Simulations Modeling Language Reference


PRINT Statement Examples
The following example shows the use of the print statement with a
task:
TASK Test3 RUNS WHEN Time == 1.0
PRINT "Start Task Test3";
RAMP (Input1.Flow, 2.5, 5.0);
PRINT "Task Test3 Finished";
END
The following example shows how to use CONVERTTO to
convert to a string:

task MyTask
s2 as StringParameter;
s2 : CONVERTTO(string, v); // where V is a
variable accessible to the task
print "variable v is "+s2;
//print CONVERTTO(string, v);// Note that
CONVERTTO cannot be used directly in a print
statement.
end
Pausing a Simulation You can use a PAUSE statements to suspend a simulation.
from a Task PAUSE Syntax
The syntax for suspending a simulation is:

PAUSE;

When a pause statement executes, the simulation is placed in a


paused state and the task executing the pause statement exits.

Example of Pausing a Simulation


The following example makes a step change to a variable, waits for
a process condition to be reached and then pauses the simulation:
TASK MyTest1 RUNS WHEN TIME == 5.0
FlowIn.Flow : 10.0;
WAIT FOR FluidHeight >= 4.5;
PAUSE;
END
Invoking a Script You can use the Invoke command within a task to invoke a script.
from a Task
Syntax for Invoking a Script
You can use the following syntax to invoke a script and wait for it
to complete:

invoke ScriptName;

Modeling Language Reference Modeling Language for Simulations • 2-29


The following syntax passes input parameters to the script which
will be available in the script as the Inputs collection:

invoke ScriptName(input1, input2, ...);

The following syntax also initializes the scripts Outputs collection


with the values output1, output2, and so on. On return this syntax
assigns the values in the returned outputs collection to output1,
output2, and so on.

invoke (output1, output2, ...) : ScriptName(input1, input2, ...);

Note Outputs must be property names: they cannot be values.


For more information on passing inputs to scripts and getting
outputs from scripts, see the Automation Reference.

You can also specify the location of the script to be invoked.

invoke Library. ScriptName;

This searches for the script in the Scripts folder under Custom
Modeling.

invoke Flowsheet. ScriptName;

This searches for the script in the Flowsheet.

invoke MyLibrary. ScriptName;

This searches for the script in the Scripts folder in the library called
MyLibrary. This library must be Open (attached) for the current
simulation.

By default the script is searched for in the same location as the


calling task.

2-30 • Modeling Language for Simulations Modeling Language Reference


Example of Invoking a Script from a Task
The following example uses a CalculateRamp script to determine
how far to ramp its variable:
task controlstep runs when time == 1.0
target as realparameter;
interval as realparameter;
invoke (target, interval) :
CalculateRamp("tank1.flowin.flow");

ramp(tank1.flowin.flow, target, interval);


end

The CalculateRamp script could take the form:


set var = Resolve(inputs(1))
outputs(1) = var.value * 2
outputs(2) = 3.0

Defining an Estimation Simulation


You can define steady-state and dynamic parameter estimation
simulations. You can also define steady-state data reconciliation
simulations.
For information on how to use the Estimation dialog box to define
Estimation simulations (which is the recommended method), see
the online Help on running Estimation simulations.
You can also use Microsoft® Visual Basic® to define your
estimated variable, steady-state, and dynamic experiments. You
can define your estimation simulation by using automation
methods and properties. The results of estimation simulations are
available through automation, so you can control and evaluate your
data in a Microsoft® Excel spreadsheet, for example.
For information on the options available for Estimation
simulations, see the Aspen Modeler Reference, Chapter 6.

Modeling Language Reference Modeling Language for Simulations • 2-31


Defining Estimated For information on how to use the Estimation dialog box to define
Variables Estimation variables (which is the recommended method), see the
online Help on running Estimation simulations.
You can also define your estimated variables using the following
automation method in Microsoft® Visual Basic®:

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
You can define a number of different variables to estimate in an
estimation simulation.
Note Estimated variables can be Fixed or Initial.

Defining Estimated Variables Example


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

Application.Simulation.AddEstimateVariable
"Reactor1.RK1"
Application.Simulation.AddEstimateVariable
"Reactor1.RK2"
Defining Steady-State For information on how to use the Estimation dialog box to define
Estimation steady-state Estimation experiments (which is the recommended
Experiments method), see the online Help on running Estimation simulations.
You can also use Microsoft® Visual Basic® automation methods
to define steady-state experiments for an estimation simulation. For
each experiment you must give an experiment name and define the
experiment as steady-state. You must also add measurement points
for the experiment, using the following syntax. You can also make
changes to the value of fixed variables for each experiment.

2-32 • Modeling Language for Simulations Modeling Language Reference


Syntax for Defining Steady State Estimation Experiments
Use the following Microsoft® Visual Basic® automation methods
to define your steady-state 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 ............................ Any name you give to this experiment


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

Remarks on Defining Steady-State Estimation Experiments


You can define any number of experiments. The experiments that
take part are those that have been added with the AddExperiment
method. This means you can define a number of experiments but
use only a selected number of the defined experiments. Also, this
means you can quickly test the effect of using different
combinations of experiments on the estimation simulation.
Note In a script for estimation, where quotation marks are nested
within quotation marks, you must use double pairs as shown in the
following example.
When the heteroscedasticity is not fixed, the Automation Method
AddSSMeasurepoint resets the heteroscedasticity parameter to 1.
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.

Modeling Language Reference Modeling Language for Simulations • 2-33


Example of Defining Steady-State Estimation Experiments
The following example shows two experiments being defined for a
simulation. Weightings on all measured data points and both
experiments are 1.0:

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

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

Application.Simulation.AddExperiment(SSExpt1)
Application.Simulation.AddExperiment(SSExpt2)
Defining Dynamic For information on how to use the Estimation dialog box to define
Estimation dynamic Estimation experiments (which is the recommended
Experiments method), see the online Help on running Estimation simulations.
You can also use Microsoft® Visual Basic® automation methods
to define dynamic experiments for an estimation simulation. 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.

2-34 • Modeling Language for Simulations Modeling Language Reference


Syntax for Defining Dynamic Estimation Experiments
Use the following Microsoft® Visual Basic® automation methods
to define your dynamic experiments:

DIM ThisExp
SET ThisExp = Application.Simulation.NewExperiment (
"ExperimentName", "Dynamic" )

ThisExp.AddDynMeasurePoint "BlockName.VariableName",
MeasurementTime, MeasuredValue, MeasurementWeight
.
ThisExp.AddFixedPoint "BlockName.VariableName", FixedValue
.
ThisExp.AddInitialPoint "BlockName.VariableName", InitialValue
.
ThisExp.AddRateInitialPoint "BlockName.VariableName",
RateInitialValue
.
ThisExp.SetWeight ExperimentWeight
Application.Simulation.AddExperiment(ThisExp)

ThisExp ............................ Any name you give to this experiment


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 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
InitialValue ....................... Value of a state variable at time zero of the
experiment
RateInitialValue ............... Value of a derivative of a state variable at time zero of
the experiment
MeasurementTime........... Time at which the MeasuredValue is taken during the
experiment
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

Remarks on Defining Dynamic Estimation Experiments


You can define any number of experiments. The experiments that
take part are those that have been added with the AddExperiment
method. This means you can define a number of experiments but
use only a selected number of the defined experiments. Also, this
means you can quickly test the effect of using different
combinations of experiments on the estimation simulation.

Modeling Language Reference Modeling Language for Simulations • 2-35


Tip To improve the speed of a dynamic estimation simulation,
from the Run menu click Run Options, and then set the
Communication time interval to a value equal to the total duration
of your experiment.
Notes
• In a script for estimation, where quotation marks are nested
within quotation marks, you must use double pairs as shown
in the following example.
• When using the RateInitialPoint method, make sure the
relevant variable has the RateInitial specification, otherwise
this will be ignored.
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("DynamicExpe
riment1","Dynamic")
DynExpt1.AddInitialPoint
"Reactor1.x(""CH3OH"")", 0.012
DynExpt1.AddFixedPoint "Reactor1.Temp", 200.0
DynExpt1.AddFixedPoint "Reactor1.Press", 12.5
DynExpt1.AddDynMeasurePoint "Reactor1.
x(""CH3OH"")", 0.1667, 0.019, 1.0
DynExpt1.AddDynMeasurePoint "Reactor1.
x(""CH3OH"")", 0.3333, 0.038, 1.0
DynExpt1.AddDynMeasurePoint "Reactor1.
x(""CH3OH"")", 0.5000, 0.044, 1.0

SET DynExpt2 =
Application.Simulation.NewExperiment("DynamicExpe
riment1","Dynamic")
DynExpt2.AddInitialPoint
"Reactor1.x(""CH3OH"")", 0.009
DynExpt2.AddFixedPoint "Reactor1.Temp", 200.0
DynExpt2.AddFixedPoint "Reactor1.Press", 12.5
DynExpt2.AddDynMeasurePoint "Reactor1.
x(""CH3OH"")", 0.1667, 0.008, 1.0
DynExpt2.AddDynMeasurePoint "Reactor1.
x(""CH3OH"")", 0.3333, 0.015, 1.0
DynExpt2.AddDynMeasurePoint "Reactor1.
x(""CH3OH"")", 0.5000, 0.029, 1.0

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

2-36 • Modeling Language for Simulations Modeling Language Reference


After entering a number of experiments, you may wish to change
Resetting Estimation
the data for the experiments and run the estimation again. After
Experiments
you have added an experiment under a particular name, you cannot
use this name again. Before you can add the new experiment, you
must reset the estimation simulation.
For information on how to use the Estimation dialog box to reset
Estimation experiments (which is the recommended method), see
the online Help on running Estimation simulations.
You can also use Microsoft® Visual Basic® automation methods
to reset Estimation experiments as described here.
Syntax for Resetting Estimation Experiments
Use the following Microsoft® Visual Basic® automation method
to reset your estimation experiments:

Application.Simulation.ResetEstimation

This automation method clears all the experiments from the


previous estimation simulation.

Example of Resetting an Estimation Experiment


The following example script enables you to repeatedly run the
script and run successive estimation runs. For example, you may
change the data in the script between successive estimation
simulations. Without the ResetEstimation command, you cannot
add the experiment SSExpt1 if this experiment has previously been
added.
SET SSExpt1 =
Application.Simulation.NewExperiment("Experiment1
","Steady State")
SSExpt1.AddFixedPoint
"Reactor1.In1.Flow(""ReagentA"")", 1.0
SSExpt1.AddFixedPoint
"Reactor1.In1.Flow(""ReagentB"")", 9.0
SSExpt1.AddSSMeasurePoint
"Reactor1.Out1.x(""ReagentA"")", 0.092, 1.0
SSExpt1.AddSSMeasurePoint
"Reactor1.Out1.x(""ReagentB"")", 0.904, 1.0
SSExpt1.SetWeight 1.0

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

Modeling Language Reference Modeling Language for Simulations • 2-37


Accessing Results of Estimation
Simulations
For information on how to use the Estimation dialog box to access
results of Estimation experiments (which is the recommended
method), see the online Help on running Estimation simulations.
You can also access the results of an estimation simulation through
the automation interface. This means you can display the results of
an estimation simulation to a Microsoft® Excel spreadsheet, for
example.
You can access:
• Individual estimated variable values
• Individual correlation values
• The complete correlation matrix
• Individual standard errors (also known as standard
deviations)
Caution The covariance, correlation, and standard error
information may not be reliable if:
• The estimated variables at the final point are near to or on
their bounds
– or –
• The fit to your measured data is poor
Accessing Estimated You can access the values of the estimated variables using the
Variables' Values following syntax.

Estimated Variable Syntax


The syntax for accessing estimated variables' values is:

EstimatedValue("EstVar1")

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

2-38 • Modeling Language for Simulations Modeling Language Reference


Dim EstVal1
EstVal1 =
Application.Simulation.EstimatedValue("Reactor.K1
")
Application.PrintToMessageWindow "Estimated value
for K1 is " & Cstr(EstVal1)
Accessing Standard After an estimation simulation is complete, you can access the
Errors 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

Deviation ("EstVar1")

EstVar1............................. The name of the estimated variable for which you


want the standard error

Example of Accessing Standard Errors


In this example, the standard error (also known as standard
deviation) of a variable is assigned to a Microsoft® Visual Basic®
variable value after a successful estimation run.
Dim StdDev
StdDev =
Application.Simulation.Deviation("Reactor.K1")
Application.PrintToMessageWindow "The standard
error for K1 is " & Cstr(StdDev)
Testing for Standard You can test to see if the standard error (also known as standard
Error Results deviation) results are available to download and view.
Syntax for Testing for Standard Error Results
Use the following syntax to find out whether standard error results
are available:

DeviationArrayPresent

The property DeviationArrayPresent returns a logical value.

Modeling Language Reference Modeling Language for Simulations • 2-39


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.PrintToMessageWindow "Standard
Error K1 = " &
Cstr(Application.Simulation.Deviation("Reactor
.K2"))
Application.PrintToMessageWindow "Standard
Error K2 = " &
Cstr(Application.Simulation.Deviation("Reactor
.K1"))
Application.PrintToMessageWindow "Standard
Error K3 = " &
Cstr(Application.Simulation.Deviation("Reactor
.K3"))
ELSE
Application.PrintToMessageWindow "Standard
Error results not available"
END IF
Accessing Individual After an estimation run has completed, you can access correlation
Correlation Results information either between two estimated variables, or you can
download the complete correlation matrix.
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 two estimated variables in the estimation


simulation

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 is printed to the Simulation Messages window.

Dim Corr
SET Corr =
Application.Simulation.Correlation("Reactor.K1",
"Reactor.K2")
Application.PrintToMessageWindow "Correlation
between K1 and K2 is " & Cstr(Corr)

2-40 • Modeling Language for Simulations Modeling Language Reference


Accessing the After an estimation simulation you can access the complete
Correlation Matrix correlation matrix of all 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 determined
by the number of estimated variables. The order of the estimated
variables is the order the estimated variables are 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.

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 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.PrintToMessageWindow "Correlation "
+ i + j + " = " Corr(i-1 ,j-1)
NEXT
NEXT

Modeling Language Reference Modeling Language for Simulations • 2-41


Testing for the You can test to see if the correlation matrix is present before
Correlation Matrix attempting to download the matrix.

Syntax for Testing for the Correlation Matrix


The following syntax is used to test whether the correlation matrix
is present:

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 a Microsoft® Visual Basic® array:

Dim Corr
IF Application.Simulation.CorrelationMatrix Present = True THEN
Corr = Application.Simulation.Correlation Matrix
ELSE
Application.PrintToMessageWindow "WARNING : Correlation Matrix
Not Present"
END IF

2-42 • Modeling Language for Simulations Modeling Language Reference


Defining an Optimization Simulation
Use optimization to calculate the maximum or minimum possible
value of a variable, given that the equations in the simulation need
to be solved. You can apply additional constraints to the values of
variables in your simulation to avoid the optimum solution giving
unrealistic figures.
For information on the solver options available for Optimization,
see the Aspen Modeler Reference, Chapter 6, and for information
on using automation to set up and control optimization
simulations, see the Aspen Modeler Reference, Chapter 4.

Syntax for Optimization Simulation


The following syntax is used for optimization simulations:

OPTIMIZATION
IsDynamic : TRUE|FALSE;
ElementSizeBoundsAutomatic : TRUE|FALSE;
TimeBoundsAutomatic : TRUE|FALSE;
EndTime : TimeValue;
VariableName : Objective;
VariableName : Control;
VariableName : Initial;
VariableName : Design;
Control.FinalTime_Upper : double value;
Control.FinalTime_Lower : double value;
Control.FinalTime_IsFixed : TRUE | FALSE;
Control.FinalTime_IsObjective : TRUE | FALSE;
Control.Elements : int value;
Control.FixedInterval : TRUE | FALSE;
Control.PiecewiseLinear : TRUE | FALSE;
Control.MaxInterval : double value;
Control.MinInterval : double value;
Control(index) : double value;
.
.
Control(index).VariableName : double disvalue ;.
Control.MaxMove.VariableName : double maxvalue, TRUE |
FALSE ;
End

Modeling Language Reference Modeling Language for Simulations • 2-43


Optimization .................... Keyword for optimization simulations
IsDynamic ........................ Can be True (dynamic optimization) or False
(steady-state optimization)
ElementSizeBoundsAutomatic .......Set to TRUE for default element size bounds to
be used and FALSE for the minimum and
maximum to be used defined by
Control.MaxInterval and Control.MinInterval.
TimeBoundsAutomatic... Set to TRUE for default lower and upper bounds
on the final time and FALSE to use manual
values specified by Control.FinalTime_Upper
and Control.FinalTime_Lower
EndTime........................... Keyword that enables you to set the end time of a
dynamic optimization
TimeValue ........................ End time of a dynamic optimization. Must be
greater than 0.
Objective.......................... Keyword signifying that the VariableName refers
to an Objective variable
Control ............................. Keyword signifying that the VariableName refers
to a Control variable
Initial ................................ Keyword signifying that the VariableName refers
to an Initial variable
Design .............................. Keyword signifying that the VariableName refers
to a Design variable
Control.FinalTime_Upper ................Upper bound for moving final time
Control.FinalTime_Lower................Lower bound for moving final time
Control.FinalTime_IsFixed Set to TRUE if final time is free; FALSE for
moving final time
Control.FinalTime_IsObjective .......Set to TRUE if final time is part of the objective
function; FALSE otherwise
Control.Elements ............ Number of control elements
Control.FixedInterval ...... Set to TRUE for fixed element sizes; FALSE for
moving element sizes (must be TRUE if
Control.FinalTime_IsFixed is FALSE).
Control.PiecewiseLinear Set to TRUE for a piecewise linear control
discretization and FALSE for a piecewise
constant control discretization.
Control.MaxInterval ........ Maximum element size bound (used for moving
elements if ElementSizeBoundsAutomatic is
FALSE)
Control.MinInterval ......... Minimum element size bound (used for moving
elements if ElementSizeBoundsAutomatic is
FALSE)
Control(index) ................. Size of element (index + 1) where index runs
from 0 to Control.Elements - 1.
Control.MaxMove.Variable Set switch to FALSE if no max move for variable
Name ................................ VariableName is required and TRUE if

2-44 • Modeling Language for Simulations Modeling Language Reference


maxmove using maxvalue is to be set
Contro(index)l.VariableName..........Disvalue is the value of the variable at the start
of telement index+1. Index must be less than or
equal to Control.Elements
VariableName .................. Names of the relevant variables

Optimization The following is an example of the modeling language for an


Simulation Example optimization simulation:

Optimization
IsDynamic : TRUE;
ElementSizeBoundsAutomatic : TRUE;
TimeBoundsAutomatic : TRUE;
EndTime : 1;
Control.FinalTime_Upper : 2;
Control.FinalTime_Lower : 0.5;
Control.FinalTime_IsFixed : TRUE;
Control.FinalTime_IsObjective : FALSE;
Control.Elements : 10;
Control.FixedInterval : TRUE;
Control.PiecewiseLinear : FALSE;
Control.MaxInterval : 0.2;
Control.MinInterval : 0.001;
Control(0) : 0.1 ;
Control(1) : 0.1 ;
Control(2) : 0.1 ;
Control(3) : 0.1 ;
Control(4) : 0.1 ;
Control(5) : 0.1 ;
Control(6) : 0.1 ;
Control(7) : 0.1 ;
Control(8) : 0.1 ;
Control(9) : 0.1 ;
b1.u : control;
Control(0).b1.u : 1;
Control(1).b1.u : 1;
Control(2).b1.u : 1;
Control(3).b1.u : 1;
Control(4).b1.u : 1;
Control(5).b1.u : 1;
Control(6).b1.u : 1;
Control(7).b1.u : 1;
Control(8).b1.u : 1;
Control(9).b1.u : 1;
b1.y2 : objective;
Control.MaxMove.b1.u : 0,FALSE;
End

Modeling Language Reference Modeling Language for Simulations • 2-45


Defining Constraints You can define constraints on your optimization simulation in
Flowsheet Constraints and Model definitions. You can define two
types of constraint:
Type of constraint Use for Effect on degrees of freedom

Equality Intermediate None


calculations
Inequality Process limits None

To define an equality constraint, create an equation in the


Flowsheet Constraints definition, using == instead of =.
Note An equality constraint is different from an equation in the
Constraints definition because:
• An equality constraint does not affect the degrees of
freedom
• An equality is satisfied during optimization simulations only
(other types of simulation will not attempt to satisfy it).
To define an inequality constraint, use <= or >= symbols directly in
the modeling language. For example:
A <=B;
It is recommended that you name your constraint equations so that
you can easily identify constraints when the results are reported.
For example, to name the preceding constraint equation
Constraint1, enter:
Constraint1: A <=B;
You can also re-write inequalities using slack variables, if you
want, although this is not as convenient as using <= or => directly.
To use slack variables to define inequalities, you define a slack
variable and use this slack variable in an equality constraint
equation. The slack variable you define must be of built-in variable
type SlackVariable. This ensures that the value of the slack
variable does not become negative during the optimization run.
To apply the following inequality:
A <= B
You need to specify the following:

A AS RealVariable;
B AS RealVariable;
Slack1 AS SlackVariable;
Slack1 + A = B;

2-46 • Modeling Language for Simulations Modeling Language Reference


This means that A cannot become greater than B, as Slack1 would
become negative, which is outside the lower bound of the built-in
variable type SlackVariable.
Caution If you rewrite existing constraints that were written in
the 10.1 modeling language to use <= or >= directly, do not use the
name of a slack variable as the name of an inequality, otherwise the
inequality becomes an assignment.

Examples of Defining Constraints


The following example shows an equality constraint in a Flowsheet
Constraints definition:
HeatExchanger1.Q == -HeatExchanger2.Q ;
The following example shows a Flowsheet Constraints definition
that contains a number of inequality constraints.
MAX_EFFLUENT_CONCENTRATION as
RealVariable(fixed);
MAX_TEMPERATURE as RealVariable(fixed);
MIN_TEMPERATURE as RealVariable(fixed);
MAX_PRESSURE as RealVariable(fixed);
MIN_PRESSURE as RealVariable(fixed);

PURGE.X1("Methanol") <=
MAX_EFFLUENT_CONCENTRATION;
MEREACTOR.TEMP >= MIN_TEMPERATURE;
MEREACTOR.TEMP <= MAX_TEMPERATURE;
MEREACTOR.PRESSURE >= MIN_PRESSURE;
MEREACTOR.PRESSURE <= MAX_PRESSURE;

Defining a Homotopy Simulation


The Homotopy section of an input file is used to specify the
homotopy variables and their target values in base units of
measurement.
Upon loading, the variables are checked to see that their
specification and target are valid. If a variable specification is not
FIXED or INITIAL, it is ignored. If a target value is outside the
bounds of a variable, it is clipped to the relevant bound.

Modeling Language Reference Modeling Language for Simulations • 2-47


Syntax for Homotopy
The following syntax is used for the Homotopy section:

Homotopy
BlockName.VariableName: TargetValue;
.
.
Enabled: TRUE|FALSE;
End

BlockName....................... Name of the relevant block


VariableName .................. Name of the homotopy variable
TargetValue...................... Value to which you want to move
Enabled ............................ Keyword which controls whether homotopy is active
or not when the input is first loaded. Can be True or
False.
Example Homotopy The following is an example of a Homotopy section in an input
Section file:

Homotopy
FEEDERMB.TOTAL: 12000;
MEREACTOR.PRESSURE: 130;
MEREACTOR.TEMP: 480;
Enabled: FALSE;
End

2-48 • Modeling Language for Simulations Modeling Language Reference


Modeling Language Reference Modeling Language for Simulations • 2-49
3 Modeling Language for Types

This chapter describes defining the following types:


• Variables
• Parameters
• Ports
• Models
• Streams
• Generic types
• Properties
• Atomic
• Solver properties
• Procedures
You can create the following types in the modeling language:

Type Keyword Description Named? More than


one
allowed?

MODEL Model type Yes Yes


STREAM Stream type Yes Yes
VARIABLE Variable type Yes Yes
PROCEDURE Procedure definition type Yes Yes
PORT Port type Yes Yes
PROPERTIES Properties type No No
TYPE Generic type Yes Yes
PARAMETER Parameter type Yes Yes
FOLDER Folder type Yes Yes
OPTIONS Options type No No

Modeling Language Reference Modeling Language for Types • 3-1


Defining Variable Types
Use the VARIABLE keyword to define variable types. Each
variable type definition can specify properties for that variable
type. These properties include the default starting value for the
numerical routines, the bounds on that variable, and the units of
measure.

VARIABLE Syntax
If you do not specify a parent variable type, as shown in the
following syntax, the built-in variable type RealVariable is used.
For information on RealVariable, see Chapter 1.

VARIABLE VariableName
Property : PropertyValue;...
END

VariableName .................. The name of a new variable type


Property............................ A property of RealVariable: Value, Upper, Lower,
Scale, IsConnected, Description, PhysicalQuantity,
and Spec.
PropertyValue.................. The first guess value for solving variables of this
type
Alternatively, you can make the variable type inherit the properties
of a previously defined variable type, with the keyword USES. You
can then modify the values of the properties of the parent variable
type:

VARIABLE VariableName USES VariableName


Property : PropertyValue;...
END

VariableName .................. The name of a new variable type


USES ................................ USES keyword
VariableName .................. The name of a previously defined variable type
Property ........................... A property of the previously defined variable type
PropertyValue.................. The first guess value for solving variables of this
type

3-2 • Modeling Language for Types Modeling Language Reference


VARIABLE Examples
The following examples show how inheritance is used to define
variable types.
The first example shows that the variable named Temperature
inherits the properties of the fundamental variable type
RealVariable:
VARIABLE Temperature
END
The following statement is equivalent to the first example:
VARIABLE Length USES RealVariable
END
The next example shows the variable type Length defined for
meter measurements:
VARIABLE Length
PhysicalQuantity: "Length" ; // defines the
base units meters
Value: 1.0; // meters
Lower: 0.0; // meters
Upper: 5e6; // meters
END
The final example shows that the variable type length_short
inherits the properties of Length. The starting value and upper
bound are overwritten. The lower bound remains at the value
defined in the length variable type definition.
VARIABLE length_short USES Length /* Length in mm */
PhysicalQuantity : "ShortLength" ; // base units now
in millimeters
Value: 10.0; // millimeters
Upper: 1000; // millimeters
END

Modeling Language Reference Modeling Language for Types • 3-3


Defining Parameter Types
You can create your own parameter types to enable your models to
be configured using meaningful names.
Once you have defined a parameter type you can define parameters
in your models that use that type. You can define a list of valid
options, for example, so that the pull-down list on the model Table
only allows the user to select a value from that list.

Parameter Type Definition Syntax

PARAMETER ParameterName USES BuiltInParameter


Value : DefaultParameterValue ;
Valid AS SetType( ValidList ) ;
END

ParameterName............... Name you give to the new parameter type


BuiltInParameter ............. One of the built-in parameter types. Can be
RealParameter, IntegerParameter, LogicalParameter
or StringParameter.
Value................................. The default value of the parameter type
Valid.................................. A set of valid values. Applies only to parameters that
inherit from IntegerParameter or StringParameter.
SetType ............................ Can be either IntegerSet or StringSet
ValidList ........................... List of valid options for this parameter type. Can be
either a list of integers or strings of text

Parameter Type Definition Example


The following example shows how to define a new parameter that
controls the geometry of a vessel.
PARAMETER GeometryParameter USES StringParameter
Valid AS StringSet( [ "Cylinder", "Cone",
"Hemisphere", "Rectangular"] );
Value : "Cylinder";
END
MODEL Tank
Geometry AS GeometryParameter("Cone");
.
IF Geometry == "Cone" THEN
Volume = PI/3 * Radius * Radius * Height;
ENDIF
IF Geometry == "Rectangular" THEN
Volume = Length * Length * Height;
ENDIF
END
You can change the parameter Geometry from a Table.

3-4 • Modeling Language for Types Modeling Language Reference


Defining Port Types
Use port statements to define the values passed between models.
You must list the variable types of the values that are
communicated between blocks on the flowsheet.

PORT Syntax

PORT PortType USES PortType


PortVariableName AS VariableType ; ...
END ;

PortType........................... The name of the port definition


PortVariableName ........... The name of the variable(s) you define in this port
VariableType.................... The variable type you ascribe to this variable

PORT Remarks
You can make the port type inherit the properties of a previously
defined port with the keyword USES. You can then add additional
variable types to the existing definition so that more information is
passed by the new port.
If you do not specify a parent port type, the built-in port type,
GenericPort, is used. For information on GenericPort, see
Chapter 1.

PORT Examples
The following examples show definitions of port type, including
inheritance. The first example defines a Port called Material, which
contains an empty variable type list, and so has limited usage:
PORT Material END
The second example definition is equivalent to the previous
example:
PORT Material USES GenericPort END
The following example shows the port type Material defined to
communicate a molar flow rate and a temperature:
PORT Material
Flow AS MolFlow;
Temp AS Temperature;
END

Modeling Language Reference Modeling Language for Types • 3-5


The final example shows that the definition of port type
NewMaterial inherits the properties of the previously defined type
Material. The port variable Press is added to the list of values
communicated by the port:
PORT NewMaterial USES Material
Press AS Pressure;
END

Defining Model Types


Use the model definition to supply all the equations required to
describe your process plant unit operation. The equations form the
basic description of your simulation. In addition to the equations, a
model can contain parameters, variables, ports, forms and icons.

MODEL Syntax

PRIVATE MODEL ModelName USES ModelName


ModelDescriptionStatements
END

PRIVATE Optional keyword that makes the model text


inaccessible to the user when used in a library. This can
be used to protect proprietary information contained
within the model.
ModelName ...................... The name you give this model description

MODEL Remarks
You can include statements in the model description to define
different aspects of the model. Models do not need to contain
specific elements. For example, you can define a model with no
ports and use inheritance to define different models with different
port configurations.
You can add the following statements to your model definition:
• Parameters
• Sets
• Variables
• Ports
• Equations
• Procedure calls
• Sub-models (instances of other models)
• Sub-model connections
• Forms and icons associated with this model

3-6 • Modeling Language for Types Modeling Language Reference


You can mark the model as PRIVATE. This means that if the
model is used in a library, the user of the library cannot:
• Display the model in the Simulation Explorer view
• Export the model with a Save
• See the model equations and variable names in a Diagnostic
view

MODEL Example
The following example shows a complete description of a gravity
flow tank:
MODEL TANK
/* Define variables for this model’s equations */
Vol AS Volume;
K AS Constant;
H AS Length;
XSArea AS Area;
/* Set up an inlet and an outlet port of port type Fluid */
In1 AS INPUT Fluid;
Out1 AS OUTPUT Fluid;
/* Equations using internal and port variables */
/* Input - Output = Accumulation */
$Vol = In1.Flow - Out1.Flow ;
/* Flow out proportional to the square root of the fluid
height */
Out1.flow * Out1.flow = K^2 * H ;
/* Cylindrical geometry tank */
Vol = H * XSArea;
/* The tank is fully described */
END

Modeling Language Reference Modeling Language for Types • 3-7


Defining Stream Types
Stream types are introduced by the keyword STREAM. A stream is
similar in syntax to a model, but it appears as a line in a flowsheet
drawing. On the flowsheet drawing, you can use a stream you
define to connect ports in the same way you use the built-in stream
type Connection. You can define a stream that contains variables,
equations, and ports.

STREAM Syntax
The syntax for a stream type is exactly the same as a model type:

PRIVATE STREAM StreamName USES StreamName


StreamStatements
END

PRIVATE Optional keyword that makes the stream inaccessible


to the user when used in a library
StreamName .................... The name you give to this stream definition

STREAM Remarks
There are some restrictions to the STREAM syntax compared to
the MODEL syntax:
• You must define at least one port, but not more than two
ports. Most streams connect two blocks together, and
therefore need two ports.
• The two ports must be INPUT or OUTPUT. The direction of
the stream depends on the direction values of the stream
ports and the block ports to which the streams are
connected.
• If the stream definition has one port only, this port must be a
feed or product stream. Again, the direction of the stream
ports or the block ports to which the stream is attached
determines the stream orientation.
Stream types are optional. You can make connections between
blocks using a built-in stream type called Connection.
You can mark the stream as PRIVATE. This means that if the
stream is used in a library, the user of the library cannot:
• Display the stream in the Simulation Explorer view
• Export the stream with a Save
• See the stream equations and variable names in a Diagnostic
view

3-8 • Modeling Language for Types Modeling Language Reference


STREAM Example
In this example, a stream is defined as having a potential loss of
fluid through a leak.
STREAM LeakyStream
FlowLeak AS MolFlow;
StreamInput AS INPUT Material ;
StreamOutput AS OUTPUT Material;
StreamInput.Flow = StreamOutput.Flow - FlowLeak;
FlowLeak: Fixed;
END
FLOWSHEET
Tank1 AS TankModel ;
Tank2 AS TankModel ;
S1 AS LeakyStream ;
CONNECT Tank1.Output1 AND Tank2.Input1 WITH S1
;
END

Defining Generic Types


You do not normally need to define generic types. However,
generic types are created by actions in the GUI, such as defining
forms and icons, and you may see these types defined if you edit a
language file.
The modeling language enables you to introduce types using
keywords. These keywords introduce definitions of types that the
simulation compiler understands. In addition, the compiler enables
you to define generic types.
Generic types are introduced by the TYPE keyword. You use
generic types to describe objects that cannot be described in the
modeling language. For example, you cannot use the modeling
language to define a form. A form definition describes the form
layout, the position of controls on the form, the mapping between
controls and data, and other aspects, all of which are beyond the
scope of the modeling language. Like forms, flowsheet icons
cannot be defined by the modeling language.
Generic types enable you to embed the native definition of an
object in a language file. The RoleString describes the function of
an instance of a generic type. For example, if you use a generic
type to describe a form implemented as a Microsoft Visual Basic
control, then the RoleString is form. Defining the RoleString
enables the compiler to take the appropriate action as it processes
the declaration of an instance of a generic type.

Modeling Language Reference Modeling Language for Types • 3-9


You can use generic types to describe external objects in the
modeling language. After you have defined a generic type, you can
make declarations of that type within other types. In this way you
can define forms in the modeling language and then associate the
forms with models.

Generic Types Example


The following example shows a form definition:
TYPE myVBHeaterForm CLASS "CLSID_VBForm" ROLE
"form"
TEXT
.
.
ENDTEXT

MODEL Heater
Input AS myVBheaterform;
.
.
END
A type called myVBHeaterForm is defined. An external type has a
class and a role. The class tells the compiler the object that
implements this type. The role tells the compiler the role that an
instance of the type plays in the problem. The compiler uses this
information to build the external object into the system and to
create instances of it.
If any text is associated with the external type, it appears between
the TEXT and ENDTEXT keywords. This text may contain data
that needs to be loaded when the compiler creates the type.
In the model Heater, a declaration gives the model a form. In this
example, the form is called Input.

3-10 • Modeling Language for Types Modeling Language Reference


Defining Physical Properties Types
This section describes the various aspects of using physical
properties types. The following topics are covered:
• Defining properties system data
• Validating component lists
• Using the ComponentList property
• Using more than one component list
Defining Properties The type introduced by the PROPERTIES keyword can be used to
System Data define:
• Physical properties system data. When it is used to define
component names that reference a physical properties
system, the type is also used to define the location of files
used to implement the Generalized Physical Property
Interface, and to define the properties data and options used
in a particular simulation.
• A set of component names that do not reference a physical
properties system.
There can be only one properties type in an input file.
You would not normally define Properties using language.
However, you may see properties definitions if you edit a language
file.

Properties Type Definition Syntax when defining Properties


System Data
The syntax for the Properties type when used to define properties
system data is:

PROPERTIES
WorkingDirectory : "value"
RunID : "value"
ComponentListDeclarations
Assignments
END

Modeling Language Reference Modeling Language for Types • 3-11


ComponentList
Declarations..................... A list of declarations of component lists of the form:

The
Name as ComponentList;
The
Name................................. The name of the component list
Assignments.................... A list of assignments to the declared component lists
and to the built-in properties of the Properties type
RunID................................ The file containing the physical properties information
WorkingDirectory ............ The full path to the RunID file
Caution If the path includes a specific drive letter,
ensure that any mapped drives are consistent with the
path. If you share properties files between many servers,
it is advisable always to map the the same drive letter on
all servers.

Properties Type Definition Syntax when a Physical Properties


Package is Not Connected
The syntax when used to define a set of component names that do
not reference a physical properties system is:

PROPERTIES
ComponentListDeclarations (IsComponentSet : value);
Assignments
END

ComponentList
Declarations..................... A list of declarations of component lists of the form:

The
Name as ComponentList;
Name................................. The name of the component list
The

Assignments.................... A list of assignments to the declared component lists


and to the built-in properties of the Properties type
IsComponentSet.............. A property that indicates whether you are creating a set
of component names
value ................................. A logical parameter that can be TRUE or FALSE. To
indicate that you are creating a set of component names,
set IsComponentSet to TRUE.

3-12 • Modeling Language for Types Modeling Language Reference


Defining Properties Example
The following is an example Properties type containing two
component lists: Process and Utility:
Properties
WorkingDirectory : "d:\aspen\bin\";
RunId : "pfdtut";

Utility, Process as ComponentList;

Utility.components : ["Water"];

Process.components :
["Methanol","Ethanol","Water"];
Process.option("OPSET") : "Sysop12";
Process.option("KBASE") : "1";
end
In this example, the Utility component list has a single component,
water. No options are specified so the defaults defined by the
implementation of the physical properties system interface will be
used. The second component list, Process, has three components:
methanol, ethanol, and water. The default values for the calculation
options OPSET and KBASE are overridden for this list.
Validating When you open an input file, the component names, option names,
Component Lists and option values are validated against the physical properties
system you have specified. To specify the physical properties
system to be used, you supply values for the WorkingDirectory and
RunID properties in the properties definition.
If the validation fails, the load operation continues using the valid
data. Invalid data is ignored but warnings are given.
If the location of the files used to perform the validation is invalid,
the component list data is loaded, but it will be validated when
physical property data is next successfully loaded. If any data is
invalid at this point, invalid data is deleted and warnings are
generated.
Using the A block, stream or port has a built-in property called
ComponentList ComponentList. You can use ComponentList to define arrays
Property indexed over the set of components defined in a component list.

Modeling Language Reference Modeling Language for Types • 3-13


ComponentList Syntax

VariableName (ComponentList) AS VariableType;

VariableName .................. Name you give to a variable


VariableType .................... The type of the variable

ComponentList Remarks
You can globally assign a value to the property ComponentList in
the LocalVariables table for the flowsheet. This value will be a
component list you have defined yourself in a properties definition.
For information on defining physical properties types, see Defining
Physical Properties Types on page 3-11.

ComponentList Example
The following is an example of a model that uses the process
component list declared in the Properties definition given in the
Defining Properties Example on page 3-13.
PROCEDURE pEnth_Mol
WORKSPACE : 10;
CALL : "gpi2ex";
LIBRARY : "sai";
IMPLEMENTATION : "SUBROUTINE";
LANGUAGE : "FORTRAN";
OPTIONS : PROPERTIES;
INPUTS:
Temperature,
Pressure,
Molefraction(*);
OUTPUTS:
/* returns molar enthalpy for non-specified-phase stream
*/
Enth_Mol;
END

MODEL FeederPP
Description:"Feed stream material balance calculation.";
ComponentList : "Process";
Z(ComponentList) AS Molefraction;
T_out AS Temperature;
P AS Pressure;
H AS Enth_Mol;
$T_out = 10 ;
CALL ( H ) = pEnth_Mol (T_out, P, Z);
SIGMA(Z) = 1.0;
END

3-14 • Modeling Language for Types Modeling Language Reference


In the model FeederPP, the array Z is sized by the set of
components defined in the component list called Process. If the list
called Process is edited in the GUI, Z will resize accordingly.
When the Properties procedure gpi2ex is called during the solution
phase, it will be passed an ID that identifies the component list
process.
Using More Than One If a model needs to use more than one component list, you can add
Component List in additional properties of the same type as the built-in
Models ComponentList property. You can then associate the additional
properties with a procedure call.
The type of the built-in property ComponentList is
ComponentListName. The ComponentListName type is a built-in
type whose value is the name of a component list you can define
either in the PROPERTIES definition or by using the GUI.
Although the value of an instance of this type is a string, an
instance can be used to index arrays because the name refers to a
set: the set of components in the named component list.

Using More Than One Component List in Models Example


This example shows two component lists used in the same model:
MODEL HeatExchanger
HotSide, Coldside AS ComponentListName;
ColdSideInlet AS INPUT Process (ComponentList: ColdSide);
ColdSideOutlet AS OUTPUT Process (ComponentList: ColdSide);
HotSideInlet AS INPUT Process (ComponentList: HotSide);
HotSideOutlet AS OUTPUT Process (ComponentList: HotSide);
:
:
EnthOutColdSide: CALL (ColdSideOutlet.H) = pEnth_Mol
(ColdSideOutlet.T, ColdSideOutlet.P, ColdSideOutlet.z) ColdSide;
SumFracColdSide: SIGMA(ColdSideOutlet.z) = 1.0;
EnthOutHotSide: CALL (HotSideOutlet.H) = pEnth_Mol
(HotSideOutlet.T,
HotSideOutlet.P, HotSideOutlet.z) HotSide;
SumFracHotSide: SIGMA(HotSideOutlet.z) = 1.0;
END

Modeling Language Reference Modeling Language for Types • 3-15


Atomic Types
You can use the atomic types to add properties to your own
variables. The added properties cannot be used in the modeling
language. This means your own added properties cannot be used in
models, ports, streams or any of the types you create for the
simulation.
There are four atomic types:
• Integer
• Real
• Logical
• String
You can use your added properties in VB scripting, or access the
properties through automation. This means you can make pre- or
post-run calculations including the added properties and the built-
in properties for your simulation.

Defining Solver Properties


You can assign values of solver properties that are different to the
default values. All solver property definitions come between the
keywords OPTIONS and END. Only one solver properties
definition can exist in a simulation description.
You may wish to change the default values of solver properties to
improve the speed and robustness of your simulation, or to provide
more diagnostic output.
Normally you would change the solver properties from the GUI.

3-16 • Modeling Language for Types Modeling Language Reference


Solver Properties Syntax

OPTIONS
SolverProperty : Value ;
.
END

SolverProperty................. Name of the property for which you want to change


the default value
Value ................................ The value you give to the solver property. Can be an
integer, a real, a logical, or a string. Valid values are
defined by each individual solver property

Solver Properties Remarks


For descriptions of the different solver properties you can choose,
see the Aspen Modeler Reference, Chapter 4,
Application.Simulation.Options. The complete list of solver
options is included when you save your simulation as a text file.

Solver Properties Example


The following example shows how to define values for solver
property options that are different from the default values:
OPTIONS
Printlevel: 1 ;
Time_step : 0.01 ;
NumberIntervals : 50 ;
Integrator : "Gear" ;
Gear.Boundcheck : TRUE ;
END

Modeling Language Reference Modeling Language for Types • 3-17


Defining External Procedures
You can use procedure type definitions to interface your models to
external Fortran, C, or C++ routines. To use procedures that are
external to the simulation, you must define the argument list and
the type of external routine, which options you need to use; the
path to the dynamic link library; and the location of the original
code.
This section explains how to link your models to procedures. For
information on writing procedures and functions, see the online
Help Improving Your Simulations, Designing Models, Using
Procedures and Functions.

External Procedure Syntax

PROCEDURE ProcedureName
LIBRARY : "dll library filename" ;
CALL : "ExternalName";
IMPLEMENTATION: SUBROUTINE | FUNCTION "Fortran, C or C++
file pathname"|
TEXT
code
ENDTEXT;
LANGUAGE: "FORTRAN | C |C++";
COMPATIBILITY: "SPEEDUP" ;
OPTIONS: ListOfOptions ;
WORKSPACE: WorkspaceExpression ;

INPUTS : InputArgumentType, InputArgumentType, ... ;


OUTPUTS: OutputArgumentType, OutputArgumentType, ... ;
END

ProcedureName .............. The name you give to this procedure definition. This name is used by
call statements in the modeling language
Dll library filename.......... The file name, including the path on the machine you are using, as a
string of text. Do not include the extension .dll or .so if you want the
name to be platform-independent.
Note If the client and server are running on the same machine, you do
not need to specify the full path name if DLLs are located:
– on the PATH;
– in the Simulation Working Directory, or;
– in the same directory as the Input language text file.
ExternalName.................. The name of the routine in the external code. If the ExternalName is the
same as the ProcedureName, the CALL statement is not required

3-18 • Modeling Language for Types Modeling Language Reference


WorkspaceExpression ... Either a fixed integer value for workspace, or an integer expression
(literal, that is, numbers not symbols, constants only, for example,
10*(10-1)/2)
Code................................. Fortran, C or C++ code written inside the definition file, between the
keywords TEXT and ENDTEXT. The code text is line-based, so the
ENDTEXT keyword must appear at the start of a line.
ListOfOptions.................. List of the options enabled for the procedure definition
Fortran or C file pathname............The file name, including the path, of the external code file you are
using, if any, as a string of text. As with the library filename, do not
specify an extension if you want the pathname to be platform-
independent.
InputArgumentType........ ..............The types in the routine input argument list. Can be any variable type,
RealParameter, IntegerParameter, or StringParameter
OutputArgumentType..... The types in the routine output argument list. Can be RealVariable or
any variable type.

External Procedure Remarks


The routine name is the name of the external routine to be called in
the external code. It is always required.
The LIBRARY name is the full path name of the library containing
the routine called by the procedure definition. This reference has to
be to a Dynamic Link Library (DLL). The library name is always
required. You can compile several different procedure calls into the
same library. Typically, for a simulation, you can define the library
for all the procedure calls to be the same DLL file. This means you
only need to supply one DLL file to run the simulation. Unless you
want to override the default extension for the language specified by
the language property, do not specify an extension to the name.
The IMPLEMENTATION statement indicates whether the external
routine is a subroutine or a function. If no implementation
statement is made, the default is subroutine. If you are creating the
DLL file, you need to include a reference in the
IMPLEMENTATION statement to the code associated with the
Procedure. You can do this either by including the path and file
name of an existing code file as a string of text, or by including the
code between the keywords TEXT and ENDTEXT. You can put
several subroutines into the same code file and refer to the same
code file in different procedure definitions.
The COMPATIBILITY statement enables you to use Fortran code
that worked with SPEEDUP 5.5. This means that you do not need
to alter the call list for 5.5 compatible code. However, Aspen
Custom Modeler is stricter than SPEEDUP 5.5 in enforcing the
correct argument list for an external procedure call. If you have
unresolved link symbols, check that your procedure argument list

Modeling Language Reference Modeling Language for Types • 3-19


contains all the required arguments. A common mistake is to miss
out the IFAIL or ITYP arguments at the end of the argument list.
The COMPATIBILITY statement can only be used when Fortran is
used to implement external procedures.
The LANGUAGE statement indicates whether the user routine is
written in Fortran, C, or C++. The default value is Fortran.
The OPTIONS statement is a list of keywords that indicates extra
options about the procedure call. The default is no extra options.
The options available are:

Keyword Meaning

PRECALL The procedure is called before the run starts, in the


following situations:
• Starting a simulation with Run
• Re-starting a simulation after an Interrupt
POSTCALL The procedure is called in the following situations:
• Changing the structure of the simulation
• Loading a new simulation
• Using Interrupt during a simulation run
DERIVATIVES You can calculate and return analytical derivatives
of the outputs with respect to the inputs from the
procedure.
PRESET The current values of the procedure outputs are
passed into the procedure. This is useful when you
back-calculate one or more of the procedure inputs
from one or more of the procedure outputs.
PROPERTIES Passes the identification information for the
components in the call when calculating material
properties.
CHANGESINPUTS Enables you to change the value of an input
variable in the external code Use this option only
if the procedure is always torn; the solver may fail
if the procedure is not always torn.
ALWAYSCALL Forces calls of the procedure even when the inputs
(and, if PRESET is also specified, the outputs),
have not changed since the last call. Use this
option only if the procedure is always torn; the
solver may fail if the procedure is not always torn.
Note A procedure with no inputs behaves as if
the ALWAYSCALL option has been specified.

3-20 • Modeling Language for Types Modeling Language Reference


The WORKSPACE statement can be a fixed integer number or
integer expression which allocates that amount as workspace to be
used by the external routine.
The INPUT and OUTPUT variable type list is defined in the order
that the variables are called in the model. In the case where an
array is passed to the procedure, you do not need to specify the size
of the array when you define the procedure. To indicate that an
array variable is to be passed, follow the variable type name in the
list with dummy subscripts, using one asterisk for each dimension,
for example, (*) or (*,*).

External Procedure Example


The following example shows a call to a Fortran subroutine that
calculates the volume of a vessel, given the height and cross
sectional area:
PROCEDURE VolCalc
LIBRARY : "C:\Examples\mlp" ;
CALL : "vc";
IMPLEMENTATION : SUBROUTINE "C:\Examples\volcal";
LANGUAGE: "Fortran";
OPTIONS : DERIVATIVES;
INPUTS : Length, Area;
OUTPUTS : Volume;
END

Modeling Language Reference Modeling Language for Types • 3-21


Defining Model Folders
In addition to the default folders that appear in the Custom
Modeling library, you can also create your own folders for models.
This allows you to sub-divide large collections of models you have
written into categories. You can then access your models in a
structured representation of your library.

Folder Syntax
You can create lists of types under named folders. The syntax is:

FOLDER FolderName
Description: "Descriptive text string";
TYPES: ["Type1", "Type2", ..., "TypeN"];
FOLDER NestedFolderName
Description: "Descriptive text string";
TYPES: ["TypeX", "TypeY", "TypeZ"];
END
END

FolderName ..................... Name you give to the folder. This name is displayed in
the Custom Modeling library folder
Type1, Type2, TypeN
TypeX, TypeY, TypeZ....... Lists of previously defined types
Descriptive text string .... Description of the folder
NestedFolderName ......... Name you give to a nested folder (if applicable)

Folder Remarks
You can create any number of levels of model folder by using the
Add Model Folder object within each model folder.
You must define folders after you have defined the types you want
to list in the folders. You should define folders in a suitable place,
for example, immediately before the flowsheet definition.

Folder Example
In this example, a number of previously defined models are
organized into different folders for more efficient access in the
Custom Modeling library.
FOLDER HeatExchangers
Types: ["HeatEx1", "HeaterCooler", "HeatEx2",
"HeatExShellInTube", "HeatExFanAssisted"];
END
FOLDER Mixers
Types: ["GeneralMixer", "TwoPhaseMixer",
"ThreePhaseMixer"];
END

3-22 • Modeling Language for Types Modeling Language Reference


4 Modeling Language for
Models

This chapter describes defining models. The following topics are


covered:
• Declaring variables
• Declaring ports
• Writing equations
• Equations with array variables
• Conditional equations
• Using sets in conditional expressions
• FOR loops and the ForEach operator
• Equations that call procedures
• Equations that refer to port variables
• CONNECT keyword
• LINK keyword
• Connectivity rules
• Using SIGMA
• Using the SIZE function
• Assigning specifications
• Referring to sub-models
• Using SWITCH
• Using external properties to write sub-models
• Using virtual types in sub-models

Modeling Language Reference Modeling Language for Models • 4-1


Declaring Variables in Models
Use variable declaration statements in models to define the
variables you need for your model equations. You can also define
array variables with one or more dimensions.
You can define a variable to be measured or manipulated by
defining a direction for the variable. This means you can connect
two variables in different blocks on the flowsheet using the
ControlSignal stream.
You can also define a variable as hidden, so that the variable
cannot be seen by the model user.

Model Variable Syntax

VariableName(Set , Set, ...) VariableName(Set…), ... AS FlagList


VariableType (SpecificationList);

VariableName .Name you give to this variable


Set ...................Optional set definition. Either a set name or a definition between
[ and ] (brackets). Use a Set to define an array variable. To
define multi-dimensional arrays, define a list of sets.
FlagList ...........List of optional qualifiers for the variable. Can be a Direction
(INPUT, OUTPUT), HIDDEN, UseUOMof, and GLOBAL.
The

INPUT, OUTPUT Direction qualifiers that define a variable as


measured or manipulated. Valid values are INPUT
or OUTPUT, or both INPUT and OUTPUT. For
information on the rules for connecting variables
with a stream, see CONNECT Keyword on page 4-
25.
HIDDEN An optional qualifier that defines a variable that
cannot be displayed in Tables and Plots. Use the
HIDDEN keyword to define a private variable.
Although the HIDDEN variable cannot be displayed,
the value is available to the Automation interface.
EXTERNAL Indicates that the declared property is not part of the
model but instead refers to a property of the
containing model.
GLOBAL Indicates that the declared variable or parameter is
not part of the model but instead refers to a global
variable. For example, a global parameter could be
the Universal Gas constant.
The

VariableType...Name of a defined variable type


Specification List of optional specifications for the variables
List ..................

4-2 • Modeling Language for Models Modeling Language Reference


Model Variable Remarks
You can declare a list of variables with the same type in one
statement. Each variable has all the properties defined in its type.
The value of each property will be the value assigned to the
property in the variable type. You can subsequently modify the
values of these properties.

Model Variable Examples


All the following declarations appear within a model definition.
In the first example, a variable called FeedTemp is created in the
model. FeedTemp takes on the characteristics of the built-in
definition of a variable:
FeedTemp AS RealVariable ;
In the second example, the variable FeedTemp takes on the
characteristics of the variable type previously defined by
Temperature. In this example, the variable FeedTemp is defined in
the model as a fixed or known variable:
FeedTemp AS Temperature(Fixed) ;
In the following example, FeedTemp takes on the characteristics of
the type Temperature. In this case, the default value and the lower
bound on the variable is altered for this variable only:
FeedTemp AS Temperature( VALUE:373.0;
LOWER:273.0; ) ;
In the next example, no specification keyword has been used. This
means the number in brackets is assigned to the value property of
the variable. The direction keyword is included in the statement,
which means the value of FeedTemp can be passed to another
block on the flowsheet using the built-in stream type
ControlSignal.
FeedTemp AS OUTPUT Temperature( 373.0 ) ;
The following example shows two variables defined in one
statement. Both variables have the default value and the lower
bound altered from the definition of the variable type Temperature.
FeedTemp, ProductTemp AS Temperature( 373.0;
LOWER:273.0; ) ;
In the following example, the variable FlowIn is defined as a four
element, one-dimensional array, and FlowOut is defined as a three
element one-dimensional array of variable type MolFlow.

Modeling Language Reference Modeling Language for Models • 4-3


Nsect AS IntegerParameter(4);
Index AS IntegerSet([1:Nsect]);
FlowIn(Index), FlowOut([1:Nsect-1]) AS MolFlow ;
A two-dimensional array variable is declared in the following
example:
Npoints AS IntegerParameter(20);
Points AS IntegerSet([1:Npoints]);
Elements AS IntegerSet([1:30]);
BulkTemperature(Points, Elements) AS Temperature;
The following example shows how to declare private variables,
that is, variables that cannot be displayed in a table or plot. The
first variable, K1, is hidden and is not available to view in a table
or a plot. The second variable, K2, is hidden and can be either a
measured variable or a manipulated variable.
K1 AS HIDDEN Constant(Fixed, 21.9);
K2 AS HIDDEN,OUTPUT Constant;
K3 AS HIDDEN, INPUT, OUTPUT Constant;
The last example shows how to define a variable to use the units of
measurement (UOM) of another variable. Examples of this are also
included in the PID controller model in the Modeler library.
If the variable, PV, is connected to a level variable in a tank, using
a ControlSignal stream, then PV will be displayed in the UOM of
the level variable. In the following example, SPRemote will also
be displayed in the UOM of the level variable.
//Input/ouput variables
PV AS Input Control_Signal
(description:"Process variable");
SPRemote AS Input Control_Signal (fixed,
description:"Remote setpoint", UseUOMof:"PV");

4-4 • Modeling Language for Models Modeling Language Reference


Declaring Ports in Models
Use port declaration statements to describe how the model
communicates to other models on a flowsheet. You can determine
the direction of information flow of the ports you define. Ports are
connected in models and in the flowsheet using the CONNECT
and LINK keywords.

Model Port Syntax

PortName AS DirectionType PortType ;

PortName ......................... Name you give the port


PortType........................... Type of port, defined in a PORT statement
DirectionType .................. Can be one of the following keywords: INPUT,
OUTPUT

Model Port Remarks


The port name is the name you provide for the port. This name is
used to refer to the port variables related to the port type. You
define the names of the port variables in the port type declaration
statement.
The port type is the name of the port as defined in the port type
declaration statement.

Model Port Examples


In the first example, the port Input1 is defined as using the port
type Material. The port has the direction property Input, which
means it can be connected to any output port:
Input1 AS INPUT Material ;
In the second example, Input1 is defined as a port of type Material
and its direction is an outlet.
Input1 AS OUTPUT Material ;

Modeling Language Reference Modeling Language for Models • 4-5


Using Port Properties A port in a block on the flowsheet contains properties in addition
to Direction and Description that you can use in the model to
determine how the port is used.
The additional properties are:

Property Description

IsConnected A logical parameter that describes whether a port


is connected
ComponentList Set of components being used in this port

Using Port Properties Examples


This example shows how the variable Output1.flow is calculated,
based on the value of the IsConnected parameter.
Here, the IF condition states that if Offtake.IsConnected has a
value of False (that is, if there is no connection to the port Offtake),
Input1.flow is equal to output1.flow, whereas if the port Offtake is
connected, it is included in the equation.
MODEL
Input1 AS INPUT Main;
Output1 AS OUTPUT Main;
Offtake AS OUTPUT Main;
IF NOT Offtake.IsConnected THEN
Input1.flow = output1.flow;
ELSE
Input1.flow - Offtake.flow = output1.flow ;
ENDIF
END
The following example shows how to use two different port
component lists:
PORT Process
Flow AS Flow_Mol_Liq;
x(ComponentList) AS Molefraction;
END
PROPERTIES
.
AqueousFluid, Process, AllComponents AS
ComponentList;
AqueousFluid.Components: ["Water", "CO2"];
Process.Components: ["Methanol", "Ethanol"];
AllComponents.Components:
AqueousFluid.Components + Process.Components;
.
END

4-6 • Modeling Language for Models Modeling Language Reference


MODEL ComponentMixer
Quench AS INPUT Process(ComponentList:
AqueousFluid);
Inlet1 AS INPUT Process(ComponentList:
ProcessFluid);
Outlet1 AS OUTPUT Process(ComponentList:
AllComponents);
.
/* Loop on components only in Inlet1 port */
FOR I IN [Inlet1.ComponentList -
Quench.ComponentList] DO
Outlet1.Flow*Outlet1.x(i) =
Inlet1.Flow*Inlet1.x(i) +
Quench.Flow*Quench.x(i);
ENDFOR

/* Loop on components only in Quench port */


FOR I IN [Quench.ComponentList -
Inlet1.ComponentList] DO
Outlet1.Flow*Outlet1.x(i) =
Inlet1.Flow*Inlet1.x(i) +
Quench.Flow*Quench.x(i);
ENDFOR

/* Loop on components only in both ports */


FOR I IN [Quench.ComponentList *
Inlet1.ComponentList] DO
Outlet1.Flow*Outlet1.x(i) =
Inlet1.Flow*Inlet1.x(i) +
Quench.Flow*Quench.x(i);
ENDFOR
.
END
The three FOR loops are designed to catch every situation for the
components entering the mixing vessel, whether there are duplicate
components in the two ports or all components are unique in both
ports.
Using the IsMatched You can connect a port to a port that does not have completely
Attribute of Variables equivalent variable names, for example, the component list used in
each port may be different. You can test for this by checking the
IsMatched attribute of the variables in ports.
When a port is connected, each variable that is matched has the
IsMatched attribute set to True. If it was not matched, IsMatched
will be False.
Note If a port is not connected, the value of IsMatched is
undefined for the variables in that port.

Modeling Language Reference Modeling Language for Models • 4-7


Example of Using IsMatched
The following example uses the IsMatched attribute in a Mixer
model that combines streams with different component sets.
PORT FlowPort
F(componentlist) as flow_mass;
END

MODEL ddd
inp as input multiport of FlowPort;
out as output FlowPort;
for s in inp.connectionset do
for c in inp.connection(s).componentlist do
if( NOT inp.connection(s).F(c).IsMatched ) then
inp.connection(s).F(c) = 0.0;
endif
endfor
endfor
END

Using Multiports You can define a collection of ports, which is known as a


multiport. A multiport is a single port that allows multiple stream
connections to the same port. A multiport uses the same port types
as a normal port.

Multiport Syntax
The syntax for defining a multiport in a model is:

PortName AS DirectionType MULTIPORT OF


PortType(MIN_CONNECTIONS:min, MAX_CONNECTIONS: max);

PortName ......................... The name you give to the port


MULTIPORT ..................... A keyword that defines this port as a multiport
DirectionType .................. Can take the values INPUT, OUTPUT, or both.
MAX_CONNECTIONS...... The maximum integer number of connections
allowed by this port
MIN_CONNECTIONS ....... The minimum integer number of connections
allowed by this port

4-8 • Modeling Language for Models Modeling Language Reference


Multiport Remarks
A multiport contains additional properties to enable you to take
into account in the model equations the number of connections to
the multiport. The additional properties are:

Connection ...................... An Array sized to the number of connections to the


multiport
ConnectionSet................. A Set of strings of text containing the names of the
streams connected to the multiport
For information on accessing the properties of a multiport, see
Using Connection with Multiports on page 4-9.

Using Connection with Multiports


You use Connection to access port variables in a multiport.

Connection Syntax
The variables in the port are accessed using the following syntax:

PortName.Connection.PortVariable

As Connection is an array, you can use the SIGMA function to sum


the values of PortVariable for all connections made to that port. If
the PortVariable is also an array, you can use SIGMA in the
following three ways.
The first way sums all combinations of
Connection(i).ArrayVariable(j).

Sum = SIGMA(PortName.Connection.ArrayVariable);

For a detailed explanation, see

Modeling Language Reference Modeling Language for Models • 4-9


SIGMA for Multidimensional Arrays Examples.
Using SIGMA a second way, for each element of the array
variable, the values of that ArrayVariable in all connections made
to the multiport are summed:

FOR i IN ArrayIndexSet DO
Sum(i) = SIGMA(PortName.Connection.ArrayVariable(i));
ENDFOR

Using SIGMA a third way , for each connection made to the


multiport, the values of all the elements of the ArrayVariable are
summed:

FOR i IN PortName.ConnectionSet DO
Sum(i) = SIGMA(PortName.Connection(i).ArrayVariable);
ENDFOR

You can use ConnectionSet to size an array variable to the same


size as the number of connections to the multiport:

Variable(ConnectionSet) AS VariableType;

Multiport Example
The following model represents a multi-mixer where only one inlet
port is defined. This mixer model can then be used to mix any
number of inlet streams between MAX_CONNECTIONS and
MIN_CONNECTIONS.
PORT Main
Flow AS Flowrate;
Z(ComponentList) AS Fraction;
END

MODEL MULTIMIX
Input 1 as INPUT MULTIPORT OF
Main(MIN_CONNECTIONS:1,MAX_CONNECTIONS:10);
Output1 AS OUTPUT Main;
Output1.Flow = SIGMA(Input1.Connection.Flow) ;
FOR i IN ComponentList DO
Output1.z(i)*Output1.Flow =
SIGMA(Input1.Connection.z(i)*Input1.Connection.Flow) ;
ENDFOR
/*Connection is an array of size ConnectionSet,
so the SIGMA function sums the values over the
elements in this array for each of the components
in ConponentList*/
END

4-10 • Modeling Language for Models Modeling Language Reference


Note In this example, if there are three streams carrying water
only connected to the port Input, then the equations produced by
this model are:
Output1.Flow = Input1.Connection("S1").Flow +
Input1.Connection("S2").Flow +
Input1.Connection("S3").Flow ;
Output1.Flow*Output1.z("Water") =
Input1.Connection("S1").Flow*Input1.Connection("S
1").z("Water") +
Input1.Connection("S2").Flow*Input1.Connection("S
2").z("Water") +
Input1.Connection("S3").Flow*Input1.Connection("S
3").z("Water") ;
If you need to sum a multi-dimensional array over one of its
dimensions, you can fix the other dimensions. In this example,
Total represents the total input flow rate of nitrogen over the inlet
multiport.
TotalN2In = SIGMA( Input1.Connection.F *
Input1.Connection.z("N2") );

Writing Equations in Models


Use equations to define relationships between variables and
parameters.

Equation Syntax

EquationName : ExpressionA = ExpressionB ;

EquationName ................. An optional equation identifier displayed in diagnostic


output
ExpressionA, ................... Mathematical functions involving variables and
ExpressionB parameters

Equation Remarks
You can have any number of variables on either side of the equality
sign. You should re-arrange equations to improve the numerical
solution of the simulation for robustness and speed.
The equations and variables in a model must completely describe
the process. You must ensure that the simulation can be solved,
given the number of known values in your simulation. The number
of equations must equal the number of unknowns in your
simulation.

Modeling Language Reference Modeling Language for Models • 4-11


However, even if the number of equations are equal to the number
of unknowns, the known values you have supplied may still cause
the equations to be illegal. You must not over-specify an equation,
so that nothing can be solved for in the equation.
Mathematical You can use the following mathematical operators in equations and
Operators in assignments:
Equations

Operator Usage Description


+ x+y Addition
- x-y Subtraction
- -x Negation
* x*y Multiplication
/ x/y Division
^ x^3 Raised to the power of
SIN SIN(x) Sine
SINH SINH(x) Hyperbolic sine
COS COS(x) Cosine
COSH COSH(x) Hyperbolic cosine
TAN TAN(x) Tangent
TANH TANH(x) Hyperbolic tangent
ASIN ASIN(x) Arc sine
ACOS ACOS(x) Arc cosine
ATAN ATAN(x) Arc tangent
SQRT SQRT(x) Square root
SQR SQR(x) Square of
EXP EXP(x) Exponent
LOGe LOGe(x) Natural logarithm
LOG10 LOG10(x) Logarithm to base 10
ABS ABS(x) Absolute value of
SIGMA SIGMA(x,y,...) Sum values of a list of arrays and variables
PRODUCT PRODUCT(x,y,…) Product of a list of arrays and variables
MAX MAX(x,y,…) Maximum value in a list of arrays and variables
MIN MIN(x,y,…) Minimum value in a list of arrays and variables
TIME TIME Current simulation time
DELAY DELAY x BY lag Applies a lag to the value of a variable

4-12 • Modeling Language for Models Modeling Language Reference


TRUNCATE TRUNCATE(x) Removes the fractional part of floating point value x and gives the
result as an integer
ROUND ROUND(x) Rounds the floating point value x away from zero to the next integral
value and returns the result as an integer. For example:
ROUND(-1.9) -> -2
ROUND(-1.5) -> -2
ROUND(-1.3) -> -1
ROUND(-1.0) -> -1
ROUND(1.9) -> 2
ROUND(1.5) -> 2
ROUND(1.3) -> 1
ROUND(1.0) -> 1
Note Ensure that trig functions are given in radians.

Equation Example
The following is a simple flow continuity equation. FlowIn and
FlowOut are variable defined for the model. The name
MaterialBalance is optional.
MaterialBalance : FlowIn = FlowOut ;
Input1.Flow and Output1.Flow are port variables. AdditionalFlow
is a variable defined in the model. Both types of variable can be
freely mixed.
Input1.Flow + AdditionalFlow = Output1.Flow ;

Equations with Array Variables


Use the following syntax to describe arrays in equations, and to
assign values to array variables.

Array Variable Syntax

ArrayVariable
ArrayVariable(Element)
ArrayVariable( [ElementA, ElementB, ...] )
ArrayVariable( [ElementA : ElementB ] )
ArrayVariable ( SetName )

ArrayVariable ................... Variable defined as an array


Element, ElementA, ........ A single element identifier. Can be either an integer,
ElementB an integer expression, or a string of text.
SetName........................... Name of a previously defined set

Modeling Language Reference Modeling Language for Models • 4-13


Array Variable Remarks
You can freely mix array variables with normal scalar variables.
If you refer to every element in an array in an equation, you need
not explicitly state the array elements.
Lists of array elements are separated by commas.
You can refer to slices of integer arrays in numerical order by
listing the first and last elements in the slice with the : (colon)
character between the elements.

Array Variable Examples


In the following example, the equation statement FlowIn =
FlowOut ; creates four equations, one for each of the array
elements. The variable definitions of FlowIn and FlowOut are both
equivalent. SetFlow is defined as a scalar non-array variable.
MODEL Test
Ncomps AS IntegerParameter(4);
Index AS IntegerSet([1:Ncomps]);
FlowIn(Index), FlowOut([1:Ncomps]), SetFlow AS
MolFlow ;
FlowIn = FlowOut ;
END
The following examples are also valid:
FlowIn(1) = FlowOut(1) ;
FlowIn(1) = FlowOut(2) ;
FlowIn([1,2,3]) = FlowOut([1:3]) ;
In the next example, SetFlow is not an array. Four equations are
created and each element of FlowIn equals SetFlow.
FlowIn = SetFlow ;
In the following example, the first three elements of FlowIn equal
SetFlow. The fourth element of FlowIn has not been defined yet,
but has to be defined at some point:
FlowIn( [1, 2, 3 ] ) = SetFlow ;
The final example is legal, even though the number of elements on
either side of the equation is not equal:
FlowIn( [1, 3, 4] ) = FlowOut ;
This expression is interpreted as the intersection of the left and
right hand side. Three equations are produced from this expression:
FlowIn(1) = FlowOut(1);
FlowIn(3) = FlowOut(3);
FlowIn(4) = FlowOut(4);

4-14 • Modeling Language for Models Modeling Language Reference


Conditional Equations
You can use conditional equations in model descriptions to change
the equations that are used depending on process variables during
the simulation.
You can also use conditional equations to make structural changes
to the models used in the flowsheet depending on parameters.
Structural changes cannot be made during simulation.
Conditional equations are defined by the keywords IF...THEN ...
ELSE ... ENDIF.

Conditional Equation Syntax

IF ConditionalExpression THEN
Equation1A;
Equation2A;
.
Assignment1A;
Assignment1B;
.
ELSE
Equation1B;
Equation2B;
.
Assignment2A;
Assignment2B;
.
ENDIF

ConditionalExpression ... Expression containing logical operators


Equation1A, ..................... Equation statements
Equation 2A
Equation 1B
Equation 2B
Assignment1A, ................ Assignment statements
Assignment 2A
Assignment 1B
Assignment 2B

Conditional Equation Remarks


The conditional expression returns a value of either True or False.
If the expression is true, the first set of equations and assignments
are used. If the expression is false, the second set of equations and
assignments are used.
Each branch of the conditional expression can take either a list of
equations, a list of assignments, or both equations and assignments.
For run-time conditionals dependent on process variables, the two
lists of equations must contain the same number of equations and

Modeling Language Reference Modeling Language for Models • 4-15


the same variables, to keep the simulation square and complete.
For situations where there are a large number of branches in a run-
time conditional, consider using a Switch statement.
For structural conditionals dependent on parameters, the two lists
of equations can contain different numbers of equations and use
different variables.
The conditional expression must contain at least one logical
operator or be a logical parameter.
You can use the following logical operators:

Operator Meaning

== (two equals signs) Equal to


> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
AND Logical AND function
OR Logical OR function
NOT Logical NOT function

Notes
• The three logical functions are evaluated in the priority
order: NOT, AND, OR.
• Two logical functions may not appear in sequence unless the
second one is the NOT operator.
• To avoid ambiguities in your logical expressions, use
parentheses to define the expression.

4-16 • Modeling Language for Models Modeling Language Reference


Conditional Equation Example
The following run-time conditional equation represents a tank
where both the inlet and outlet pipes are submerged below the
liquid level. The conditional expression accounts for flow reversal.
IF Input.Press >= Output.Press THEN
Input.Flow - Output.Flow = $Volume ;
Output.Flow = K * SQRT (LiquidLevel) ;
ELSE
Output.Flow - Input.Flow = $Volume ;
Input.Flow = K * SQRT (LiquidLevel) ;
ENDIF
The next example shows a structural conditional based on a logical
parameter whose value is TRUE:
IF IncludeValve THEN
Output1.Pressure = Input1.Pressure -
Cv*Output1.Flow;
Cv : 10.0, FIXED;
ELSE
Output1.Pressure = Input1.Pressure;
Cv : 1.0e6, FREE;
ENDIF
The following example shows a structural conditional based on a
logical parameter that has a value of FALSE, using the logical
NOT function:
IF NOT Feed.IsConnected THEN
$Holdup = Inlet.F – Outlet.F;
ELSE
$Holdup = Inlet.F + Feed.F – Outlet.F;
ENDIF
In the next example, the not-equal-to operator, <>, is used to
decide how pressure is calculated dependent on the value of the
string parameter, ModeOfOperation.
IF ModeOfOperation <> "PressureDriven" THEN
// ModeOfOperation has the value FlowDriven
// Find minimum inlet pressure
Pin = MIN(Inlet.Connection.P);
ELSE
// ModeOfOperation has the value
PressureDriven
// Equate inlet pressures
Inlet.Connection.P = Pin;
ENDIF

Modeling Language Reference Modeling Language for Models • 4-17


The next example shows the use of more than one operator in a
conditional expression using the logical OR function. It shows how
to avoid a divide by zero error, or the evaluation of the log of zero
for the evaluation of LMTD (log mean temperature difference).
IF DT_Inlet * DT_Outlet <= 0.0 OR DT_Inlet == DT_Outlet THEN
LMTD = (DT_Inlet + DT_Outlet) * 0.5;
ELSE
LMTD =( DT_Inlet – DT_Outlet) / LOG (ABS (DT_Inlet / DT_Outlet));
ENDIF
The following example shows a run-time conditional equation
using the logical AND function to calculate the heat transfer area
that is dependent on the level of liquid present within an
evaporator.
IF level < level_low THEN HT_Area = 0;
ELSEIF (level > level_low AND level <= level_high) THEN
HT_Area * (level_high – level_low) = MaxHT_Area * (level – level_low);
ELSE
HT_Area = MaxHT_Area;
ENDIF

Using Sets in Conditional


Expressions
You can use sets in a conditional expression to test whether a
parameter is equivalent to an element in a set.

Sets in Conditional Expressions Syntax

IF Parameter IN SetDefinition THEN


...
ELSE
...
ENDIF

Parameter......................... String or Integer Parameter


SetDefinition .................... IntegerSet or StringSet

4-18 • Modeling Language for Models Modeling Language Reference


Sets in Conditional Expressions Remarks
The condition in this case can be interpreted as “if the parameter
exists within the SetDefinition, then true, else false”.

Sets in Conditional Expressions Example


The following IF statement tests that a string parameter is assigned
to a value in a set of strings.
Components1 AS StringSet(["CH4","C2H6"]);
IF KeyComponent IN Components1 THEN ...
The above statement is equivalent to:
IF (KeyComponent == "CH4") OR (KeyComponent ==
"C2H6") THEN ...

FOR Loops
FOR loops enable you to simplify repetitive statements. FOR loops
are useful for handling arrays with large numbers of elements, or
more than one dimension.

FOR Loop Syntax


The following syntax is used for FOR loops:

FOR Index IN SetDefinition DO

statements;

ENDFOR

Index................................. Index variable unique to this FOR loop


SetDefinition .................... Either a set name, set definition or a *set expression
between [ and ] (brackets)
statements ....................... A number of statements using the Index variable
*(i.e. operations between sets), which is something that can be
useful to know, as for example:
// set flow to 0 for every component except water
for i in Componentlist - ["H2O"] do F(i) : 0;
endfor

FOR Loop Remarks


The index value is a counter that is incremented for each iteration
of the FOR loop. The statement uses the index value to produce a
different statement at each iteration. Note that there is no implied

Modeling Language Reference Modeling Language for Models • 4-19


order for the iteration of the index, particularly when the set is a set
of strings.
Statements can be either equations or assignments.

FOR Loop Example


In the following example, the ComponentList is defined as
Nitrogen, Oxygen, and Carbon Dioxide. The index counter in the
FOR loop, I, takes the value "N2", "O2" and "CO2", and three
equations and three assignments are created.
MODEL Test
FlowIn(ComponentList), FlowOut(ComponentList) AS
Flow_Mol ;
Split(ComponentList) AS Fraction ;
FOR I IN ComponentList DO
FlowIn(I) = Split(I) * FlowOut(I) ;
Split(I) : 0.33, FIXED ;
ENDFOR
END
Note that for this example, it is valid to write the equation without
the For loop:
FlowIn = Split * FlowOut;
In this case, the number of equations created is based on the
intersection of the sets defining the variables in the equation. As all
three array variables are indexed by the same set, an equation is
generated for each component.
The next example shows how to instance a number of the same
model within a larger model and how to simplify repetitive
CONNECT statements.
Note that you can do simple integer arithmetic on the index value
and the set that defines the number of FOR loops.

4-20 • Modeling Language for Models Modeling Language Reference


MODEL Column
NStage AS IntegerParameter(20) ;
StageSet AS IntegerSet([1:NStage]);
Stage(StageSet) AS Tray;

FOR J IN [2:NStage -1] DO


CONNECT Stage(J).LiqOutFlow AND Stage(J+1).LiqInFlow ;
CONNECT Stage(J).VapOutFlow AND Stage(J-1).VapInFlow;
ENDFOR
.
.
END
In the previous example NStage is assigned a value of 20 in the
model. The value of the parameter NStage can be overwritten for
the block on the flowsheet that uses this model.
FLOWSHEET
Col1 AS Column ;
Col1.NStage: 30 ; /* Change number of trays from
default to 30*/
.
.
END

ForEach Operator
The ForEach operator is the equivalent of the For operator, but is
used only with list operators, that is:
• SIGMA
• PRODUCT
• MIN
• MAX
• UNION
• INTERSECTION
• DIFFERENCE
• SYMDIFF

List Operator Syntax


The following syntax is used for list operator expressions:

ListOperator(expression1, expression2, …)

ListOperator..................... Can be SIGMA, PRODUCT, MIN, MAX, UNION,


INTERSECTION, DIFFERENCE, or SYMDIFF
expressionn ..................... Any normal modeling language expression, for example,
a variable name, a number, and so on. Can also be a
ForEach expression, as shown in the following syntax.

Modeling Language Reference Modeling Language for Models • 4-21


ForEach Expression Syntax
The following syntax is used for ForEach expressions:

ForEach(IndexExpression1, IndexExpression2, …) expression

IndexExpressionn ........... IteratorVar IN SetExpression


expression ....................... Must be valid type for the list operator, for example, if
the operator takes a list of set expressions then
The
expression must be a set expression.

ForEach Examples
The following is a simple matrix multiplication example:
Index([1:n]) as IntegerSet;
A(Index, Index), B(Index, Index), C(Index, Index) as RealVariable;
For i in Index DO
For j in Index DO
C(i,j) = Sigma(ForEach (k in Index) A(i,k)*B(k,j) );
EndFor
EndFor
The result of the above for n = 2 would be the following equations
C(1,1) = sigma(A(1,1)*B(1,1), A(1,2)*B(2,1)); // i=1, j=1
C(1,2) = sigma(A(1,1)*B(1,2), A(1,2)*B(2,2)); // i=1, j=2
C(2,1) = sigma(A(2,1)*B(1,1), A(2,2)*B(2,1)); // i=2, j=1
C(2,2) = sigma(A(2,1)*B(1,2), A(2,2)*B(2,2)); // i=2, j=2
The following example is a legal statement using ForEach with
sigma:
sigma(foreach (i in set) x(i)) = 0;
Result when set = [1:3]:
sigma(x(1), x(2), x(3)) = 0;
The second example is also a legal statement:
sigma(foreach(i in set1, j in submodel(i).set) model(i).x(j) ) = 0;
Result when set1 = ["a", "b"], submodel("a").set = [1,2],
submodel("b").set = [3,4]:
Sigma(model("a").x(1),model("a").x(2),model("b").x(3),model("b").x(4
)) = 0;
The third example is also a legal statement:
sigma(foreach(i in set1) x(i), foreach(i in set2) y(i) ) = 0;
Result when set1 = ["a", "b"] and set2 = [1,2]:

4-22 • Modeling Language for Models Modeling Language Reference


sigma(model("a").x(1),model("a").x(2),model("b").x(1),model("b").x
(2)) = 0;
Note the following illegal statement:
sigma(foreach(i in set1) x(i), y(i)) = 0;
In this statement, i is not declared for the second expression. The
legal form of this expression is:
sigma(foreach(i in set1) sigma(x(i), y(i)) );

Equations that Call Procedures


You can use procedure calls in models to use an external routine to
make calculations. You must define the procedure call in a
Procedure definition.

Procedure Call Syntax

CALL (OutputArgumentList) = ProcedureName(


InputArgumentList ) ComponentList, TEAR;

ProcedureName............... Name of a procedure definition


InputArgumentList .......... List of variables in the order of the procedure definition
inputs
OutputArgumentList ....... List of variables in the order of the procedure definition
outputs
ComponentList................ Optional name of a component list property that applies
to this individual call. The component and
thermodynamic properties associated with this list are
used in property calculation calls. A value is required
only when you want to override the default component
list. For an example, see Using More Than One
Component List in Models in Chapter 3.
TEAR ................................ Optional. Specifies that this instance of the procedure is
torn. For information on tearing, see the Aspen Modeler
Reference, Chapter 6.

Procedure Call Remarks


The order of the argument lists has to be the same as the order of
the variable types in the procedure definition. The variable types
have to be of a related type to the types in the procedure definition
lists.
You can declare procedure calls at any point in the model
definition after you have defined the variables used in the
procedure call.

Modeling Language Reference Modeling Language for Models • 4-23


Procedure Call Example
In the following example, VolCalc is the name of a procedure
definition:
CALL (TankVolume) = VolCalc ( TankHeight, TankArea ) ;
The next example shows how to use the component list name after
a procedure call to determine the components and properties used
in the procedure calculation.
CALL (EnthOut) = Enthalpy ( MolFracOut, PressOut, TempOut ) Process ;
The enthalpy calculation is carried out using the component list
Process. The component list can be different using the same
property calculation procedure but using different components and
thermodynamic properties options.

Equations that Refer to Port


Variables
Use port variables in equations to refer to the values being passed
between blocks. Use the following syntax to refer to a port
variable.

Port Variables Syntax

PortName.PortVariableName

PortName ......................... Name of the port in the model


PortVariableName ........... Name of the port variable in the port definition

Port Variables Remarks


When you declare a port in a model, you can refer to all the
variables defined in the port’s type definition.

4-24 • Modeling Language for Models Modeling Language Reference


Port Variable Example
This example defines a port type, a model, and a flowsheet. The
example shows a value being assigned to a port variable.
PORT Main
Flow AS Flowrate ;
Temp AS Temperature ;
Press AS Pressure;
END
MODEL SimpleValve
// Define internal variable
DeltaP AS Pressure ;
/* Defined one inlet and one outlet port*/
Input1 AS INPUT Main ;
Output1 AS OUTPUT Main;
// Equations - pressure change only
Input1.Flow = Output1.Flow ;
Input1.Temp = Output1.Temp ;
Input1.Press - DeltaP = Output1.Press ;
END
FLOWSHEET
/*Define an instance of the valve model*/
Valve1 AS SimpleValve ;
/*Specify the value of a port variable*/
Valve1.Input1.Flow : 12.5, Fixed ;
END

CONNECT Keyword
You use connection statements to connect ports and variables in a
flowsheet. You have the option of connecting ports with a stream.
Use the CONNECT keyword to connect ports of compatible
directions in the flowsheet. You can use CONNECT in model
definitions and in flowsheet definitions.
For information on when to use CONNECT, and how to connect
ports and variables, see Connectivity Rules.

Modeling Language Reference Modeling Language for Models • 4-25


CONNECT Syntax

Name : CONNECT BlockName.PortName AND


BlockName.PortName WITH StreamName ;

or

Name : CONNECT BlockName.VariableName via portname AND


BlockName.VariableName via portname WITH StreamName;

Name ................................ Name of the connection for display


CONNECT ........................ CONNECT keyword
BlockName....................... Name of the block in the flowsheet or model
PortName ......................... Name of the port in the model
VariableName Name of a variable that has been defined as measured
or manipulated
StreamName .................... Name of the stream in the flowsheet or model. For
connecting variables, the stream must be of built-in
type ControlSignal
portname.......................... Optional name of the Controlport through which the
connection should be made

CONNECT Remarks
The following table shows the results of specifying port names:

If you specify Then

One port name only The first port becomes either a feed or a product
port, depending on the direction of the port
Two port names One port must be an inlet and the other an outlet.

If you do not specify a stream, the ports are connected with a


stream of an automatically generated name using the built-in
stream type Connection. The Connection stream equates port
variables of the same name and defines them as having equal
values.
Caution If you connect two ports of different types, there may be
a mismatch in the variable list. The values that are passed over the
connections are the intersection of the variables between the two
ports. That is, the variables with names common to both ports are
transmitted.
This means you can have fewer equations in your simulation than
you expected, because the stream does not create an equivalence
equation for all the variables in the ports. This usually makes the
flowsheet under-specified. If you find your simulation is under-

4-26 • Modeling Language for Models Modeling Language Reference


specified when you believe that the models are correctly defined,
check for port mis-matching on the flowsheet.
If you use the CONNECT statement to connect variables in a
flowsheet, you must use the built-in stream type ControlSignal. All
control variables in sub-models are accessible in the containing
model. You do not need to use LINK in order to connect a control
variable from a sub-model to a control variable of the same
direction in a containing model.
When you connect variables with ControlSignal, the downstream
variable spec property is checked:
• If the downstream variable was Fixed before it was
connected, it is now made Free.
• If you subsequently disconnect the ControlSignal or delete
the connection, the downstream variable is made Fixed.
These two actions preserve the degrees of freedom of your
flowsheet without manual intervention as you add, remove, or
reconnect control elements.
Tip To change the way this feature works, from the Tools menu
click Settings, and then change the setting on the Control Stream
Connections tab.
CONNECT The following restrictions apply when using CONNECT:
Restrictions • You cannot use a CONNECT statement to directly connect
arrays of variables or ports. The following example is
therefore illegal:

a([1:nStage]) as ModelType1;
b([1:nStage]) as ModelType2;
connect a.outlet and b.inlet; // Illegal implicit loop

However, you can use a CONNECT statement to connect


arrays of variables or ports using a FOR loop, as shown in
the next example:
a([1:nStage]) as ModelType1;
b([1:nStage]) as ModelType2;
FOR i IN [1:nStage] DO connect a(i).outlet and b(i).inlet;
ENDFOR
• FOR loops in the flowsheet cannot contain CONNECT
statements. This is because the flowsheet cannot contain the
array of streams required to make the connections.
• A CONNECT statement without a defined stream cannot
appear in nested FOR loops where the index for any inner
loop is dependent upon the index variable of an outer loop.
This is because you cannot declare a suitable stream array to
connect the ports or variables. The following example is

Modeling Language Reference Modeling Language for Models • 4-27


therefore illegal:

nStage as IntegerParameter;
a([1:nStage]) as ModelType1;
b([1:nStage]) as ModelType2;
FOR i IN (1:a.nStage] DO
FOR j IN [1:a(i).nArraySize] DO
// j is dependent upon i the outer
loop index variable
connect a(i).x(j) and b(i).y;
// nested FOR loop too complex for
CONNECT statement
ENDFOR
ENDFOR

CONNECT Examples
The following examples show the different options available for
the CONNECT keyword.
The first example shows the port Valve.Outlet is not connected to
another port. On the flowsheet the unconnected end of the stream is
shown as a product.
CONNECT Valve.Outlet ;
Then the ports Valve.Outlet and Tank.Inlet are connected with a
universal stream:
CONNECT Valve.Outlet AND Tank.Inlet ;
In the following example, the ports Valve.Outlet and Tank.Inlet are
connected with the stream called Stream1. Stream1 is defined
before this statement as using a defined Stream Type:
CONNECT Valve.Outlet AND Tank.Inlet WITH Stream1 ;
The next example shows the connection named as S1. This name
overrides the default connection name in the flowsheet display:
S1 : CONNECT Valve.Outlet AND Tank.Inlet ;
The next example shows the connection named S1 using the
stream named Stream1:
S1 : CONNECT Valve.Outlet AND Tank.Inlet WITH
Stream1 ;

4-28 • Modeling Language for Models Modeling Language Reference


The final example shows two variables connected with the built-in
stream type ControlSignal:
Conn1 AS ControlSignal;
CONNECT Tank1.Temp AND C101.SigIn WITH Conn1;

LINK Keyword
Use the LINK keyword to define a connection to a containing
model's ports from the ports of sub-models within the containing
model. Use LINK to connect ports of the same direction. If the
ports are of different directions, use CONNECT.
For information on when to use LINK, and how to connect ports,
see Connectivity Rules.

LINK Syntax

Name : LINK PortName AND ModelName.PortName ;

Name ................................ Name of the link connection for display


LINK.................................. LINK keyword
ModelName ...................... Name of the model instance within the holding model
PortName ......................... Name of the port in the model

LINK Remarks
Use the LINK keyword when you have a list of sub-models within
a containing model. Use the CONNECT keyword for connections
within the containing model. LINK enables you to attach an
internal connection to one of the containing model’s ports.
You can connect two ports of the same direction with the LINK
keyword.
You must specify two port names in a LINK statement, one of
which is the port name for the containing model.
You cannot use LINK in the flowsheet definition. You must use
LINK only in a model definition.
LINK Restrictions The following restrictions apply when using LINK:
• You cannot use a LINK statement to connect arrays of
variables or ports. The following example is therefore
illegal:

Modeling Language Reference Modeling Language for Models • 4-29


feed([1:nStage]) as input PortType1;
stage([1:nStage]) as ModelType2;
link feed and stage.inlet; // illegal implicit
loop

However, you can use a LINK statement to connect arrays


of variables or ports in a FOR loop, as shown in the next
example:
feed([1:nStage]) as input PortType1;
stage([1:nStage]) as ModelType2;
for i in [1:nStage] do
link feed(i) and stage(i).inlet;
endfor
• A LINK statement without a defined stream cannot appear
in nested FOR loops where the index for any inner loop is
dependent upon the index variable of an outer loop. This is
because you cannot declare a suitable stream array to link
the ports or variables. The following example is therefore
illegal:
nStage as IntegerParameter;
Feed([1:nStage]) as input Multiport of Fluid;
Stage([1:nStage]) as StageModel;
for i in [1:nStage] do
for j in Feed(i).Connectionset do
// j is dependent upon i the outer
loop index variable
link Feed(i).Connection(j) and
Stage(i).Outlet;
// nested FOR loop too complex for LINK
statement
ENDFOR
ENDFOR

4-30 • Modeling Language for Models Modeling Language Reference


LINK Examples
In the following example, the LINK keyword is used to connect a
port from the model Tank to a port of the model MultiTank. The
Tank models are instanced within the model MultiTank. This
method enables you to group models within one containing model.
MODEL MultiTank
/* Define one inlet and one outlet port*/
Input1 AS INPUT FluidStream ;
Output1 AS OUTPUT FluidStream ;
/* Define the sub-models of Tank in the
containing model*/
Tank1 AS Tank ;
Tank2 AS Tank ;
Tank3 AS Tank ;
/* Use LINK for external connections outside of
the containing model*/
LINK Tank1.Input1 AND Input1 ;
LINK Tank3.Output1 AND Output1 ;
/* Use CONNECT for internal connections within
this model*/
CONNECT Tank1.Output1 AND Tank2.Input1 ;
CONNECT Tank2.Output1 AND Tank3.Input1 ;
/* MultiTank completed*/
END
You can use LINK to connect to multiports, either where the
containing model has a multiport and/or the submodel has a
multiport.
A common situation where you might link to a multiport is where
you have a distillation column modeled by an array of stages. You
can define the feed to the column as a multiport. This allows
multiple feeds to the stages in the column.
MODEL Column
.
Feed AS INPUT MULTIPORT OF Material;
StageMap(Feed.ConnectionSet) AS
IntegerParameter(1);
Nstages AS IntegerParameter(20);
Stage([1:Nstages]) AS TrayModel;
FOR i IN Feed.ConnectionSet DO
FeedStage: LINK Feed.Connection(i) AND
Stage(StageMap(i)).TrayFeedPort ;
ENDFOR
.
END
In this example, the key is the array StageMap. You can define the
stage numbers in StageMap for each of the connections made to
the column. For example, if you have three connections to the

Modeling Language Reference Modeling Language for Models • 4-31


column's Feed port, you can define which stage these connect to, so
that StageMap is an array of three elements indexed by the
connections to the Column. For example:
StageMap("S1").Value : 5;
StageMap("S2").Value : 11;
StageMap("S3").Value : 14;

Connectivity Rules
Connect ports in models as shown in the following table:

To connect ports To ports belonging Use


belonging to to

Sub-models Sub-models CONNECT


Sub-models Containing models LINK

Connectivity Rules for CONNECT


When using the CONNECT statement, connect ports and variables
according to the following table:

Connect this port / variable To this port / variable

INPUT OUTPUT
OUTPUT INPUT

Connectivity Rules for LINK


When using the LINK statement, connect ports according to the
following table:

Link this port To this port

INPUT INPUT
OUTPUT OUTPUT

4-32 • Modeling Language for Models Modeling Language Reference


Using SIGMA
Use the SIGMA keyword to sum values in expressions. Typically
the expressions contain array variables. You can use the SIGMA
function in models.

SIGMA Syntax
The syntax for using SIGMA is:

SIGMA ( Expression );

SIGMA .............................. Keyword


Expression....................... Expression using variables

SIGMA Remarks
The SIGMA function is normally applied to expressions containing
arrays. You can sum the whole array or a defined slice of an array.
If you use an array variable in sigma without any qualification, all
the values in the array are summed.
You can apply SIGMA to multidimensional arrays. To control the
way SIGMA works, you define the extent of the arrays to be
summed. You can also use SIGMA to sum the variables in
multiports.

SIGMA Examples
The most basic use of the SIGMA function is to sum non-array
variables or values:
A1, A2, A3, B1 AS RealVariable;
B1 = SIGMA (A1, A2, A3, 2.0 );
The SIGMA command is interpreted as:
B1 = A1 + A2 + A3 + 2.0
More typically, SIGMA is used to sum elements of arrays:
ComponentList AS StringSet(["N2", "O2", CO2"]);
x(ComponentList) AS Fraction;
SIGMA(x) = 1.0;
In this example, x is an array, so SIGMA(x) calculates the sum of
the values in the array. The SIGMA command is interpreted as:
x("N2") + x("O2") + x("CO2") = 1.0

Modeling Language Reference Modeling Language for Models • 4-33


Another way you can write the expression is to state the array
explicitly:
SIGMA(x("N2"),x("O2"),x("CO2")) = 1.0;
The following statement is equivalent to the previous SIGMA
expression:
SIGMA(x(ComponentList)) = 1.0 ;
You can use SIGMA on the whole array, or a selected slice of an
array.
Nsect AS IntegerParameter(10);
Sections AS IntegerSet([1:nsect]);

Temp(Sections) AS Temperature;
x, y AS RealVariable;

x = SIGMA(Temp);
y = SIGMA(Temp([2:Nsect]));
You can remove an element of a set from the calculation in the
SIGMA expression:
NonWaterFraction AS Fraction;
x(ComponentList) AS Fraction;
SIGMA(x(ComponentList - ["WATER"])) =
NonWaterFraction;
In this example, SIGMA is used to sum the fractions of all the
components in a component list except for water.
Using SIGMA for You can use SIGMA to sum arrays that contain more than one
Multidimensional dimension.
Arrays and Multiports
SIGMA( Variable(Dim1, Dim2, ..., Dimn) )

or

SIGMA( Array.Array. ... )

Variable ............................ Name of an array variable of n dimensions


Dim1, Dim2, Dimn............ Set expressions that define the index of the array
dimensions
Array................................. Array element in an object path, such as an array of
models, an array of ports, a multiport, an array
variable

4-34 • Modeling Language for Models Modeling Language Reference


SIGMA for Multidimensional Arrays Examples
You can create an expression that contains more than one
dimension that can be expanded:
PORT Material
F AS Flow;
z(ComponentList) AS Fraction;
END
MODEL Tank
M, Mc(ComponentList) AS Holdup;
Total AS RealVariable;
Input1 as INPUT MULTIPORT OF Material;
Total = SIGMA(Input1.Connection.z);
END
In this example, there are two index sets:
• The multiport set Input1.ConnectionSet,which indexes
Input1.Connection
• The component set Input1.Connection(i).ComponentList,
which indexes Input1.Connection(i).z
In this case SIGMA performs an expansion that generates all
possible expansions so that Total would equal the sum of z for all
components in all the connections to the multiport.
The expression is expanded to:
Total = Input1.Connection("S1").z("C1") +
Input1.Connection("S1").z("C2") + ...
+ Input1.Connection("S1").z("Cn")
+ Input1.Connection("S2"). z("C1") +
Input1.Connection("S2").z("C2") + ... +
Input1.Connection("S2").z("Cn")
+...
+ Input1.connection("Sm"). z("C1") +
Input1.Connection("Sm").z("C2") + ... +
Input1.Connection("Sm").z("Cn");
Another example is where you have a sub-model flowsheet in
which the sub-models have multiports. You get a path:
MODEL MultiTank
Ntank AS IntegerParameter(10);
Tank([1:Ntank]) AS MultiMixTank;
CONNECT ...
Sum1 = SIGMA(Tank.Input1.Connection.z *
Tank.Input1.Connection.Flow)
END

Modeling Language Reference Modeling Language for Models • 4-35


In this case, the sigma expression has to evaluate the expression:
SIGMA(
Tank([1:Ntank]).Input1.Connection(ConnectionSet).
z(ComponentList) *
Tank([1:Ntank]).Input1.Connection(ConnectionSet).
Flow )
As in the previous example, all combinations of model array,
multiport array and component array, are calculated and summed.
Use the ForEach operator to override the default expansion of
arrays within SIGMA. For more information, see ForEach Operator
on page 4-21.

Using the SIZE Function


You can use the SIZE function on a Set to determine the number of
elements in that set. This can be useful for determining a default
initial specification for molefractions in a model, for example.
Size can be applied to integer and string sets. It returns an integer
value of the number of elements in the set.
Note Size may not be used in an equation (or procedure call)
statement, or in the condition part of a run time If statement.

SIZE Syntax

SIZE ( SetName )

SetName................... Name of an integer or string set

SIZE Example
In the following example SIZE is used to determine the number of
components used in a model, and calculates some default values
for the molefractions of the components.
MODEL Feed
x(ComponentList) AS Molefraction(fixed);
.
x(ComponentList) : 1 / SIZE(ComponentList) ;
.
END
The SIZE function calculates the size of the ComponentList Set. A
value of one over the number of components is used as an default
value for the fixed molefraction array variable.

4-36 • Modeling Language for Models Modeling Language Reference


Assigning Specifications in Models
You can assign a specification to a variable or parameter either
when you declare it, or after its declaration. For assigning the
specification after the variable or parameter is defined, the syntax
is the same as the syntax for defining specifications in the
flowsheet, except that the block name is not required.

Syntax for Assigning Specifications in Models


The syntax for defining specifications in models is:

VariableName.Spec : Fixed|Free|Initial|RateInitial ;

– or –

VariableName : Value, Specification ;

– or –

ParameterName.ParameterProperty : PropertyValue;

– or–

ParameterName : PropertyValue ;

VariableName .......... Name of a variable in the model


Spec ......................... Name of a variable property in the model
ParameterName....... Name of a parameter in the model
ParameterProperty.. Name of a parameter property in the model
PropertyValue.......... Integer, real, logical or string value assigned to the
variable or parameter. Can be Fixed, Free, Initial,
or RateInitial
Value ........................ Value for the variable
Specification ........... Specification for the variable. If you do not
specify a value, Free is assumed. Valid values are:
The
Fixed A variable whose value is not being
solved for
Initial A variable whose value is known at
time zero for an initialization or
dynamic run
RateInitial A state variable whose time derivative
is known at time zero for an
initialization or dynamic run
Free A variable whose value is being solved
for
The
The specification Initial means that the state
variable itself is initialized, whereas RateInitial
applies to the time derivative. The two are
mutually exclusive specifications. Similarly, you
cannot fix the state variable and initialize the time
derivative. This helps to ensure that you do not
give incorrect specifications.

Modeling Language Reference Modeling Language for Models • 4-37


Assigning Specifications in Models Example
The following example shows the declaration of a variable called
Temp. Temp is then given a value and a fixed specification. This
specification can be overwritten in the flowsheet or by the GUI.
Temp AS Temperature;
Temp: 100.0, Fixed;
Alternatively the specifications can be supplied as part of the
variable declaration.
Temp AS Temperature (100.0, Fixed);
The specifications in the model need not provide the complete
information for the simulation. You may choose to include only the
value or the specification, or both in separate statements.
Temp : 100.0 ;
This means that the temperature is not fixed in the model. You can
define Temp as fixed later when you build the flowsheet. If the
variable remains not fixed, the value is used as the starting value
for the solution routines.
Temp : Fixed ;
This means you are stating that the variable Temp is fixed in the
model, but you are not assigning it a value. You can assign the
value later in the flowsheet, or you can make the variable Free for
the block in the flowsheet by using the variables table.
Similarly, you can define a variable to have the specification of
Initial within the model. In the following example, the variable
Level is declared and is then given a value and an Initial
specification. This specification can be overwritten in the
flowsheet or by the GUI:
Level AS Length;
Level: 1.5, Initial;
Alternatively, you can supply the specifications when the variable
is declared:
Level AS Length (1.5, Initial);
The following example shows how a specification of Initial is
made for a derivative, by assigning the specification RateInitial to
the state variable:

4-38 • Modeling Language for Models Modeling Language Reference


Mass AS Holdup_mass;
Mass.derivative: 0;
Mass.spec: rateinitial;
– or –
Mass AS Holdup_mass;
$Mass: 0;
Mass : rateinitial;
Note Initial means the state itself is initialized. RateInitial means
that the derivative has the specification of Initial.

Referring to Sub-Models in a Model


Definition
You can refer to equations in sub-models directly from a model
without using the LINK keyword to establish communication
between the containing model and the sub-models.

Syntax for Referring to Sub-Models in a Model Definition


You can refer to equations in sub-models directly by defining an
instance of a model within a containing model. You can then refer
to a variable in the sub-model using the following syntax:

SubModelName.VariableName

In the statement where you declare the name of a sub-model, you


can optionally make equalities between sub-model variable and
parameter names and the containing model variable and parameter
names with the following syntax:

SubModelName AS
ModelName( SubModelVariable = ModelVariable, ...,
SubModelParameter : ModelParameter, ... ) ;

You can also instance sub-models that are dependent on parameter


values with the following syntax:

SubModelName ([1:(condition)]) AS
ModelName( SubModelVariable = ModelVariable, ...,
SubModelParameter : ModelParameter, ... )

Modeling Language Reference Modeling Language for Models • 4-39


This declares an array of sub-models. The array will be empty
when the condition is false (0), because the integer set is then [1:0],
which is an empty set. The array will be one element when the
condition is true (1), as the integer set is then [1:1]. The declaration
will thus instance the sub-model only when the condition is true.
When you want to instance the submodel only when a parameter X
is equal to a value Y, you would use as the condition above the
expression (X==Y).

Referring to Sub-Models Examples


The following example shows a single equation sub-model used in
a containing model:
MODEL VolCalc
Vol AS Volume;
R AS Length;
h AS Length;
PiValue AS RealParameter;
VolumeCalc: Vol = PiValue * R^2 * h;
R: Fixed;
h: Initial;
END
MODEL Tank
k AS Constant;
height AS Length;
Radius AS Length;
PI as RealParameter(3.14159);
// sub-model
Vc AS VolCalc(R=Radius, h=height, PiValue:PI);
FlowIn AS INPUT Fluid;
FlowOut AS OUTPUT Fluid;
MaterialBalance: Vc.vol = FlowIn.flow -
FlowOut.flow ;
Outflow: FlowOut.flow*FlowOut.flow = K*K * Vc.h ;
k:Fixed;
END

4-40 • Modeling Language for Models Modeling Language Reference


In the following example, the sub-model used to calculate density
is dependent on the parameter Material. Here, the sub-model
RhoAl is instanced and the other is not:
MODEL Tank
Material AS MaterialType (description: "Material
type used");
:
//Using sub-model to calculate density
RhoAl([1:(Material=="Alkali")]) AS RhoAlkaliCalc
(RhoAlkali=Rho, X("NaOH”)=Inlet.X("NaOH"));
RhoAq([1:(Material=="Aqueous")]) AS
RhoAqueousCalc (RhoAqueous=Rho);
//Equations
:
END
FLOWSHEET
Tank1 as Tank (Material: "Alkali");
:
END

Using External Properties to Write


Sub-Models
Sub-models are often used to package together standard
calculations (for example, property calculations or partial
derivative calculations).
Normally, a sub-model declares all the variables it uses locally. A
containing model must equate its local variables with the variables
in the sub-model. To reduce the duplication of variables, you can
use the EXTERNAL declaration qualifier in the sub-model. The
EXTERNAL qualifier indicates that variables do not exist in the
sub-model but instead come from the parent of this model.
Note When you declare the properties of the sub-model as
EXTERNAL, you must remove the equivalence equations in the
containing model.
Example of Using Normally, a sub-model declares all the variables it uses locally, for
External Properties to example:
Write Sub-Models

Modeling Language Reference Modeling Language for Models • 4-41


Model FractionToFlow
TotalFlow as flow_mol;
Flow(componentlist) as flow_mol;
X (componentlist) as fraction;
Flow = TotalFlow * X;
End

To use this sub-model, the containing model must equate its local
variables with the variables in the sub-model, for example:
Model Simple
TotalFlow as flow_mol;
Flow(componentlist) as flow_mol;
X(componentlist) as fraction;
//Include submodel for conversion from
fractions to flows
convert as FractionToFlow(TotalFlow=TotalFlow,
X=X, Flow=Flow);
// Rest of models equations
End

This has introduced duplicates of each Flow and X variable and the
TotalFlow variable. To reduce the duplication of variables, you can
use the EXTERNAL declaration qualifier in the sub-model, for
example:
Model FractionToFlow
TotalFlow as EXTERNAL moleflow;
Flow(componentlist) as EXTERNAL flow;
X (componentlist) as EXTERNAL fraction;
Flow = TotalFlow * X;
End

The EXTERNAL qualifier indicates that the variables TotalFlow,


Flow, and X do not exist in the sub-model but instead come from
the parent of this model. For example, where TotalFlow is used in
the sub-model, it is the parent's TotalFlow variable that is used.
When you declare the properties of the sub-model as EXTERNAL,
you must remove the equivalence equations in the containing
model:

4-42 • Modeling Language for Models Modeling Language Reference


Model Simple
TotalFlow as moleflow;
Flow(componentlist) as flow;
X(componentlist) as fraction;
//Include submodel for conversion from
fractions to flows
// this operates directly on the TotalFlow,
Flow, and X variables
// of this model
convert as FractionToFlow;
// Rest of models equations
End

Now there is only one copy of the variables TotalFlow, Flow, and
X.

The containing model can redefine a sub-model's external


Changing the Default
properties using the IS operator in the declaration of the sub-
Mapping For External
model.
Properties

Example of Changing the Default Mapping for External


Properties
The following example demonstrates extending the example given
in Using External Properties to Write Sub-Models on page 4-41 to
apply to two sets of variables:
Model Simple
TotalX as flow_mol;
TotalY as flow_mol;
FlowX(componentlist) as flow_mol;
FlowY(componentlist) as flow_mol;
X(componentlist) as fraction;
Y(componentlist) as fraction;
//Include submodel for conversion from
fractions to flows
convertX as FractionToFlow(TotalFlow IS TotalX,
Flow IS FlowX);
// Include a second submodel to convert the Y
fractions
convertY as FractionToFlow(TotalFlow is TotalY,
Flow IS FlowY, X IS Y);
// Rest of models equations
End

Here convertX.TotalFlow will resolve to TotalX and


convertY.TotalFlow will resolve to TotalY.

Modeling Language Reference Modeling Language for Models • 4-43


Note the following points when writing sub-models:
Notes and
Restrictions on • An assignment to an external property may conflict with
Writing Sub-Models other assignments made to the same property.
Although you can assign external properties in the declaring
sub-model, you must be careful. The sub-model assignment
can conflict with an assignment to the same external
property from another sub-model. If assignments conflict no
warning is given and the result may be unpredictable.
• External arrays must be declared with consistent indexing.
If the indexes of the external property and the resolved
property do not match then array operations may be
expanded incorrectly. The parser does not check the
indexes for consistent use: this is the responsibility of the
model writer.
• When you edit models interactively, if you add or remove
external properties, you must recompile models using the
edited model.
Recompiling the models ensures that any changes are
completely propagated through the system.
• Models that use external properties can only be used as sub-
models: they cannot be placed directly onto the flowsheet.

Using Virtual Types in Sub-Models


Virtual types are used in sub-models where the types of the
properties can only be determined when the model is included in a
containing model.
Example of Using The following model is an example usage of VIRTUAL types, in
Virtual Types in Sub- this case to provide a generic model to calculate the average of a
Models vector of values:
Model AverageValue
VIRTUAL ValueType USES RealVariable;
NValues as external IntegerParameter;
Value([1:NValues]) as external RealVariable;
Average as ValueType;
Average = sigma(Value)/NValues;
End

The first statement declares that the type ValueType is a


VIRTUAL type derived from RealVariable. Properties of type
ValueType (that is, Average) are referred to as virtual properties.
By using a virtual type, it is then possible for the containing model
to redefine the types that will be used for virtual properties.

4-44 • Modeling Language for Models Modeling Language Reference


For example, the following model uses the AverageValue sub-
model to calculate the average temperature from a temperature
profile:
Model Pipe
// Discretize temperature profile into
NSections. NSections as integerParameter;
T([1:NSections]) as Temperature;
Q as heat_flux;
WallArea as Area;
U as notype;
T_Wall as Temperature;
// Use submodel to calculate average
T_Av as AverageValue(NValues is NSections,
Value is T);
// Calculate heat transfer based on average
temperature
Q = U * WallArea * (T_Wall - T_Av.Average);
End

Since ValueType has not been redefined, T_Av.Average is a


simple RealVariable. This means that it will appear on tables and
plots with no units of measurement. The ValueType can be
redefined by using the IS operation in the declaration of the sub-
model, for example:
Model Pipe
// Discretize temperature profile into
NSections.NSections as integerParameter;
T([1:NSections]) as Temperature;
Q as heat_flux;
WallArea as Area;
U as notype;
T_Wall as Temperature;
// Use submodel to calculate average
T_Av as AverageValue(NValues is NSections,
Value is T, ValueType IS Temperature);
// Calculate heat transfer based on average
temperature Q = U * WallArea * (T_Wall -
T_Av.Average);
End

Here ValueType has been redefined to be Temperature (which is


derived from RealVariable). Consequently, T_Av.Average is
created as a Temperature variable rather than as a simple
RealVariable, so it will show consistent units of measurement on
tables and plots.

Modeling Language Reference Modeling Language for Models • 4-45


Restrictions on Using Note the following restrictions when using virtual types:
Virtual Types • Virtual types are only visible in the scope in which they
are declared: they cannot be used directly within nested
model definitions. However, the right side of the IS operator
may be a virtual type. In this way, the redefinition of a
virtual type in a container model can be propagated down to
sub-models nested within sub-models.
• When you edit models interactively, if you add or remove
virtual properties, you must recompile models using the
edited model.
Recompiling the models ensures that any changes are
completely propagated through the system.
• Models that use external properties can only be used as sub-
models: they cannot be placed directly onto the flowsheet.

Using SWITCH
You can use the SWITCH keyword to define any number of
different modes of operation directly in the model definition.
A switch definition always applies to the model during simulation.
SWITCH operates with all run modes.
You can use SWITCH to change between different equations in a
model. You can define conditions that determine how the model
switches between different sets of equations.

Syntax for SWITCH

SwitchName: SWITCH
INITIAL STATE StateName
SwitchStatements;
IF Condition STATE : StateName;
ENDSTATE
.
.
ENDSWITCH

Switchname ............. Optional name you can give to the Switch


definition
SWITCH.................... Keyword that defines a switch
INITIAL ..................... The state that applies at the start of the simulation
run. Use the Initial keyword on only one state
definition.
Note One of the states you define in a SWITCH
definition must be flagged as the initial state.

4-46 • Modeling Language for Models Modeling Language Reference


STATE ...................... Keyword that defines a number of different states
in a Switch
StateName ............... Unique name of a state within the current Switch
definition
SwitchStatements ... Equations that apply to the state you are defining
IF condition STATE: If the condition is met, the equations in the named
Statename................ state definition are used instead of the current
state.

SWITCH Remarks
You can use SWITCH to change the way a model works depending
on the condition of a process variable during run-time. SWITCH
provides a quick and easy way for you to describe reversible and
non-reversible changes in your process.
You cannot change the structure of the simulation between states.
Each state definition in a switch must maintain a square and
complete simulation status. This means that you must have the
same number of equations in each state within a SWITCH
definition.

Modeling Language Reference Modeling Language for Models • 4-47


SWITCH Examples
The following example shows how to model a non-reversible
action using a switch definition. The switch is non-reversible
because there is a condition that enables the state Normal to switch
to Burst, but there is no condition to reverse this switch.
SWITCH
INITIAL STATE Normal
NMolDepletion = 0;
IF VesselPressure > 8.5 STATE: Burst;
ENDSTATE
STATE Burst
NMolDepletion = 0.01*(VesselPressure - 1.0)/8.0;
ENDSTATE
ENDSWITCH
The following example shows a switch statement used to model a
tank with two different cross-sectional areas. Between fluid height
0.0 and 1.0, the sectional area is 0.25; between the fluid level 1.0
and 11.0, the sectional area is 2.0. The switch models overflow in
this example, where the fluid level remains constant.
CalculateFluidLevel:
SWITCH
INITIAL STATE BottomZone
FluidLevel = FluidVolume / 0.25;
OverflowFlowrate = 0.0;
IF (FluidVolume >= 1.0) STATE : Topzone;
ENDSTATE
STATE TopZone
FluidLevel = (FluidVolume - 1) / 2 + 4;
OverflowFlowrate = 0.0;
IF FluidVolume >= 11.0 STATE :
Overflowing;
IF FluidVolume < 1.0 STATE : BottomZone;
ENDSTATE
STATE Overflowing
OverflowFlowrate = MAX(FluidInA.Flow +
FluidInB.Flow - FluidOut.Flow,0);
FluidLevel = 11.0;
IF FluidVolume < 11.0 STATE : TopZone;
ENDSTATE
ENDSWITCH

4-48 • Modeling Language for Models Modeling Language Reference


5 Modeling PDE Systems

Aspen Modeler products provide a systematic way to model and


solve distributed parameter systems in which process variables
vary with respect to spatial position as well as time.
With the custom PDE modeling feature, you can formulate linear
and nonlinear partial differential equations involving first-order
and/or second-order derivatives. Extensions to the modeling
language enable you to write compact and readable PDEs over one,
two, or three spatial dimensions, using rectangular or polar
coordinates. The built-in text editor, configuration forms, and
specification analysis also facilitate the efficient preparation of
your PDE models for solution.
This chapter describes:
• How PDE modeling is implemented
• Creating a custom PDE model
• Using domains with PDE modeling
• PDAE models
• Using Method of Lines for the solution of PDEs

Modeling Language Reference Modeling PDE Systems • 5-1


About PDE Modeling
Domains and distributions are provided as fundamental types to
make it easier to package the PDE discretization methods in sub-
models. A domain determines how to discretize a spatial
dimension based on your selection of the type and order of
discretization method, as well as element spacing. Element spacing
is uniform within a given domain section, but non-uniform spacing
can be applied using multiple sections, each with a different
spacing. The latter is particularly useful for modeling PDE systems
with sharp fronts. A distribution represents a variable distributed
over a single domain or up to three domains in the case of a three-
dimensional distribution. Using profile plotting, you can view the
distribution of your variables along the length of the discretized
domain.
The PDE modeling facility uses the well-known Method of Lines
(MOL) to solve the time-dependent PDE systems arising from
distributed parameter models. It is a two-phase solution method:
• In the first phase, the partial differential equations in your
models are discretized automatically using the finite
difference or finite element method you select.
• In the second phase, the resulting DAE systems are
integrated over time using the dynamic solver of your
choice.
The PDE feature can be applied to a wide range of distributed
parameter systems. These include packed bed tubular reactors,
packed bed adsorption and distillation columns, furnaces and heat
exchangers, and pipelines.

5-2 • Modeling PDE Systems Modeling Language Reference


Creating a Custom PDE Model
To create a new custom PDE model:
1. Create a model.
2. Declare one or more domains and specify the highest order
derivative in that domain. To customize a domain, you can
specify the following properties:
• Discretization method
• Domain length
• Number and location of domain section(s)
• Element spacing preferences
3. Declare a distribution for each distributed variable and
specify the highest order derivative of the variable in each
direction if it differs from the default set for the
corresponding domain.
4. Write your partial differential equations over the domain.
5. Write your boundary conditions.
6. For a dynamic simulation, write your initial conditions.

Example of Custom The following example shows a complete description of a two-


PDE Modeling dimensional heated slab:

Modeling Language Reference Modeling PDE Systems • 5-3


MODEL HEATEDSLAB
// Declare domains for X and Y spatial domains.
X as LengthDomain(DiscretizationMethod:"BFD1",
HighestOrderDerivative: 2,
Length:1, SpacingPreference:0.1);
Y as LengthDomain(DiscretizationMethod:"BFD1",
HighestOrderDerivative: 2, Length:1,
SpacingPreference:0.1);

// Declare a two-dimensional distribution for


distributed temperature variable.
T as Distribution2D(XDomain is X, YDomain is Y)
of Temperature(10);
D as constant (1.2, Fixed);
// Heat transfer equation: Time-dependent second
order partial differential
// equation. PDE is specified over the interior
of the domain.
$T(X.Interior, Y.Interior) = D * T(X.Interior,
Y.Interior).d2dx2
+ D * T(X.Interior, Y.Interior).d2dy2;

// Initial conditions (Initial conditions) -


steady state
T(X.Interior, Y.Interior): RateInitial;
// Dirichlet boundary conditions (Boundary
conditions)
// Specify temperature at domain boundaries.
T(0, [0:Y.EndNode]) : Fixed, 31;
T(X.EndNode, [0:Y.EndNode]) : Fixed, 15;
// Neumann Boundary conditions - No heat
transfer at sides
T([1:X.EndNode-1], 0).ddy = 0;
T([1:X.EndNode-1], Y.EndNode).ddy = 0;
// The two-dimensional heated slab is fully
described.
End

5-4 • Modeling PDE Systems Modeling Language Reference


Using Domains with PDE Modeling
Domains are used to define the space over which a PDE system
and its corresponding variables are distributed. A single domain
describes one dimension of the distribution (for example, the axis
of a tubular reactor). In the modeling language, a built-in type
definition called Domain represents this concept. Two other built-
in types, LengthDomain and AngleDomain, inherit properties from
Domain and are provided for your modeling convenience.
For example, a pipe model that contains equations that are
distributed along the axis may contain the following declaration:
Model Pipe
Axis as LengthDomain(Length:10,
SpacingPreference:1.0, NumSections:1,
DiscretizationMethod:"CFD4");
End
In this example, Axis is an instance of the LengthDomain model
with boundaries at 0.0 (the default) and 10.0. Describing the
boundaries of a domain is only a small part of the functionality of a
domain model. It also calculates how the space is discretized. The
discretization is based on your selection of element spacing,
number of domain sections, and type and order of discretization
method.
The following is an illustration of using domains.

Modeling Language Reference Modeling PDE Systems • 5-5


Notes
• You can change domain properties in the domain
declaration or by using the domain configuration form.
• The built-in Domain model is dimensionless. The units of
measurement for the LengthDomain and AngleDomain are
meters and radians, respectively. You must ensure that these
base units of measurement are consistent for all your model
equations. The user interface converts between the base
units of measurement and your current UOM so that plots
and tables are displayed in the chosen UOM. See Using
Units of Measurement in Chapter 2 for more information.
Declaring Domains When modeling a distributed parameter system, you start by
for PDE Modeling declaring one or more domains. For each domain, you can specify
the following properties:
• Discretization method
• Highest order derivative
• Domain length
• Element spacing preference
• Number of sections
• Section location and spacing
The capability to assign these properties separately for each
domain instance gives you modeling flexibility.
You can declare domains in a model using the following syntax.

Domain Syntax

Domain, Domain, … AS
DomainModel of RealParameterType(Property :
PropertyValue, ... );

Domain ....................Name you give to this domain.


DomainModel..........Name of a defined domain model. Three domain model types are built in to the system,
namely DOMAIN, LENGTHDOMAIN, and ANGLEDOMAIN. The Domain model is
dimensionless. The units of measurement for the LengthDomain and AngleDomain
models are meters and radians, respectively.
RealParameterType Name RealParameter type to use for domain values and length.
Property ..................Parameter or variable defined in the built-in domain model. The following are domain
parameters that can be used in the assignment list:
DiscretizationMethod Discretization method used to calculate partial derivatives.
The default is "BFD1". Valid values are "BFD1", "CFD4",
"OCFE2", "OCFE4", and "UBFD4".
HighestOrderDerivative Highest-order partial derivative (with respect to the
independent spatial variable) to calculate for a given
domain. Valid values are 0, 1 and 2. The default value is 1.

5-6 • Modeling PDE Systems Modeling Language Reference


No partial derivatives are calculated for a value of 0. For a
value of 1, only 1st-order partial derivatives are calculated.
A value of 2 means that both 1st-order and 2nd-order partial
derivatives are calculated.
Length Length of domain. The default is 1.0.
NumSections Number of sections in the domain. Default value is 1.
SpacingPreference Preferred spacing for the domain. The default value is
Length/NumSections/8. Note that the actual spacing used
(SpacingUsed) by Aspen Custom Model may differ from
your preferred spacing. This happens when your domain
length is not a multiple of your spacing preference. In this
case, ACM divides the domain length by your preferred
spacing. The result is rounded to the nearest integer to
determine the number of elements in the domain. The
domain length is divided by the calculated number of
elements to produce the actual spacing used. Your preferred
spacing must also provide the minimum number of elements
required for the discretization method (for example, four
elements for 4th-order methods). If it does not, the spacing
used is equal to the domain length divided by the minimum
number of elements. Because the value of the SpacingUsed
property is determined by the built-in domain model, you
must not modify it. For more information, see Element
Spacing Preference.
Section(*).Location Absolute location of the left-hand boundary of a section.
The locations of contiguous sections in a given domain must
be in increasing order. The location of the right-hand
domain boundary is equal to Section(1).Location plus
Length.
Section(*).Spacing Preferred spacing for the section. The default value is the
Preference value of the SpacingPreference property for the domain.
Element spacing is uniform in any given section. Different
spacing can be used in different sections. Note that the
actual spacing used, Section(*).SpacingUsed, may differ
from your preferred section spacing for the same reasons
discussed for the SpacingPreference property. Because the
value of the Section(*).SpacingUsed property is determined
by the built-in domain model, you must not modify it. For
more information, see Element Spacing Preference
PropertyValue Value to be assigned to the
property.

Modeling Language Reference Modeling PDE Systems • 5-7


Domain Remarks
• You can declare a comma-separated list of domains of the
same type in a single declaration statement.
• You may associate up to three domains with each distributed
variable in your process model. This association is made
with a distribution.
• Distributed variables can refer only to domains that you
have already declared explicitly in your model.
• You can change the configuration of a domain using the
domain configuration form. This form is particularly useful
if you want to use different discretization methods or
element spacing.

Domain Declaration Examples


All the following declarations appear within a model definition.
In the first example, a domain called X is created in the model. X
takes on the characteristics of the built-in definition of a domain
model:
X AS Domain;
In this example, the domain properties such as X.Value and
X.Length are simple RealParameters. To provide units of
measurement for a Domain the value type can be redefined using
the 'of' qualifier, for example:
X AS Domain of LengthParameter;
For brevity, LengthDomain is provided as a built-in DomainModel
that uses LengthParameter as its ValueType by default. The
following example declares Axis as a domain of type
LengthDomain, and requires 2nd-order partial derivatives:
Axis AS LengthDomain (HighestOrderDerivative:2);
In the next example, the domain Angle is of type AngleDomain,
which is a built-in domain model. The default discretization
method used is the 4th-order central finite difference method.
Angle AS
AngleDomain(DiscretizationMethod:"CFD4");
The following example shows three domains defined in one
statement. Each domain contains 2nd-order partial derivatives that
are discretized using 4th -order orthogonal collocation on finite
elements:

5-8 • Modeling PDE Systems Modeling Language Reference


X, Y, Z AS LengthDomain
(HighestOrderDerivative:2,
DiscretizationMethod:"OCFE4");
By using three separate domain declaration statements, a different
discretization method can be used for each domain:
X AS LengthDomain (HighestOrderDerivative:2,
DiscretizationMethod:"BFD1");
Y AS LengthDomain (HighestOrderDerivative:2,
DiscretizationMethod:"CFD4");
Z AS LengthDomain (HighestOrderDerivative:2,
DiscretizationMethod:"UBFD4");
In the next example, the domain Y of type LengthDomain is
discretized using the 4th-order upwind biased finite difference
method. The values of highest order derivative and domain length
are specified. The domain is divided into three sections having
lengths of 3.0, 1.0, and 6.0, respectively. Note here that by default
Section(1).Location is 0.0. A domain spacing preference of 0.2
applies to the first and third sections, whereas a finer element
spacing of 0.1 is preferred for the second section.
Y AS LengthDomain (DiscretizationMethod:"UBFD4",
HighestOrderDerivative:2, Length:10.0,
NumSections:3, SpacingPreference:0.2,
Section(2).Location:3.0, Section(3).Location:4.0,
Section(2).SpacingPreference:0.1)

Using Discretization Aspen Modeler products provide two well-known classes of


Methods for PDE discretization methods, namely finite difference over uniform grids
Modeling and orthogonal collocation on finite elements. As shown in the
following table, the methods differ in the order and type of
approximation used. For the built-in domain models, the default
method is 1st-order backward finite difference. You can specify
another discretization method when declaring your domain or by
going to the domain configuration form.

Method Order of Approximation Type of Approximation

BFD1(default) 1st-order Backward Finite Difference


CFD4 4th-order Central Finite Difference
UBFD4 4th-order Upwind Biased Finite
Difference
OCFE2 2nd-order Orthogonal Collocation on
Finite Elements
OCFE4 4th-order Orthogonal Collocation on
Finite Elements

Modeling Language Reference Modeling PDE Systems • 5-9


Discretization Method Remarks
• The order of approximation for partial derivatives in finite
difference methods and the degree of polynomials used in
finite element methods have a significant impact on the
accuracy of the solution. Generally, a higher order algorithm
of the same type implies higher accuracy. This is especially
true if you use a large element spacing (coarse grid).
• By writing your PDEs and initial conditions using the
Interior set provided in the built-in domain model, you can
switch between the various discretization methods without
having to modify your model. The underlying requirement
that finite difference and OCFE methods inherently require
derivatives and model equations to be evaluated at different
discretization points is handled automatically.
• You can use different discretization methods for each
domain in a 2D or 3D distribution.

Specifying a Discretization Method in the Domain


Configuration Form
Use the domain configuration form to choose a PDE discretization
method for your domain:
1. In the All Items pane of the Simulation Explorer, double-
click on the Flowsheet folder.
2. In the Contents pane, double-click Configure for the
domain block of interest. The domain configuration form
appears.
3. Click the cell corresponding to the
DomainName.DiscretizationMethod (row) and the Value
attribute (column).
4. Select the method you want from the menu.

Examples of Specifying a Discretization Method in the


Declaration of a Domain
When writing a PDE model, the discretization method can be
specified in the declaration of the domain.
In the first example, a domain called X is discretized using the 4th-
order central finite difference method.
X AS Domain(DiscretizationMethod:"CFD4");
The following example shows two domains declared in one
statement. Each domain contains 2nd-order partial derivatives that
are discretized using 2nd -order orthogonal collocation on finite
elements:

5-10 • Modeling PDE Systems Modeling Language Reference


Axial, Radial AS LengthDomain
(HighestOrderDerivative:2,
DiscretizationMethod:"OCFE2");
By using two separate domain declaration statements, a different
discretization method can be used for each domain:
Axial AS LengthDomain (HighestOrderDerivative:2,
DiscretizationMethod:"BFD1");
Radial AS LengthDomain (HighestOrderDerivative:2,
DiscretizationMethod:"CFD4");
Specifying Domain Distributed parameter systems are described as distributions over
Length one or more spatial domains of a given length.
Taking a tubular reactor as an example, the lengths of the axial and
radial domains are the reactor length and radius, respectively.
The built-in domain models contain a property called Length. The
default value for the domain length is 1.0. This value can be
changed in the declaration of your domain or by using the domain
configuration form.
Tip While the built-in Domain model is dimensionless, the units
of measurement for the LengthDomain and AngleDomain models
are meters and radians, respectively. When setting the Length
parameter for the built-in LengthDomain and AngleDomain
models, you must ensure that these base units of measurement are
consistent for all your model equations. The user interface converts
between the base units of measurement and your current UOM so
that plots and tables are displayed in the chosen UOM. See Using
Units of Measurement in Chapter 2 for more information.

Specifying Domain Length in the Domain Configuration Form


Use the domain configuration form to specify the length of your
domain. The default value is 1.0.
1. In the All Items pane of the Simulation Explorer, double-
click on the Flowsheet folder.
2. In the Contents pane, double-click Configure for the
domain block of interest. The domain configuration form
appears.
3. Click the cell corresponding to DomainName.Length (row)
and the Value attribute (column).
4. Enter the domain length you want.

Modeling Language Reference Modeling PDE Systems • 5-11


Examples of Specifying Domain Length in the Declaration of a
Domain
When writing a PDE model, the length of the discretized domain
can be specified in the declaration of the domain. If it is not
specified, the length defaults to the value of 1.0 assigned in the
built-in domain models.
In the first example, a domain X of length 25 is discretized using
the 4th-order central finite difference method.
X AS Domain(DiscretizationMethod:"CFD4", Length:
25.0);
The next example shows the specification of the domain lengths
for a two-dimensional reactor problem.
Axial AS LengthDomain (Length:10.4);
Radial AS LengthDomain (Length:2.1);
Specifying Element Given a fixed domain length, the spacing of the elements
Spacing Preference determines the granularity of the discretized grid and the number of
elements. A small spacing gives a fine grid with a large number of
elements, whereas a larger spacing means a coarse grid with a
small number of elements. The element spacing, along with the
domain length, number of sections, and section locations,
determine the number and location of discretization nodes.
Element spacing is uniform within a given domain section, but
non-uniform spacing can be applied using multiple sections, each
with a different spacing. The latter is particularly useful for
modeling PDE systems with sharp fronts.
The element spacing you use can have a large influence on the
trajectory of the solution. Generally, a smaller element spacing
implies higher accuracy at the expense of additional computation.
As you reduce the element spacing, the computational
requirements will increase. This happens because the number of
partial derivatives to be computed will in general be proportional
to the number of elements. On the other hand, if you specify too
large a value, the simulation may be far from accurate and even fail
to converge, especially for problems with steep gradients.

5-12 • Modeling PDE Systems Modeling Language Reference


Aspen Modeler products enable you to specify an element spacing
preference for your domain. The default value of the
SpacingPreference property is Length/NumSections/8, a spacing
that gives 8 points per section. A different value can be specified in
the declaration of your domain or by using the domain
configuration form. Different element spacings can be used in
different sections, but element spacing is uniform in any given
section.
Note that the actual spacing used (SpacingUsed) may differ from
your preferred spacing. This happens when your domain length is
not a multiple of your spacing preference. In this case, the domain
length is divided by your preferred spacing. The result is rounded
to the nearest integer to determine the number of elements. The
domain length is then divided by the calculated number of
elements to produce the actual spacing used. Your spacing
preference must also give enough elements to support the
discretization method you select. If it gives fewer, the actual
spacing used is set to give the minimum. For example, all of the
4th-order discretization methods require at least four elements. In
summary, the value of the SpacingUsed property depends not only
on the preferred spacing you specify, but also on domain length, as
well as the order and type of discretization method you select.
Because the value of the SpacingUsed property is determined by
the built-in domain model, you must not modify it. See the
examples in Specifying Element Spacing Preference on page 512.

Notes
• The default spacing preference for each section in a domain
is the spacing preference specified for the domain.
• The information on spacing preference vs. spacing used for
a domain also applies to element spacing for individual
sections.

Specifying Spacing Preference in the Domain Configuration


Form
Use the domain configuration form to specify the element spacing
preference. The default value is Length/NumSections/8.
1. In the All Items pane of the Simulation Explorer, double-
click on the Flowsheet folder.
2. In the Contents pane, double-click Configure for the
domain block of interest. The domain configuration form
appears.

Modeling Language Reference Modeling PDE Systems • 5-13


3. Click the cell corresponding to the
DomainName.SpacingPreference (row) and the Value
attribute (column).
4. Enter the element spacing you prefer to be used for this
domain.

Examples of Specifying Spacing Preference in the Declaration


of a Domain
When declaring a domain in your PDE model, you can specify a
preferred element spacing in the list of property assignments.
In the first example, the preferred element spacing
(SpacingPreference) for domain X is set to a value 0.2. Because the
length is a multiple of the preferred element spacing, the actual
spacing used (SpacingUsed) is also 0.2. The total number of
elements in this domain is equal to Length/SpacingUsed or 2.0/0.2
= 10.
X AS Domain(DiscretizationMethod:"BFD1",
Length:2.0, SpacingPreference:0.2);
If the length is not a multiple of the spacing preference you choose,
the SpacingUsed property is based on the nearest number of
elements. For example, if your domain length is 1.0 and you
specify a preferred spacing of .35 for BFD1, the actual
SpacingUsed property will be set to .3333 (1.0/3).
As another example, take the case where your domain length is 1.0
and you specify a spacing preference of 0.5 with a 4th-order
discretization method. The value of the SpacingUsed property in
this case is set to .25 (1.0/4), because at least four discretization
points are required for a 4th-order method.
Axial AS LengthDomain
(DiscretizationMethod:"CFD4", Length:1.0,
SpacingPreference:0.5);
Using Domain The solution path for some PDEs may exhibit steep gradients in
Sections one or more spatial domains. When the location of the sharp front
does not move much in time and is known a priori, you can divide
the domain into multiple sections to handle this problem. You can
use a small element spacing (that is, fine grid) for any section that
contains a steep gradient and a large spacing (that is, coarse grid)
elsewhere.
The built-in domain model contains the NumSections property for
specifying the number of sections. The default value is 1. You have
the flexibility to set the Location and preferred element spacing
(Section(*).SpacingPreference) for each section in your domain.

5-14 • Modeling PDE Systems Modeling Language Reference


The default location for the first section (that is,
Section(1).Location) is 0.0. By default, the remaining section
locations are set at equally spaced intervals. The default spacing
preference for each section is taken to be the spacing preference
specified for the domain.

Section Remarks
• You can change the number of domain sections and their
location and element spacing in the declaration of your
domain or by using the domain configuration form.
• The locations of contiguous sections in a given domain must
be in increasing order. A section location value must not
exceed Section(1).Location plus Length.
• Uniform element spacing is used in a given section. Element
spacing can vary between sections, therefore, non-uniform
spacing can be applied using multiple sections, each with a
different spacing. The latter is particularly useful for
modeling PDE systems with sharp fronts.

Specifying Section Parameters in the Domain Configuration


Form
Use the domain configuration form to specify the number of
sections and their location and element spacing.
1. In the All Items pane of the Simulation Explorer, double-
click the Flowsheet folder.
2. In the Contents pane, double-click Configure for the
domain block of interest. The domain configuration form
appears.
3. Click the cell corresponding to the Value attribute (column)
of the DomainName.NumSections (row).
4. Enter the number of sections you want.
5. For each of the domains, click the cells corresponding the
Value attribute (column) of the
DomainName.Section(*).Location (row) and enter the
location. The value you enter represents the absolute
location of the left-hand boundary of the section. The
locations of contiguous sections in a given domain must be
in increasing order and a section location value must not
exceed Section(1).Location plus Length.
6. For each of the domains, click the cells corresponding the
Value attribute (column) of the
DomainName.Section(*).SpacingPreference (row) and enter
the element spacing you prefer.

Modeling Language Reference Modeling PDE Systems • 5-15


Examples of Specifying Section Parameters in the Declaration
of a Domain
When declaring a domain with multiple sections, you can specify
the number of sections using the NumSections parameter in the
declaration of the domain.
The first example shows that domain X is divided into three
sections.
X AS Domain(NumSections:3);
You can set the location of one or more of the sections in the
domain using the parameters called Section(*).Location. In the
following example, the second and third sections are located at 0.3
and 0.5, respectively. The default location for Section(1) is 0.0.
X AS LengthDomain(NumSections:3,
Section(2).Location:0.3,
Section(3).Location:0.5);
Next, a different spacing preference is specified for each of the
three sections in the previous example. A much smaller spacing
between elements is used for the second section because this part
of the domain is known to contain a sharp front. Note here also that
the Section(*).Location values must not exceed 1.0 as the domain
Length is 1.0 by default.
X AS LengthDomain(NumSections:3,
Section(2).Location:0.3, Section(3).Location:0.5,
Section(1).SpacingPreference:0.2,
Section(2).SpacingPreference:0.01,
Section(3).SpacingPreference:0.2);
In the following example, two sections each having size 8.0 are
specified. The spacing preference for the first section is set at a
value of 0.2, whereas the spacing preference for the second section
is 1.0 by default (Length/NumSections/8).
X AS LengthDomain(DiscretizationMethod:"CFD4",
Length:16.0, NumSections:2, Section(1).Location:-
8.0, Section(2).Location:0.0,
Section(1).SpacingPreference:0.2)
Number and Location Based on the configuration parameters you select, the domain
of Discretization model distributes the discretization nodes. More specifically, it
Nodes determines the number of nodes (EndNode+1) and their location,
Value([0:EndNode]), where 0 and EndNode correspond to the
node indices for the left-hand and right-hand domain boundaries,
respectively. Given this convention for indexing over the discrete
domain, Value([0:EndNode]) specifies a closed domain and
Value([1:EndNode-1]) defines a domain open on both ends nodes.

5-16 • Modeling PDE Systems Modeling Language Reference


The Value array and EndNode are displayed in the Configuration
Form for each domain.

EndNode and Value Array Remarks


• The EndNode parameter and the Value array are calculated
by the domain and must not be modified.
• If you wish to produce a profile plot showing your
distribution, use the Value array in your domain as your X-
axis variable. For example, use XDomain.Value
([0:XDomain.EndNode]) or XDomain
([0:XDomain.EndNode]) for short.

Example of Use of EndNode and Value Array


The following example of Dirichlet boundary conditions
demonstrates the use of EndNode and the Value array:
// Boundary conditions specified using EndNode
T(0,[0:Y.EndNode] ) = 0.0;
T([1:X.EndNode-1],0) = 0.0;
T([1:X.EndNode-1],Y.EndNode) = 0.0;
// Use the Value array, Y([0:Y.EndNode]), to vary
the Boundary condition depending
// on location along the boundary
T(X.EndNode, [0:Y.EndNode]) =
sinh(PI)*sin(PI*Y([0:Y.EndNode]));

Distributions for Declaring Distributed Variables


Distributions are used to distribute a variable over a spatial
domain. A distribution can reference one or more domains
dependent on its dimensionality (1D, 2D, or 3D). In the modeling
language, three built-in type definitions represent this concept:
• Distribution1D
• Distribution2D
• Distribution3D
The distribution sub-models that you declare in your process model
represent distributed variables. They provide access to the values
of the distributed variable at each point of the discretized spatial
domain(s). To refer to the value of a particular distributed variable
at a specific location (for example, node i in a 1D domain), use
Distribution.value(i) or Distribution(i) for short. Using profile
plotting, you can view these distributed variable values as your Y-
axis variable along the length of the discretized domain. As your
X-axis variable, use the Value array in your domain (for example,
XDomain.Value([0:XDomain.EndNode]) or
XDomain([0:XDomain.EndNode]) for short).

Modeling Language Reference Modeling PDE Systems • 5-17


The built-in distribution models also contain the logic for
calculating partial derivatives. More specifically, they calculate the
derivatives of the distributed variables with respect to the
independent spatial variables. First and/or second derivatives are
calculated depending on the order of the PDE problem (as defined
by the highest-order derivatives in the PDEs). Only first derivatives
are considered for problems of order one. Both first and second
derivatives are considered for problems of order two. The exact
form of the derivative calculation is based on the discretization
method and order of approximation. For more information on
partial derivative calculation, see Discretization Methods: Finite
Difference on page 5-37 and Discretization Methods: Finite
Element Methods on page 5-40.
Declaring When modeling distributed parameter systems, you declare one or
Distributions for more distributed domains and associate each distributed variable in
Distributed Variables your model with up to three of these domains. The distributed
variable is declared using a distribution. A distribution can refer
only to domains that you have declared previously in your model.
Within a given process model, all variables do not necessarily have
to be distributed over the same domain(s). For example, some
variables may be distributed over both radial and axial domains,
while others may be distributed over the axial domain only.
You can use an array to define a collection of distributions. For
example, you can define a concentration array indexed by
component names and distributed over a domain. For an example,
see Using an Array of Distributions on page 5-22.
In the declaration of your distribution, you can use the IS operator
to change the default domain sub-model names (that is, XDomain,
YDomain, ZDomain) to the domain names of your choice.
You can also specify the highest order derivative of the distributed
variable in each direction if it differs from the default set for the
corresponding domain. To do this, assign a value to the
HighestOrder*Derivative (where * is X, Y, or Z) property in the
declaration of your distribution.
In addition, you can define a distribution as hidden so that the
model user does not see the properties for the distributed variable.
You can declare distributions in a process model using the
following syntax.

Syntax for Declaring a Distribution

Distribution (Set , Set, ...) Distribution (Set…), ... AS


DistributionModel (DomainSubModel IS Domain, ... ,

5-18 • Modeling PDE Systems Modeling Language Reference


Distribution ............ Name you give to the distribution that you declare in your process model.
You can instance a list of distributions using the same distribution model in
one statement. Each distribution has all the properties defined in its
distribution model. The value of each property will be the value assigned to
the property in the distribution model type (that is, 1D, 2D, or 3D). You can
modify the values of these properties.
Set ........................... Optional set definition. Either a set name or a definition between square
brackets [ and ]. Use a Set to define an array of distribution variables. To
define multi-dimensional arrays, define a list of sets.
DistributionModel.. Name of a built-in distribution model. Valid built-in model names are
DISTRIBUTION1D, DISTRIBUTION2D, and DISTRIBUTION3D.
DomainSubModel.. Name of a built-in domain sub-model declared in a built-in distribution
model. The valid domain sub-model names are dependent on the distribution
model. For DISTRIBUTION1D, the only valid DomainSubModel value is
XDOMAIN. For DISTRIBUTION2D, the valid values are XDOMAIN and
YDOMAIN. For DISTRIBUTION3D, the valid values are XDOMAIN,
YDOMAIN, and ZDOMAIN.
Domain ................... Name you give to the domain in your process model. You can then refer to
properties (variables and parameters) in the corresponding built-in domain
and distribution model using the following syntax: Domain.PropertyName
Property.................. Parameter or variable defined in the built-in distribution model.
You can assign a value to HighestOrder*Derivative (where * is X, Y, or Z )
for a specific domain in the distribution. Valid values for these parameters are
0, 1 and 2. The default value is 1. No partial derivatives are calculated for a
value of 0. Use a value of 0 to declare a variable that is distributed but that
does not require partial derivatives. For a value of 1, only 1st-order partial
derivatives are calculated. A value of 2 means that both 1st-order and 2nd-
order partial derivatives are calculated.
HighestOrderXDerivative Highest order partial derivative with respect
to the independent spatial variable in the
XDOMAIN. This parameter can be
assigned for all three built in distribution
models: DISTRIBUTION1D,
DISTRIBUTION2D, and
DISTRIBUTION3D.
HighestOrderYDerivative Highest order partial derivative with respect
to the independent spatial variable in the
YDOMAIN. This parameter can be
assigned for DISTRIBUTION2D and
DISTRIBUTION3D.
HighestOrderZDerivative Highest order partial derivative with respect
to the independent spatial variable in the
ZDOMAIN. This parameter can be
assigned for DISTRIBUTION3D only.
VariableType.............. Name of a defined variable type.

Modeling Language Reference Modeling PDE Systems • 5-19


Examples of Declaring Distributions
All the following declarations appear within a process model
definition.
In the first example, a temperature variable, T1, is distributed on a
two-dimensional domain and takes on the characteristics of the
built-in DISTRIBUTION2D model. In this example, the default
value and the lower bound on the variable are altered:
T1 AS Distribution2D of Temperature (Value:373.0;
Lower:273.0);
Two distributed temperature variables can be declared in one
statement:
T1, T2 AS Distribution2D of Temperature
(Value:373.0; Lower:273.0);
The next example shows how to define an array of distributed
temperature variables. The variable T is indexed explicitly as
having integer elements from 1 to 2:
T([1:2]) AS Distribution2D of Temperature
(Value:373.0; Lower:273.0);
Use the IS operator to change the default domain names, XDomain
and YDomain, to the more meaningful local names, Axial and
Radial:
T([1:2]) AS Distribution2D(XDomain IS Axial,
YDomain IS Radial) of Temperature (Value:373.0;
Lower:273.0);
Continuing with the preceding example, the Axial and Radial
domains can provide second-order derivatives by assigning a value
of 2 to HighestOrderXDerivative and HighestOrderYDerivative,
respectively. These parameter values override the default value of 1
assigned in the built-in domain model. They also override any
value assigned to HighestOrderDerivative in the declaration of the
Axial and Radial domains:
T([1:2]) AS Distribution2D(XDomain IS Axial,
YDomain IS Radial, HighestOrderXDerivative:2,
HighestOrderYDerivative:2) of Temperature
(Value:373.0; Lower:273.0);
In the next example, the concentration variable, Conc, is declared
as a distribution over three domains:

5-20 • Modeling PDE Systems Modeling Language Reference


Conc AS Distribution3D of Conc_Mole;
The following example shows how to declare an array of
concentration variables distributed over three domains. The
variable Conc is indexed to the set called Components, which
contains three string elements:
Components AS StringSet(["N2", "O2", "CO2"]);
Conc(Components) AS Distribution3D of Conc_Mole;
Declaring Distributed The recommended way to declare a variable that is distributed but
Variables that do not does not require partial derivatives is as follows:
Require Partial
Derivatives Model Pipe
XDomain as Domain (HighestOrderDerivative: 2);
T as Distribution1D of Temperature;
TWall as Distribution1D of Temperature
(HighestOrderXDerivative: 0);
End

In the above example, the domain declaration sets the default order
for all distributed variables to 2. This means that both ddx and
d2dx2 are calculated for the distributed variable T. However, for
TWall the default is overridden and set to zero. In this case the ddx
and d2dx2 arrays are empty and no partial derivatives are
calculated.
Alternatively you can simply index TWall over the same range as
the domain:
Model Pipe
XDomain as Domain(HighestOrderDerivative: 2);
T as Distribution1D of Temperature;
TWall([0:XDomain.EndNode]) as Temperature;
End
Referring to Domains Distributed variables can refer only to domains that you have
in Distributed declared previously in your model. For instance this sequence of
Variable Declarations declarations is legal:
Model Pipe
// Declare distributed domain
Axis as Domain of LengthParameter;
// Declare array of concentration variables
distributed over a 1D domain
Conc(ComponentList) as Distribution1D(XDomain
is
Axis) of Conc_Mole (Value: 0.0);
End
whereas the following declarations are illegal because the Axis
domain is used before it is declared:

Modeling Language Reference Modeling PDE Systems • 5-21


Model Pipe
// Declare array of concentration variables
distributed over a 1D domain
Conc(ComponentList) as Distribution1D(XDomain
is
Axis) of Conc_Mole (Value: 0.0);
// Declare distributed domain
Axis as Domain of LengthParameter;
End
Using an Array of Use an array of distributions to model a property (for example,
Distributions concentration) of various components distributed over a domain:
Model Pipe
// Declare distributed domain
Axis as Domain of LengthParameter;
// Declare array of concentration variables
distributed over a 1D domain
Conc(ComponentList) as Distribution1D(XDomain
is
Axis) of Conc_Mole (Value: 0.0);
FeedConc(ComponentList) as Conc_Mole;
V as Velocity;
// PDE written over nodes 1 to EndNode
$Conc(ComponentList)
(Axis.Interior+Axis.EndNode)
= -V * Conc(ComponentList)
(Axis.Interior+Axis.EndNode).ddx;
// Dirichlet boundary condition at left-hand
domain boundary
Conc(ComponentList)(0) =
FeedConc(ComponentList);
End

Notes
• The declaration of the distributed array called Conc
illustrates the convention for separating declaration
qualifiers (for example, XDomain is Axis), which appear
before the value type (for example, Concentration), and
assignments (for example, Value:0.0), which are put after
the value type.
• To refer to the concentration of a particular component (for
example, "A") at a specific location (for example, node iX),
use Conc("A").value(iX) or Conc("A")(iX) for short.
Referencing Domains You can declare a domain and/or distribution in a model and then
and Distributions in use this in a submodel of that model. To do this you should declare
Sub-Models the domain and/or distribution as External in the sub-model, and
pass the name of the domain and/or distribution to be used when
you instance the sub-model. For example to use the Domain X and
distribution T in a sub-model called Conductivity, the main model

5-22 • Modeling PDE Systems Modeling Language Reference


would contain:
X as LengthDomain (Length:1,
SpacingPreference:0.1);
T as Distribution1D (XDomain is X) of
Temperature;
cond as conductivity (XDomain is X, YDomain is
Y);
And the sub-model would define XDomain and T as external as
follows:
Model Conductivity
XDomain as external Domain;
T as external Distribution1D;
XDomain and T can then be used in the Conductivity model as
normal.

About PDAE Models


The equation-based simulation environment enables you to
perform dynamic simulations involving both lumped and
distributed parameter processes. Distributed systems have
properties that vary with one or more spatial dimensions as well as
time. Both space and time are independent variables. These
systems are described in terms of partial differential and algebraic
equations (PDAE systems) expressed over a domain. In addition,
these PDAE systems usually involve both boundary conditions and
initial conditions.
The general form of the PDAE system over the bounded domain is:
f (t , x, φ, φt , φx , φxx ) = 0
with boundary conditions of the following form:
g (t , x, φ,φt ,φx ) = 0
Where:
t = Time, an independent variable
x = Vector of at most three independent spatial variables
φ = Vector of dependent variables of the form f(t,x)
φt = Time derivatives
φx = First-order spatial derivatives
φxx = Second-order spatial derivatives

Modeling Language Reference Modeling PDE Systems • 5-23


The partial derivatives with respect to the spatial variables are
often written as follows:
∂φ ( x , t ) ∂ 2φ ( x , t )
φx = , φ xx =
∂x ∂x 2
The well-known Method of Lines (MOL) is used to solve the time-
dependent PDE systems. It is a two-stage process that discretizes in
space and leaves the time domain continuous, thereby converting
the PDAE system to a DAE system with respect to time.
Partial Differential Partial differential equations contain one or more partial
Equations (PDEs) derivatives and involve at least two independent variables.
For distributed parameter modeling of physical and chemical
processes, the most prevalent and useful PDEs are those with first-
and/or second-order partial derivatives. Usually, at most four
independent variables are involved, the three spatial coordinates
and time.
A first-order, time-dependent PDE can be put in the form:
f = aφ + bφ t + c φ x
Where:
t = Time, an independent variable
x = Vector of at most three independent spatial
variables
φ = Vector of dependent variables of the form f(t,x)
φt = Time derivatives
φx = First-order spatial derivatives
In general, the coefficients can be functions of all the variables and
their derivatives, for example:
a = a (t , x , φ , φ t , φ x )
The following is an example of a widely-used, linear second-order
PDE:
f = aφ + bφ t + cφ x + dφ xx
Where a, b, c, and d are a function of (t,x).
To represent a distributed parameter problem fully, the model also
requires auxiliary conditions. These are of two kinds, boundary
conditions and initial conditions. The latter is used when time is
one of the independent variables.

5-24 • Modeling PDE Systems Modeling Language Reference


Writing PDEs in The following features enable you to write PDE models that are
Models concise, correctly specified, and flexible from the standpoint of
solution with different discretization methods:
• Use the Interior set for writing (that is, indexing) your
PDE model equations and initial conditions. The Interior
set is defined automatically in the built-in domain model and
contains the grid points (nodes) required for your problem.
The contents of the set are based on the following domain
properties: order of your PDEs (HighestOrderDerivative),
the discretization method you select (that is, finite difference
vs. OCFE), and the number of sections and elements in your
domain.
The following table shows that for 1st-order PDE problems
the Interior set is always contiguous and contains all
interior nodes, 1 to EndNode-1. For 2nd-order PDE
problems however, the Interior set is contiguous only when
using finite difference methods with a single section and
OCFE methods with a single element. For all other 2nd-
order PDE problems, the Interior set is not contiguous. In
these cases, the model equation and 2nd-order derivative
equation at the node(s) excluded from the set are replaced
by a first-derivative continuity equation. For example, the
Interior set does not include the section boundaries when
using the finite difference methods for domains specified as
having more than one section. For the OCFE methods, all
element boundaries are excluded from the Interior set for
2nd-order PDE problems.

It is important to emphasize again that this Interior set is


automatically defined to help you write your PDE model
equations and initial conditions. Failing to do so can lead to
specification problems (that is, non-square systems) for
second-order PDE problems, especially when using finite
difference methods with multiple sections or OCFE
methods with multiple elements.
• Using the Interior set allows you to switch between finite
difference and finite element methods without having to
modify your PDEs. The underlying requirement that finite
difference and OCFE methods inherently require derivatives
and model equations to be evaluated at different
discretization points is automatically handled.

Modeling Language Reference Modeling PDE Systems • 5-25


Discretization Highest Order Number of Number of Interior Set
Methods Derivative Sections Elements per
Section

BFD1, CFD4, 1 --- --- [1:EndNode-1]


UBFD4
2 =1 --- [1:EndNode-1]
2 >1 --- [1:EndNode-1] –
[Section
Boundaries]
OCFE2, OCFE4 1 --- --- [1:EndNode-1]
2 --- =1 [1:EndNode-1]
2 --- >1 [1:EndNode-1] –
[Element
Boundaries]
• You should always index your boundary conditions using an
explicit list of contiguous nodes as shown here:
T([1:X.EndNode-1], 0) = 0.0;
T(0, [0:Y.EndNode] ) = 0.0;
Do not use the Interior set for writing boundary conditions
because, as previously explained, it may not always contain
a contiguous set of nodes from 1 to EndNode-1. Because 2D
and 3D problems typically require boundary conditions
over all nodes along the boundary, the excluded nodes in
the Interior set would lead to an underspecified problem.
• Access to first-order and second-order partial derivatives is
via the dd* and d2d*2 arrays where * is x, y, and/or z
depending on the dimensionality of the distributed variable.
Tip The range of each domain of every distributed variable in an
equation must be the same as in the following heat equation:
// Heat transfer equation: Time-dependent second
order partial differential
// equation. PDE is specified over the interior
of the domain.
$T(X.Interior, Y.Interior) = D *
T(X.Interior, Y.Interior).d2dx2 + D *
T(X.Interior, Y.Interior).d2dy2;
The following example is not legal because the range of the X
domain for the $T variable is not consistent with the range of X
domain for the distributed variables on the right-hand side of the
equation:

5-26 • Modeling PDE Systems Modeling Language Reference


// Heat transfer equation: Time-dependent second
order partial differential
// equation. PDE is specified over the interior
of the domain.
$T([0]+X.Interior, Y.Interior) = D *
T(X.Interior, Y.Interior).d2dx2 + D *
T(X.Interior, Y.Interior).d2dy2;

Examples of Writing PDEs in Models


The first example shows the advection equation for flow in a tube
where T is temperature and V is velocity. The PDE is 1st-order in
time (t) and space (x). It is written over a domain that is open at the
left-hand boundary. This is handled by using the Interior set and
adding EndNode.

Advection Equation
∂T ∂T
= −V
∂t ∂x
// Modeling Language
$Temp = -V *
Temp(Axis.Interior+Axis.EndNode).ddx;
For example, Fourier’s second law for heat conduction in one-
dimensional Cartesian coordinates:

Fourier’s Second Law

can be written in the modeling language as:


$T(X.Interior) = k/(rho*cp) *
T(X.Interior).d2dx2;
Next, consider three well-known elliptic PDEs (zero-order in time)
written over the interior of a domain defined in two-dimensional
Cartesian coordinates:

Modeling Language Reference Modeling PDE Systems • 5-27


LaPlace’s Equation
∂2u ∂2 u
+ =0
∂x 2 ∂y 2

// Modeling Language
u(X.Interior,Y.Interior).d2dx2 +
u(X.Interior,Y.Interior).d2dy2 = 0.0;

Poisson’s Equation
∂2u ∂2 u
+ 2 = sinh( π 2 + 1 x ) sin(πy )
∂x 2
∂y

// Modeling Language
for ix in x.interior do
for iy in y.interior do
u(iX, iY).d2dx2 + u(iX, iY).d2dy2 =
sinh(sqrt(sqr(PI)+1.0)*X(iX)) * sin(PI*Y(iY));
endfor
endfor

Helmholtz’s Equation
∂2u ∂2u
+ =u
∂x 2 ∂y 2
// Modeling Language
u(X.Interior,Y.Interior).d2dx2 +
u(X.Interior,Y.Interior).d2dy2 = u(X.Interior,
Y.Interior);

Specifying Partial Derivatives


Specify partial derivatives in your models using the dd* array for
first derivatives and the d2d*2 array for second derivatives, where
* can be x, y, or z depending on the dimensionality of your
distribution.

Distribution Model 1st-Order Partial 2nd-Order Partial


Derivatives Derivatives

Distribution1D ddx d2dx2


Distribution2D ddx, ddy d2dx2, d2dy2
Distribution3D ddx, ddy, ddz d2dx2, d2dy2, d2dz2

5-28 • Modeling PDE Systems Modeling Language Reference


For one-dimensional distributions, access to first-order partial
derivatives is via the ddx array defined in the built-in distribution
models. First derivatives can appear in PDE model equations such
as this advection equation:
$Temp(Axis.Interior+Axis.EndNode) = -V *
Temp(Axis.Interior+Axis.EndNode).ddx;
and in Neumann boundary conditions for 2nd-order PDE problems:
T(X.EndNode).ddx = 25.0;
The next example shows a LaPlace equation with second-order
partial derivatives:
T(X.Interior,Y.Interior).d2dx2 +
T(X.Interior,Y.Interior).d2dy2 = 0.0;

Partial Derivative Type


The PartialDerivative type is a built-in variable type for use in
custom PDE modeling. It has a reduced set of attributes (that is,
value, description, and units) compared to a normal RealVariable.
This saves memory if you are dealing with distributed parameter
systems with a large number of partial derivatives.

Using PDE with a Conservative Term


As an example, consider the following heat balance equation for a
two-dimensional pipe model:
∂ ∂T ∂ 2T Kr ∂ æ r∂T ö
A = −B + Kz + ç ÷
∂t ∂x ∂x 2 r ∂r è ∂r ø
To model the conservative term:
∂ æ r∂T ö
ç ÷
∂r è ∂r ø
it is necessary to introduce an intermediate distributed variable (for
example, rdTdr) which is distributed over the axis and radius and
equivalent to the inner radial flux expression:
æ r∂ T ö
ç ÷
è ∂r ø
The conservative term is then the derivative of rdTdr with respect
to the radius, that is rdTdr.ddy. Because only the ddy derivative is
required for this term, HighestOrderXDerivative is set to 0 and
HighestOrderYDerivative to 1.

Modeling Language Reference Modeling PDE Systems • 5-29


Using Boundary and The solution of PDEs must satisfy certain auxiliary conditions
Initial Conditions for (initial and boundary) on the boundary of the specified domain.
PDE Modeling These auxiliary conditions of a PDE system determine its unique
solution from among an infinite number of solutions. They serve as
the starting point for calculating the interior solution. The boundary
conditions are a fundamental part of the description of the process
system behavior, while the initial conditions define the initial state
of the process system and may often differ from one simulation to
the next.
In general, derivatives with respect to the spatial independent
variables must be at least one order lower than the highest-order
derivative in the PDE. Thus, for a 2nd-order PDE in x, the
auxiliary conditions can be no higher than 1st-order:
g (t , x, φ, φt , φx ) = 0
where:
t = Time, an independent variable
x = Vector of at most three independent spatial
variables
φ = Vector of dependent variables of the form f(t,x)
φt = Time derivatives
φx = First-order spatial derivatives
The auxiliary conditions associated with 2nd-order PDEs typically
involve values of the dependent variable and/or its first derivatives
at particular locations and time. In these cases, the preceding
general form becomes:
f = aφ + bφ x
where a, b, and f are a function of (t,x). The derivative is normal to
the domain boundary.
In the mathematical literature, three of the most commonly
recognized conditions are:
• Dirichlet
• Neumann
• Cauchy
The boundary conditions arising in your applications may be
significantly more complicated than the Dirichlet, Neumann, and
Cauchy classifications discussed here.

5-30 • Modeling PDE Systems Modeling Language Reference


Important
• When writing initial conditions, use the Interior set so
that your initial specifications are only applied to the Interior
points. This avoids over-specification for second-order PDE
problems with time derivatives. This is particularly
important when using OCFE discretization methods or finite
difference methods with multiple domain sections.
• When writing boundary conditions, do not use the
Interior set as you typically want them to apply to
contiguous locations along the boundary. Remember here
that for second-order PDE problems solved using OCFE
discretization methods or finite difference methods with
multiple domain sections, the Interior set does not contain
the contiguous set of nodes from 1 to EndNode-1. When
using OCFE methods, the nodes corresponding to
element/section boundaries are excluded from the Interior
set. When using finite difference methods with multiple
sections, the element boundaries are not included. In view of
this, you should always index boundary conditions
explicitly using integer elements.
• When writing boundary conditions, do not use second
partial derivatives unless you explicitly write the
derivatives' equations and include them in your model.
The built-in domain models do not include second
derivatives at the domain boundaries. For more information,
see Boundary Conditions Containing Second-Order
Derivatives.
Dirichlet conditions (b=0 in the preceding equation) specify the
values of the dependent variables at the boundary points as a
function of time. These Dirichlet points represent the exact
solutions at the boundary points.
Neumann conditions (a=0 in the preceding equation) specify the
values of the first-order spatial derivatives on the boundary. This
corresponds to specifying the flux across the boundary. If f=0, we
have a homogeneous Neumann boundary condition, which leads to
property conservation within the domain.

Cauchy or mixed boundary conditions comprise property flux and


property value at the boundary ( a, b ≠ 0 in the preceding
equation). This is often used to specify property transport over the
boundary (for example, interface kinetic, oxidizing surface
conditions).

Modeling Language Reference Modeling PDE Systems • 5-31


Example of Initial and Boundary Conditions
The following model gives examples of Dirichlet and Neumann
boundary conditions, as well as initial conditions:
Model HeatEquation
// Heat conduction example
// Domain declaration.
X as
LengthDomain(DiscretizationMethod:"OCFE4",
HighestOrderDerivative: 2);
// Declaration of distributed temperature
variable
using a Distribution1D model.
T as
Distribution1D(XDomain is X) of
Temperature;
// Declaration of thermal diffusivity for the
solid K as
RealParameter(1/32);
// PDE - open on both ends of the domain as
boundary conditions specified at // 0 and
EndNode.
$T(X.Interior) = k*T(X.Interior).d2dx2;
// Initial conditions
T([1: X.EndNode-1]): 10.0;
// Initial specification must only be applied
to
'Interior' points to avoid
// over-specification when using OCFE methods
or
finite difference methods
// with multiple sections.
T(X.Interior): initial;
// Dirichlet boundary condition. Applied at
left-
hand domain boundary.
T(0) = 0.0;
// Neumann boundary condition. Applied at
right-
hand domain boundary.
T(X.EndNode).ddx = 25.0;
End

5-32 • Modeling PDE Systems Modeling Language Reference


Boundary Conditions The built-in domain models explicitly exclude second-order partial
Containing Second- derivatives at the domain boundaries. The main reasons for this
Order Derivatives are:
• The majority of process models do not involve boundary
conditions containing second-order derivatives.
• The OCFE discretization methods do not require second-
order derivative calculations at element boundaries
including the domain boundaries. Excluding the
unnecessary second derivatives at the boundaries saves on
wasted operations and memory and also allows Aspen
Custom Modeler to provide more useful analysis for
specification errors.
Important If your model requires second derivatives at the
domain boundaries, you must explicitly write equations for the
second derivatives and include them in your model. For example,
you can write standard second-order forward and backward finite
difference equations for the left-hand boundary and right-hand
boundary, respectively.
This example shows a second-order forward finite difference
equation that can be used as a boundary condition for the left-hand
domain boundary. The second-partial derivative of a temperature
variable, T, is set to zero.
(T(0)–2*T(1)+T(2)) / (X.value(1)-X.value(0))^2 =
0.0;

The next example shows a 2nd-order backward finite difference


equation that can be used as a boundary condition for the right-
hand domain boundary. The second-partial derivative of a
temperature variable, T, is set to zero.
(T(X.EndNode-2)-2*T (X.EndNode-1)+T (X.EndNode))
/ (X.value(X.EndNode)-X.value(X.EndNode-1))^2 =
0.0;

If your boundary conditions contain second derivatives and you do


not include the derivative equations in your model, Aspen Custom
Modeler™ gives an error indicating that your model has equations
that use variables that do not exist. The error message is displayed
in the Simulation Messages window when checking the syntax of
your model.

Modeling Language Reference Modeling PDE Systems • 5-33


For example, consider the following HeatEquation model with a
boundary condition involving a second-order partial derivative:
Model HeatEquation
// Heat conduction example
// Domain declaration.
X as
LengthDomain(DiscretizationMethod:"OCFE4",
HighestOrderDerivative: 2);
// Declaration of distributed temperature
variable
using a Distribution1D model.
T as
Distribution1D(XDomain is X) of
Temperature;
// Declaration of thermal diffusivity for the
solid K as
RealParameter(1/32);
// PDE - open on both ends of the domain since
boundary conditions specified at
// 0 and EndNode.
$T(X.Interior) = k*T(X.Interior).d2dx2;
// Initial conditions
T([1: X.EndNode-1]): 10.0;
// Initial specification must only be applied
to
'Interior' points to avoid
// over-specification when using OCFE methods
or
finite difference methods
// with multiple sections.
T(X.Interior): initial;
// Dirichlet boundary condition. Applied at
left-
hand domain boundary.
T(0) = 0.0;
// Boundary condition containing second partial
derivative.
// Applied at right-hand domain boundary.
T(X.EndNode).d2dx2 = 0.0;
End

The following syntax error message is displayed in the Simulation


Messages window when Aspen Custom Modeler compiles the
PDE model shown above:

5-34 • Modeling PDE Systems Modeling Language Reference


Model HeatEquation has equations that use
variables which do not exist:
HeatEquation.T.d2dx2(8) - Failed path is (8)

To avoid this error, you can replace the boundary condition


involving d2dx2 with a polynomial approximation as discussed
above.

Open Domains for The proper declaration of models of distributed parameter systems
PDE Modeling requires the accurate specification of the domain of applicability of
each equation and boundary condition. You can easily distinguish
between the interior of the domain and the different parts of the
boundaries. The built-in domain model provides an integer set
called Interior that can be used to facilitate the efficient writing of
partial differential equations in your model.
An open domain is a domain without its boundaries. You can
define an open domain in your model equations using the Interior
set declared in the domain model. As its name implies, the Interior
set does not include the left-hand domain boundary [0] and right-
hand [EndNode] domain boundary.
Closed Domains for A closed domain is a domain with its boundaries included. The
PDE Modeling left-hand and right-hand domain boundaries are represented by
nodes 0 and EndNode, respectively. You will often need to define a
closed domain when writing your boundary conditions:
// Boundary condition for Heat transfer to solid
$TS([0:X.EndNode]) = SCon * (TG([0:X.EndNode]) -
TS([0:X.EndNode]));
Important Do not use the Interior set for writing boundary
conditions, especially when using OCFE discretization methods
and finite difference methods with multiple domain sections. You
should always index boundary conditions explicitly using integer
elements.
Using Domain Slices The boundary condition equations in a model may involve just a
for PDE Modeling sub-domain of an entire domain distribution. To define such sub-
domains, you can make use of the built-in support for set
operations. For example, in the case of the variable Temp which is
distributed over both axial and radial domains:

Modeling Language Reference Modeling PDE Systems • 5-35


Axial AS LengthDomain
(DiscretizationMethod:"CFD4", Length: 10.0);
Radial AS LengthDomain
(DiscretizationMethod:"CFD4", Length: 2.0);
Temp AS Distribution2D (XDomain is Axial, YDomain
is Radial) of Temperature;
The notation Temp([0:Axial.EndNode], 0) refers to the
temperature along the axis of the reactor.

Using Method of Lines for the


Solution of PDEs
The Method of Lines (MOL) solves time-dependent PDE systems
by discretizing in space, but leaving the time variable continuous
(rather than time evaluated at discrete nodes). If you think of the
solution as a surface over the space-time plane, the MOL computes
cross-sections of the surface along series of lines, each parallel to
the time axis and corresponding to one of the discrete spatial
nodes.
The MOL solution process has two phases. In the first, the partial
derivatives with respect to the independent spatial variables are
replaced with algebraic approximations (finite difference or finite
element) evaluated at discrete points. In the second phase, a series
of DAE systems are solved using a dynamic integrator (See the
Integrator tab of the Solver Properties dialog box for a list of
integrators available). The accuracy of the approximate solution
depends on the element spacing and the integration step size in
time.
Phase1 Phase 2
Discretization of Integration
Spatial Domains Over Time

PDAEs DAEs Solution

Two Key Steps in MOL Approach


1. Replace continuous domain(s) of equations by a discrete
grid of points (nodes) and replace derivatives in PDEs by
finite difference or finite element approximations
2. Obtain numerical solution at each time step that is a table
of approximate values at selected nodes in spatial
domain(s).

5-36 • Modeling PDE Systems Modeling Language Reference


Finite Difference In the finite difference method, the continuous problem domain is
Methods: General discretized in terms of the values of the dependent variables at
discrete points only. First-order and second-order partial
derivatives are approximated by finite difference formulas derived
using Taylor series expansions. The general forms of these
derivative equations are:
∂φ æ 1 ö [ n ]]
= ç ÷A φ
∂ x è ah ø
∂ 2φ æ 1 ö [ n ]]
= ç ÷B φ
∂ x 2 è bh ø
Where:
∂φ
= Derivative vector
∂x
φ = Dependent variable vector
x = Independent spatial variable
h = element spacing
1/a,1/b = multiplying constant
A, B = (n+1)x(n+1) differentiation matrix. The elements of the
matrix are the weighting coefficients of nth-order approximations
at the n+1Taylor series points.
n = order of approximation
Finite difference methods differ in terms of type (for example,
forward, backward, central, upwind-biased) and order of
approximation.

Discretization Methods: Finite Difference


You can choose between several finite difference options for use as
a domain discretization method. The default method is BFD1.
When writing your PDE model, you can specify a different
DiscretizationMethod property when declaring a domain. You can
also select another method using the Domain Configuration Form.

Method Order of Approximation Type of FD Approximation

BFD1 1st-order Backward


CFD4 4th-order Central
UBFD4 4th-order Upwind-Biased

Modeling Language Reference Modeling PDE Systems • 5-37


Remarks
The finite difference methods are based on the assumption of
uniform grids.

1st-Order Backward Finite Difference (BFD1)


The BFD1 discretization method uses the 1st-order BFD method
for 1st-partial derivatives and the 2nd-order CFD method for 2nd-
partial derivatives, except at the section and domain boundaries as
shown in the following table. The minimum number of elements
required for BFD1for 1st-order and 2nd-order problems is 1 and 2,
respectively.

First Partial Derivatives (HighestOrderDerivative=1 or 2)


• 1st-order forward finite difference (FFD1) for first
derivative at left-hand domain boundary (LHB).
• 1st-order backward finite difference (BFD1) for all interior
nodes and right-hand boundary (RHB).

Second Partial Derivatives and First Derivative Continuity


(HighestOrderDerivative=2)
• 2nd-order central finite difference (CFD2) for section
interior nodes.
• First spatial derivative continuity (ddx Cont) at section
boundaries (SBound).
• No second derivative at left-hand boundary (LHB) and right-
hand boundary (RHB).

PDE Order LHB Section1 Section1 Section1 Sbound Section2 Section2 Section2
RHB
Node 0 Node 1 Node 2 Node 3 Node 4 Node 5 Node 6 Node 7 EndNode

1-ddx FFD1 BFD1 BFD1 BFD1 BFD1 BFD1 BFD1 BFD1 BFD1
2-d2dx2 None CFD2 CFD2 CFD2 ddx Cont CFD2 CFD2 CFD2 None

4th-Order Central Finite Difference (CFD4)


The CFD4 discretization method uses the 4th-order CFD method
for 1st- and 2nd-partial derivatives, except near the section and
domain boundaries as shown in the following table. The minimum
number of elements required for CFD4 for 1st- and 2nd-order
problems is four.

5-38 • Modeling PDE Systems Modeling Language Reference


First Partial Derivatives (HighestOrderDerivative=1 or 2)
• 4th-order central finite difference (CFD4) for all interior
nodes, except at/near the boundaries (fictitious points).
• 4th-order forward finite difference (FFD4) for first
derivative at left-hand domain boundary (LHB).
• 4th-order backward finite difference (BFD4) for the section
boundaries and the right-hand boundary (RHB).
• 4th-order downwind biased finite difference (DBFD4) and
upwind biased finite difference (UBFD4) for interior nodes
next to the left-hand and right-hand boundaries,
respectively.

Second Partial Derivatives and First Derivative Continuity


(HighestOrderDerivative=2)
• 4th-order central finite difference (CFD4) for all interior
nodes, except at/near the boundaries (fictitious points).
• 4th-order downwind biased finite difference (DBFD4) and
upwind biased finite difference (UBFD4) for interior nodes
next to the boundaries.
• First spatial derivative continuity (ddx Cont) at section
boundaries (SBound).
• No second derivative at left-hand boundary (LHB) and right-
hand boundary (RHB).

PDE LHB Section1 Section1 Section1 Section1 Sbound Section2 Section2 Section2
Section2 RHB
Order Node 0 Node 1 Node 2 Node 3 Node 4 Node 5 Node 6 Node 7 Node 8 Node 9 EndNode

1-ddx FFD4 DBFD4 CFD4 CFD4 UBFD4 BFD4 DBFD4 CFD4 CFD4 UBFD4 BFD4
2-d2dx2 None DBFD4 CFD4 CFD4 UBFD4 ddx Cont DBFD4 CFD4 CFD4 UBFD4 None

4th-Order Upwind Biased Finite Difference (UBFD4)


The UBFD4 discretization method uses the 4th-order UBFD
method for 1st- and 2nd-partial derivatives, except near the section
and domain boundaries as shown in the following table. The
minimum number of elements required for UBFD4 for 1st- and
2nd-order problems is four.

First Partial Derivatives (HighestOrderDerivative=1 or 2)


• 4th-order upwind biased finite difference (UBFD4) for all
interior nodes, except at/near the boundaries (fictitious
points).
• 4th-order forward finite difference (FFD4) for first
derivative at left-hand domain boundary (LHB).
• 4th-order backward finite difference (BFD4) for section
boundaries and the right-hand boundary (RHB).

Modeling Language Reference Modeling PDE Systems • 5-39


• 4th-order downwind biased finite difference (DBFD4) and
central biased finite difference (CFD4) at interior nodes next
to the LHB.

Second Partial Derivatives and First Derivative Continuity


(HighestOrderDerivative=2)
• 4th-order upwind biased finite difference (UBFD4) for all
interior nodes, except at/near the boundaries (fictitious
points).
• 4th-order downwind biased finite difference (DBFD4) and
central biased finite difference (CFD4) at interior nodes next
to the LHB.
• First spatial derivative continuity (ddx Cont) at section
boundaries (SBound).
• No second derivative at left-hand boundary (LHB) and right-
hand boundary (RHB).

PDE LHB Section1 Section1 Section1 Section1


Sbound Section2 Section2 Section2 Section2 RHB
Order Node 0 Node 1 Node 2 Node 3 Node 4 Node 5 Node 6 Node 7 Node 8 Node 9 EndNode

1-ddx FFD4 DBFD4 CFD4 UBFD4 UBFD4 BFD4 DBFD4 CFD4 UBFD4 UBFD4 BFD4
2-d2dx2 None DBFD4 CFD4 UBFD4 UBFD4 ddx Cont DBFD4 CFD4 UBFD4 UBFD4 None
Discretization The finite element family of methods divides the domain into many
Methods: Finite smaller elements and applies weighted residual methods within
Element Methods each element. The weighted residual methods assume that the
solution can be represented as a weighted combination of known
polynomial approximations of order n with unknown weighting
coefficients. The latter are determined to satisfy boundary
conditions and the system of equations at a finite set of points,
called collocation or polynomial points. The precise criterion used
to choose the weighting coefficients determines the method.
The weighted residual method that is combined with the finite
element concept is the method of orthogonal collocation (OCFE).
Second- and fourth-order OCFE methods are provided as shown in
the following table. You can specify that you want to use an OCFE
method using the DiscretizationMethod property assignment when
declaring a domain.

5-40 • Modeling PDE Systems Modeling Language Reference


Method Order of Type of Approximation Polynomial
Approximation (Collocation) Points

OCFE2 2nd-order Orthogonal Collocation 0.00000, 0.50000,


on Finite Elements 1.00000
OCFE4 4th-order Orthogonal Collocation 0.00000, 0.21132,
on Finite Elements 0.50000, 0.78868,
1.00000

As shown in the following tables for OCFE2 and OCFE4, the


domain is divided into a number of elements and orthogonal
collocation is applied within each element. The value of EndNode
is equal to the number of elements times the order of the method,
where the order is the number of collocation points plus one. By
using the Interior set provided, the PDEs in your model are
evaluated automatically at the interior collocation points only. The
correct derivatives are also evaluated automatically. For 1st-order
PDE problems, the first derivatives at the element boundaries are
calculated using the element to the left of the boundary. For 2nd-
order PDEs, the OCFE methods are implemented using the
condition that the first derivatives are continuous between
elements. This treatment of the boundaries between elements gives
a solution that is continuous, with continuous flux, as in the exact
solution.

OCFE2
PDE LHB Node 0 Element1 ElemBoundNode 2 Element2 Coll 1 RHB EndNode 4
Order Coll 1

1 ddx ddx ddx Elem1 ddx ddx


2 None d2dx2 ddx Cont d2dx2 None

OCFE4
PDE LHB Element1 Element1 Element1 ElemBound Element2 Element2 Element2 RHB
Order Node 0 Coll 1 Coll 2 Coll 3 Node 4 Coll 1 Coll 2 Coll 3 EndNode 8

1 ddx ddx ddx ddx ddx Elem1 ddx ddx ddx ddx
2 None d2dx2 d2dx2 d2dx2 ddx Cont d2dx2 d2dx2 d2dx2 None

Finite Element Remarks


One advantage of finite element methods is their ability to handle
problems with steep gradients by concentrating many small
elements in areas with steep gradients.

Modeling Language Reference Modeling PDE Systems • 5-41


PDE Modeling Glossary
Dirichlet
Dirichlet is a type of boundary condition that specifies the values
of the dependent variables at the boundary points as a function of
time.

Distributed parameter system


A distributed parameter system contains process variables that vary
with respect to spatial position as well as time.

Distribution
A distribution is a variable distributed over one or more domains.

Domain
A domain is a region over which a distributed parameter system is
discretized.

Method of Lines
The Method of Lines is an approach to solving time-dependent
PDAE systems by discretizing in space, but leaving the time
variable continuous

Neumann
Neumann is a type of boundary condition that specifies the values
of the first-order spatial derivatives on the boundary.

5-42 • Modeling PDE Systems Modeling Language Reference


6 Modeling Language for
Flowsheets

This chapter describes defining flowsheets. The following topics


are covered:
• Defining flowsheets
• Declaring blocks
• Defining the connectivity of blocks
• Making flowsheet assignments
• Specifying variable properties
• Defining flowsheet constraints

Modeling Language Reference Modeling Language for Flowsheets • 6-1


Defining Flowsheets
To define a flowsheet in text format, you can include the
statements:
• Creating blocks — instances of models in the flowsheet
• Defining the connectivity of blocks
• Defining the Fixed, Initial, RateInitial, and Free variables
and their values
• Defining variables and equations in a constraint definition

Flowsheet Syntax

FLOWSHEET
FlowsheetStatements
CONSTRAINTS
Variable and Equation definitions
END
END

Flowsheet Remarks
The flowsheet describes instances of models and streams, and the
connections between them. Models and streams describe the
equations and variables that will be solved.
You usually define the flowsheet using the GUI. However, you
may sometimes prefer to define the flowsheet in a text editor,
where cutting and pasting lines of text is more efficient than
placing blocks on a flowsheet. For example, you may want to
create a large, repetitive flowsheet, where the same model is used
many times.
Caution If you want to use a text editor to modify an existing
flowsheet in a saved language file by either adding or deleting
blocks, you must delete the existing text flagged in the file as
SYSTEM SECTION. Before deleting the System section, you are
strongly advised to make a backup copy of your work. The System
section usually contains graphical or other data in a strict format
associated with the last saved flowsheet. Normally, you should
avoid editing the System section, but in this case, you must delete
the System section to be able to open the modified language file.
You can declare variables local to the flowsheet that are used in
flowsheet equations. All variables and equations in a flowsheet
must be declared between the keywords CONSTRAINT and END.
Constraint equations can include variables in the flowsheet blocks.
This syntax does not apply to hierarchy flowsheets. These should
only be created and editing using the GUI.

6-2 • Modeling Language for Flowsheets Modeling Language Reference


Flowsheet Example
The following example shows how to define a flowsheet and
specify values between the keywords FLOWSHEET and END.
FLOWSHEET
/* Declare three blocks using the model called
TankModel */
Tank1 AS TankModel ;
Tank2 AS TankModel ;
Tank3 AS TankModel ;
/* Declare a stream using a stream type that
contains equations */ HS1 AS HeaterStream ;
// Make the inlet and outlet connections
CONNECT Tank1.Input ;
CONNECT Tank1.Output AND Tank2.Input ;
CONNECT Tank2.Output AND Tank3.Input WITH HS1 ;
CONNECT Tank3.Output ;
/* Assign the known values for time zero of the
dynamic run */
Tank1.Input.Flow : 3.0, Fixed ;
Tank1.area : 0.67, Fixed ;
Tank1.k : 1.8, Fixed ;
Tank1.height: 2.0, Initial ;
Tank2.area : 0.67, Fixed ;
Tank2.k : 1.8, Fixed;
Tank2.height: 2.0, Initial ;
/* Optional use of WITHIN\ENDWITH */
WITHIN Tank3
Area : 0.92, Fixed ;
K : 12.8, Fixed;
Height : 1.45, Initial;
ENDWITH
//The Flowsheet is fully described
END

Modeling Language Reference Modeling Language for Flowsheets • 6-3


Declaring Blocks
An instance of a model in the flowsheet is known as a block. You
can declare blocks in the flowsheet using the following syntax.

Block Declaration Syntax

BlockName AS ModelName ;

BlockName............... Name of the block you choose for this block


ModelName .............. Name of the model you associate with this block

Block Declaration Remarks


Each statement declares one instance of a model in a flowsheet.
Each statement can use the same model with a different block
name. This enables you to use one model a number of times on the
same flowsheet. Each block has its own version of the equations
and variables defined in the model.
After you have declared the blocks on the flowsheet, you can
connect the blocks using CONNECT statements.

Block Declaration Example


This example shows how blocks are declared in the flowsheet
description.
FLOWSHEET
Feed1 AS Feeder ;
Tank1 AS TankModel ;
Valve1 AS Valve;
END

6-4 • Modeling Language for Flowsheets Modeling Language Reference


Defining the Connectivity of Blocks
For information on defining the connectivity of blocks, see Chapter
4, CONNECT Keyword.

Making Flowsheet Assignments


Use assignment statements to give values to parameters and
variables in the flowsheet. You can define whether the variables
are known throughout the simulation, known only at time zero of a
dynamic simulation, or you can give a specific first guess value to
a variable.
You can also change the values of the variable properties.

Flowsheet Assignment Syntax

BlockName.VariableName : Value , Spec ;

or

BlockName.ParameterName : ParameterValue ;

BlockName .............. Name of a block in the flowsheet


VariableName .......... Name of a variable in the block
ParameterName Name of a parameter in the block
Value ........................ Numerical or string value assigned to the block
variable
Spec ......................... Specification of a block property. If you do not
specify a value, Free is assumed. Valid values are:
• Fixed
• Initial
• RateInitial
• Free
The specification Initial means that the state
variable itself is initialized, whereas RateInitial
applies to the time derivative. The two are
mutually exclusive specifications. Similarly, you
cannot fix the state variable and initialize the time
derivative. This helps to ensure that you do not
give incorrect specifications.

Modeling Language Reference Modeling Language for Flowsheets • 6-5


Flowsheet Assignment Remarks
For assigning values to large numbers of variables in the same
block, use the WITHIN / ENDWITH syntax. For information on
WITHIN / ENDWITH, see Chapter 1.
Note An assignment written in a flowsheet is equivalent to
updating a value in a table. The new value will override any
previous assignment to the same property.

Flowsheet Assignment Example


The following example shows how to assign values to variables in
the flowsheet definition.
Constraints
ProductPrice AS RealVariable;
FeedCost AS RealVariable;
Profit AS Money;
ProfitCalculation: Profit =
s11.flow*ProductPrice-s1.flow*FeedCost;
End
/*Assign the values and specifications of some
variables */
Tank1.FlowIn : 25., Fixed;
Tank1.Area : 0.79, Fixed;
Tank1.Volume : 1.57, Initial;
Reactor.Temp: 120, Vary;
/* In Tank2, the time derivative, $Volume, is
initialized */
Tank2.$Volume: 0;
Tank2.Volume: RateInitial;
/* Assign a value to a parameter */
Column1.Ntrays : 24 ;

6-6 • Modeling Language for Flowsheets Modeling Language Reference


Specifying Variable Properties
You can change the values of properties of a variable’s type in the
flowsheet description.

Variable Properties Syntax

BlockName.VariableName.PropertyName : PropertyValue ;

BlockName.............. The name of the model instance


VariableName ......... The name of the variable in the model
PropertyName......... The name of the variable type property
PropertyValue......... The value of the variable type property

Variable Properties Example


In the following example, the Value property of the variable
FlowIn is assigned a new value:
Tank1.FlowIn.Value : 1.45 ;
The second example shows an assignment for the property Lower:
Tank1.FlowIn.Lower : -100.0 ;

Modeling Language Reference Modeling Language for Flowsheets • 6-7


Defining Flowsheet Constraints
You can define the following in a flowsheet constraint definition:
• Variables
• Parameters
• Equations
• Procedure calls
• Assignments
• Equalities and inequalities
Use the flowsheet constraints to write equations that contain
variables from different blocks on your flowsheet. For more
information on constraints, see Chapter 2.

Flowsheet Constraint Example


The following example shows two heat exchangers in separate
loops. The duty Q is equated in the constraint to model the process
fluid in one loop heating or cooling the process fluid in the other
loop.
FLOWSHEET
HeatX1 AS HeatExchanger;
HeatX2 AS HeatExchanger;
Feed1 AS FeedStream;
Feed2 AS FeedStream;
CONNECT HeatX1.ProcessIn WITH Feed1;
CONNECT HeatX2.ProcessIn WITH Feed2;
CONNECT HeatX1.ProcessOut;
CONNECT HeatX2.ProcessOut;
CONSTRAINT
HeatX1.Q = -HeatX2.Q;
END
END

6-8 • Modeling Language for Flowsheets Modeling Language Reference


7 Modeling Language
Conventions

This chapter describes the following:


• Conventions used when writing modeling language
• Text conventions used in this manual to describe the
modeling language

Modeling Language Reference Modeling Language Conventions • 7-1


Modeling Language Conventions
This section describes the conventions you must follow when
writing modeling language.
Adding Comments You can use two comment markers:

Symbol Effect

// Everything to the right of the // characters is commented out. The // comment


marker is not modal on the line, so everything to the right of // on one line is
commented out. A second // on the same line has no effect.
/* ... */ All text between /* and */ is commented out. /* and */ pairs can be nested.

In the model editor, all commented out text appears highlighted in


green. However, note that the text editor does not highlight
commented information after a nested comment.
Comments Examples The following examples show the use of the comment markers:
// This is a comment

// This is a comment // This is a comment also

/*All text in this sentence is commented out

*/
General Modeling The modeling language is free format. This means that you can
Language write syntax over several lines and insert spaces for clarity.
Conventions The modeling language is not case sensitive.

7-2 • Modeling Language Conventions Modeling Language Reference


Text Conventions
The conventions used in the documentation that describes the
modeling language are:

Convention Example Meaning

Text in courier font FlowIn = FlowOut ; Examples of modeling language.


... Item , Item ... A list of arguments
. MODEL HeatedTray USES Heater More text is required but not shown
. .
.
.
END
Text in bold, upper case MODEL, CONNECT, AND Aspen Custom Modeler keywords
Text with initial capital VariableName, Value You must supply a name, quantity, etc.
letters
Italic text VALUE:Value , HIBOUND:HiBound ; You may supply the indicated optional
arguments

Modeling Language Reference Modeling Language Conventions • 7-3


7-4 • Modeling Language Conventions Modeling Language Reference
Index

control signal stream type 1-30, 4-25


/ model type 1-28
modeling language for 1-24
/ used as comment symbol 7-2
parameter types 1-25
port type 1-30
A
slack variable type 1-31
ALWAYSCALL keyword 3-20 solved type 1-27
Arithmetic operators 4-12 stream type 1-29
Arrays
distinguished from sets 1-13 C
in equations 4-13
C language
modeling language for 1-17
modeling language for external procedures
values assigned to elements 1-8
3-18
with many elements or dimensions 4-19
CHANGESINPUTS keyword 3-20
Assignments
Comments in modeling language 7-2
array elements 1-8
Comparison operators 4-15
in flowsheets 6-5
Compatibility with SPEEDUP 5.5 3-19
lists 1-9
Component lists
modeling language for 1-5
modeling language for 3-13
statements for 1-2
multiple 3-15
values to variables in tasks 2-21
validating 3-13
WITHIN and ENDWITH 1-9
ComponentList property 3-13–3-15, 4-6
Conditional equations
B
modeling language for 2-22, 4-15
Base types 1-24 sets in 4-18
BLOCK keyword 1-11 CONNECT keyword 4-25
Blocks Connection built-in stream type 1-29, 4-25
modeling language for 6-4 Connection port type, built-in 1-31
passing values between 3-5 Connections
Built-in types modeling language for streams 3-8
connection port type 1-31 ConnectionSet property 4-9–4-10, 4-31
connection stream type 1-29, 4-25 Constraints
control port type 1-30 modeling language in flowsheets 2-45, 6-8

Modeling Language Reference Index • 1


Control port type, built-in 1-30 identifying objects from 1-10
ControlSignal built-in stream type 1-30, 4- EXTERNAL qualifier 4-41
25
Conventions F
documentation 7-3
Fixed specification, defined 4-37
modeling language 7-2
Fixed values 1-12
Converting
Flow, direction of 4-5
strings and integers 1-19
Flowsheets
units of measurement 2-2
constraints 2-45, 6-8
CONVERTTO operator 1-19
FLOWSHEET keyword 6-2
Folders
D
creating your own 3-22
Declaration statements 1-4 FOR loops
Definitions, modeling language for re-using modeling language for 4-19
1-20 ForEach loops
DERIVATIVES keyword 3-20 modeling language for 4-21
DIFFERENCE operator 1-15, 4-21 Fortran
Directories modeling language for external procedures
creating your own 3-22 3-18
Discontinuities Free specification, defined 4-37
modeling language for 2-15 Functions
Disturbances in sets 1-15
modeling language for 2-15 modeling language for 3-18
Duplicate names, BLOCK and STREAM 1-
11 G
Generic types 3-9
E
GenericConnection built-in stream type 1-29
ENDPARALLEL keyword 2-26–2-27 GenericConnectionSignal built-in stream
ENDWITH keyword 1-9 type 1-30
Equations GenericModel built-in model type 1-28
calling procedures 4-23 GenericPort built-in port type 1-30
conditional 4-15 GenericStream built-in stream type 1-29
logical operators 4-16 GLOBAL qualifier 4-2
mathematical operators 4-12
modeling language for 4-11 H
referring to port variables 4-24
HIDDEN qualifier 4-2
switching between 4-46
Homotopy simulations
with array variables 4-13
modeling language for 2-46
Estimation simulations
accessing results 2-37
I
modeling language for 2-30
External procedures IF keyword
modeling language for 3-18 defining conditional equations on the
External programs value of a simulation variable in tasks
2-22

2 • Index Modeling Language Reference


defining structural variation with 1-12 MOL for PDEs 5-36
in conditional equations 4-15 Multidimensional arrays, SIGMA for 4-34
Index value in FOR loops 4-19 Multiports 4-8
Indexed assignments 1-8
Inheritance N
defined 1-20
Names
related types 1-21
duplicate 1-11
Initial specification, defined 4-37
rules for choosing 1-10
INPUT qualifier 4-2
Nesting model folders 3-22
Instances of models, modeling language for
6-4
O
IntegerParameter built-in parameter type 1-
25 Objective specification, defined 4-37
Integers, converting to strings 1-19 Operators
IntegerSet 1-14 ForEach expressions 4-21
INTERSECTION operator 1-15, 4-21 logical 4-15
IS keyword 4-43, 4-46, 5-18 mathematical 4-12
IsComponentSet keyword 3-12 Optimization simulations
IsConnected property 1-27, 1-30, 1-31, 4-6 modeling language for 2-42
IsMatched attribute 4-7 OUTPUT qualifier 4-2

L P
LINK keyword 4-29 PARALLEL keyword 2-26–2-27
Logical operators 4-12, 4-15 PARAMETER keyword 1-12, 1-25
LogicalParameter built-in parameter type 1- Parameters
25 built-in types 1-25
defined 1-12
M modeling language for 3-4
relating to variables 4-11
Matching port variables 4-7
Path names, assignment lists for 1-9
Mathematical operators 4-12
Pausing a simulation 2-28
MAX operator 4-12, 4-21
PDAE models 5-23
Method of Lines 5-36
PDE models 5-1
MIN operator 4-12, 4-21
Physical properties
MODEL keyword 3-6
modeling language for 3-11
Modeling language
Physical quantities 2-3, 2-4
conventions for writing 7-2
PhysicalQuantity property 2-3
Models
PORT keyword 3-5
built-in type for 1-28
Ports
connecting 4-25, 4-29
built-in type 1-30
modeling language for blocks 6-4
collections of 4-8
modeling language for model types 3-6
connecting 4-5
specifications in 4-37
modeling language for 3-5, 4-5, 4-25, 4-29
variables in 4-2
properties for 4-6
Modes of operation 4-46
restrictions in streams 3-8

Modeling Language Reference Index • 3


variables in equations 4-24 Simulation Messages window
POSTCALL keyword 3-20 task messages in 2-27
PRECALL keyword 3-20 Simulations
Predefined types 1-24 accessing estimation results 2-37
PRESET keyword 3-20 estimation modeling language 2-30
Printing homotopy 2-46
task messages to Simulation Messages optimization 2-42
window 2-27 SIZE function 4-36
Procedures Slack variable type, built-in 1-31, 2-45
called from equations 4-23 Snapshots
modeling language for 3-18 modeling language for 2-26
PRODUCT operator 4-12, 4-21 Solved types 1-27
Properties Solver properties
adding to variables 3-16 modeling language for 3-16
for ports 4-6 Specifications
modeling language for 1-4, 6-7 in models 4-37
naming conventions 1-10 SPEEDUP
writing sub-models 4-41 COMPATIBILITY statement 3-19
PROPERTIES keyword 3-11, 3-20 SRAMP keyword 2-22
Statements
Q repeating 4-19, 4-21
syntax for 1-2
Qualifiers for variables 4-2
Step changes during simulation 4-15
STREAM keyword 1-11, 3-8
R
Streams
Ramp functions in tasks 2-22 built-in type 1-29
RAMP keyword 2-22 types for 3-8
RateInitial specification, defined 4-37 StringParameter built-in parameter type 1-25
RealParameter built-in parameter type 1-25 Strings, converting to integers 1-19
RealVariable built-in solved type 1-27 StringSet 1-14
Relational operators 4-15 Stringsets 1-19
Repeating statements 4-19, 4-21 Sub-models 4-39, 4-41, 4-44
RESTART statement 2-23 Switch definitions 4-46
Re-using models 6-4 Symbols
for sets 1-15
S SYMDIFF operator 1-15, 4-21
Sets SystemLibrary library 1-24
arithmetic for 1-15
defined 1-13, 1-17 T
in conditional expressions 4-18 Task statements
SIZE function 4-36 assigning values to variables 2-21
SIGMA conditional equations 2-22
for multidimensional arrays 4-34 modeling language for creating snapshots
ForEach operator 4-21 2-26
syntax for 4-33 overview 2-21

4 • Index Modeling Language Reference


parallel 2-26 Values
pausing a simulation 2-28 array elements 1-8
printing to Simulation Messages window fixed 1-12
2-27 VARIABLE keyword 3-2
ramping value of variables 2-22 Variables
suspending 2-23 adding properties to 3-16
Tasks in models 4-2
callable 2-18 modeling language for 3-2, 6-7
modeling language for 2-15 relating to parameters 4-11
opening simulations 2-20 solved for 1-27
rewinding simulations 2-20 Vary specification, defined 4-37
task statements 2-21
Testing W
parameters modeling language 1-12
WAIT statement 2-23
Text conventions in documentation 7-3
WITHIN keyword 1-9
TYPE keyword 3-9
Types
atomic 3-16
built-in 1-20, 1-24
generic 3-9
keywords for 3-9
model 3-6
modeling language for 1-3, 1-4
naming conventions 1-10
parameters 1-12
physical properties 3-11
port 3-5
related 1-21
stream 3-8
variable 3-2
virtual types in sub-models 4-44

U
UNION operator 1-15, 4-21
Units of measurement
automation 2-4
modeling language for 2-2
UOM
modeling language for 2-2
USES keyword 1-20, 3-2, 3-5
UseUOMof qualifier 4-2

V
Validating component lists 3-13

Modeling Language Reference Index • 5


6 • Index Modeling Language Reference

You might also like