0% found this document useful (0 votes)
13 views242 pages

UniSim Design Customization Guide

Uploaded by

alex
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views242 pages

UniSim Design Customization Guide

Uploaded by

alex
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UniSim® Design

Customization Guide

Customization Guide

Release 492
October 2022
DISCLAIMER

This document contains Honeywell proprietary information. Information contained herein is to be used solely for the purpose
submitted, and no part of this document or its contents shall be reproduced, published, or disclosed to a third party without the
express permission of Honeywell International Sàrl.

While this information is presented in good faith and believed to be accurate, Honeywell disclaims the implied warranties of
merchantability and fitness for a purpose and makes no express warranties except as may be stated in its written agreement
with and for its customer.

In no event is Honeywell liable to anyone for any direct, special, or consequential damages. The information and specifications in
this document are subject to change without notice.

Copyright 2022 - Honeywell International Sàrl

-2-
CONTENTS

Chapter 1 - Introduction 8
1.1 Customization 8
1.2 Automation & Extensibility 9
1.2.1 Automation 9

1.2.2 Extensions 9

1.3 Customizing UniSim Design 10


1.3.1 UniSim Design & the Macro Language Editor 10

1.3.2 Programming UniSim Design from External Programs 12

Chapter 2 - Automation 13
2.1 Introduction 13
2.2 Objects 13
2.2.1 Object Hierarchy 14

2.2.2 UniSim Design Type Library 14

2.2.3 Object Browser 14

2.3 Automation Syntax 18


2.3.1 Declaring Objects 18

2.3.2 Set Keyword 18

2.3.3 GetObject, CreateObject 19

2.3.4 Object Properties, Methods, & Hierarchy 20

2.3.5 Collection Objects 21

2.3.6 Variants 22

2.4 Key UniSim Design Objects 24


2.4.1 UniSim Design Object Overview 24

2.4.2 Container Objects 24

2.4.3 Basis Objects 25

2.4.4 Oils Objects 38

-3-
2.4.5 Stream Objects 40

2.4.6 Operation Objects 42

2.4.7 Support Objects 45

2.4.8 PFD Objects 48

2.5 Example 1: The Macro Language Editor 48


2.6 Example 2: Automation in Visual Basic 55

Chapter 3 - Extensibility 64
3.1 Introduction 64
3.2 Implementing Interfaces 65
3.2.1 Implementing an Interface Through a Dispatch Interface 65

3.2.2 Implementing an Interface Through a Custom Interface 65

3.3 Data Types 65


3.4 Extension Development Kit 66
3.5 Creating an Extension 66
3.5.1 In Visual Basic 66

3.5.2 In C++ 69

3.6 Registering Extensions 72


3.6.1 Registering Extensions Written in C++ 72

3.6.2 Registering Extensions Written in Visual Basic 74

3.7 Extension Interface Details 74


3.7.1 ExtnContainer Interface 75

3.7.2 ExtensionObject Interface 75

3.8 Extension Reaction Kinetics 75


3.8.1 Extension Definition Files 76

3.8.2 ExtnKineticReaction Interface 77

3.8.3 ExtnKineticReactionContain er Interface 77

3.8.4 Kinetic Reaction Example 77

3.9 Extension Property Packages 90


3.9.1 Initialization 91

3.9.2 ExtensionPPkgInit structure 91

3.9.3 ExtnPPkgContainer Interface 92

3.9.4 ExtnPropertyPackage Interface 93

3.10 Extension Unit Operations 93

-4-
3.10.1 Extension Definition Files 94

3.10.2 ExtnUnitOperationContainer Interface 94

3.10.3 ExtnUnitOperation Interface 94

3.10.4 Passes 95

3.10.5 Extension Unit Operation Example 95

3.11 References 122

Chapter 4 - Extension View Editor 123


4.1 Introduction 123
4.1.1 Accessing the View Editor 123

4.1.2 Creating a New EDF File 125

4.1.3 Editing an Existing EDF File 126

4.2 Using the View Editor 127


4.2.1 Manipulating Widgets 127

4.2.2 DefaultView Form Toolbar 130

4.2.3 Visibility Manager 133

4.2.4 The Objects Manager View 138

4.2.5 Views Manager 141

4.3 Widget Properties 141


4.3.1 Moniker Specification 142

4.3.2 Common Widget Properties 144

4.3.3 DefaultView Form Object 145

4.3.4 Button Widget 148

4.3.5 Static Text Widget 150

4.3.6 Text Entry Widget 151

4.3.7 Rich Text Entry Widget 152

4.3.8 Format Entry Widget 153

4.3.9 Numerical Input Widget 153

4.3.10 Matrix Widget 155

4.3.11 Check Box Widget 161

4.3.12 Radio Buttons Widget 162

4.3.13 Graphic Button Widget 163

4.3.14 Group Widget 165

4.3.15 Page Tabs Widget 165

4.3.16 Ply Picker Widget 167

-5-
4.3.17 Attachment Name Widget 168

4.3.18 Enumeration Widget 169

4.3.19 Unit Enumeration Widget 170

4.3.20 Text List Widget 171

4.3.21 Enumeration List Widget 173

4.3.22 Attachment List Widget 174

4.3.23 Level Widget 176

4.3.24 Plot Widget 178

4.3.25 Worksheet Matrix Widget 179

4.3.26 ACTIVEX Container Widget 182

Chapter 5 - User Variables 183


5.1 Introduction 183
5.2 Adding a User Variable 183
5.3 Importing/Exporting User Variables 187
5.3.1 Exporting a User Variable 187

5.3.2 Importing a User Variable 189

5.4 User Variable View 189


5.5 Data Types 190
5.5.1 Type Drop-down List 190

5.5.2 Dimensions Drop-down List 190

5.5.3 Real Data Type 190

5.5.4 Enumeration Data Type 191

5.5.5 Message Data Type 192

5.5.6 Code Only Data Type 192

5.6 User Variables Tabs 192


5.6.1 Macros Tab 192

5.6.2 Attributes Tab 194

5.6.3 Filters Tab 195

5.6.4 Security Tab 196

5.6.5 Defaults Tab 197

5.7 Code Editor 197


5.7.1 Tool Tip Text 198

5.8 User Variable Examples 198

-6-
5.8.1 Dew Point Temperature Variable 198

5.8.2 Automatic Pump Energy Stream 202

Chapter 6 - User Unit Operation 206


6.1 Introduction 206
6.2 Adding a User Unit Operation 206
6.2.1 Importing and Exporting a User Unit Op 208

6.3 User Unit Op Property View 208


6.3.1 Design Tab 209

6.3.2 Worksheet Tab 214

6.4 Dehumidifier Example 214

Chapter 7 - Customization FAQ 221


7.1 Automation FAQ 221
7.2 Extensibility FAQ 226
7.2.1 General Extensibility 226

7.2.2 Unit Operation Extensions 227

7.2.3 Kinetic Reaction Extensions 240

-7-
CHAPTER

1 INTRODUCTION

1.1 Customization
Unlike its accompanying volumes, the Customization Guide does not discuss exact procedures for accomplishing tasks
within UniSim Design. The purpose of this volume is to demonstrate the possible simulation technologies that can be created
both within UniSim Design and also in addition to the application. UniSim Design incorporates an advanced software
architecture and OLE Technology to provide a component- based framework that can be easily customized, updated and
maintained to meet changing user requirements.

The term customization encompasses several different approaches for tailoring UniSim Design including:

Method Description

Automation The use of third party tools such as Visual Basic or the UniSim Design Macro Language Editor to
programmatically run UniSim Design.

Extensibility The creation of custom unit operations, property packages and kinetic reactions which become part of the
simulation and function as built in UniSim Design objects.

The difference between automation and extensibility may not be explicitly apparent. The difference lies in the environment in
which your personal algorithms are executed. Automation requires the use of third party software to link to UniSim Design in
a client-server relationship. Using this functionality, you can hide the complexity of a simulation by building a front-end in
another program that allows access to only the important parameters of the simulation. You can also use UniSim Design as a
server in your own applications. UniSim Design is an Automation Server, which means that it can act as an Automation client
that can be used to access UniSim Design. Some examples of tools that can access UniSim Design are Microsoft Visual
Basic and the VBA component of applications such as Excel, Word, PowerPoint and Visio. You can also access UniSim
Design through programs written in C++.

Extensibility incorporates your custom algorithms in the form of Extension Property Packages, Extension Unit Operations,
and Extension Reaction Kinetics. The calculations take place within the calculation sequence of a UniSim Design simulation.
Extensions can be easily distributed to other machines, and they appear as any other UniSim Design object in the program.
You could easily develop an extension, test it, market it and sell it to other UniSim Design users as a third party add-in.

The Customization Guide’s purpose is threefold:

l To introduce the user to the functionality of UniSim Design automation and extensibility.
l To demonstrate different methods of accessing and using UniSim Design objects.
l To provide straightforward examples that teach you the basics and allow you to begin customizing UniSim Design.

Within the UniSim Design environment, several tools are provided so you can begin writing code for automation and
extensions:

Tool Description

The Macro Language Editor An interactive design environment for developing, testing and executing WinWrap
basic scripts.

User Variables and the User Unit Allow you to increase the functionality of UniSim Design by creating your own
Operation variables or unit operations.

-8-
Chapter 1 - Introduction

TIP
For more information on User Variables and User Unit Ops see User Variables and User Unit Operation.

1.2 Automation & Extensibility


1.2.1 Automation
Automation allows programmers to expose objects within a program for use by other applications. The exposed objects
provide the means by which different applications can interact with each other and the operating system. Automation is a
standard based on Microsoft's Component Object Model (COM). It is not necessary to understand all the intricacies of
Automation or COM in order to utilize the functionality they provide.

Automation evolved from what was once called OLE, which stands for Object Linking and Embedding. This allowed you to
take a particular object such as a spreadsheet and embed it into another object such as a text document. Changes to values
in the spreadsheet would automatically be updated in the text document. This was a very powerful feature and was available
to users without the added complexity of writing code. It was simply a matter of cutting and pasting the objects.

Automation is the ability to programmatically interact with an application through objects exposed by developers of that
application. While UniSim Design was being developed, code was added to expose various objects in the program. By using
an Automation client like Visual Basic, the end user can write the code to access these objects and interact with UniSim
Design. The end user does not need to see the UniSim Design source code or even understand what was required to
expose the objects. All that is required is the knowledge of those objects that are available.

Automation works in a client/server fashion. A server is something that provides a service that can be used by clients if they
know the proper protocols. UniSim Design is an Automation server application. By writing a little Visual Basic code, it is
possible to send and receive information to and from UniSim Design. The exposed objects make it possible to perform nearly
any action that is accomplished through the UniSim Design graphical user interface.

You can use Automation to access UniSim Thermo in UniSim Design to calculate UniSim Thermo properties such as
fugacity coefficients, K- values, entropy, and enthalpy.

1.2.2 Extensions
The UniSim Design architecture allows direct extensibility for unit operations, kinetic reactions, and property packages.
Extensibility can be described as the ability to augment existing functionality in a direct and seamless manner. Unit operation
extensions look and feel like the existing operations in UniSim Design but the algorithms used by the extension reside in a
separate Windows DLL. Similarly, kinetic reaction extensions and property package extensions appear seamlessly in the
basis environment.

A UniSim Design extension is typically composed of two distinct and interdependent components; an ActiveX Server DLL
and an Extension Definition File (EDF). The ActiveX Server DLL contains the actual code for the extensions and can be
created in any OLE controller language such as Visual Basic, C++, or Delphi. Nearly any other type of compiled code base
can be accessed via a short wrapper utilizing Visual Basic or C++. The Server is a program that exposes a class with a set of
properties and methods. For UniSim Design extensions, the exposed class contains methods recognized by UniSim Design
(for example, when dealing with a Unit Operation Extension, UniSim Design looks for a method named Initialize that takes
one argument and returns a long variable).

The EDF file acts as the interface view within UniSim Design as well as the point for variable declaration and storage. It is
created through the Extension View Editor which is included with your copy of UniSim Design. The View Editor is similar to
the tool used by Honeywell Developers when creating the views for UniSim Design.

[Link] How Does a UniSim Design Extension Work?

When UniSim Design first starts up, it looks in the system registry, at a specific location, to see if any extensions exist for the
machine. If an extension does exist it is added to the appropriate menu within UniSim Design. Unit operation extensions
show up in the UnitOps view when the Extensions radio button is selected. Kinetic reaction extensions show up in the
Reactions view which is brought up when the Add Rxn button is clicked on the Reactions tab of the Simulation Basis

-9-
Chapter 1 - Introduction

Manager property view. Property package extensions show up in the Property Package Selection group found on the Set
Up tab of the Fluid Package property view.

Once you find the appropriate extension, you can select it and begin using it as though it were a built-in UniSim Design
object.

1.3 Customizing UniSim Design


UniSim Design can be programmatically run from any tool that supports Automation. You can set up scripts that do repetitive
tasks, or you can set up programs of your own that uses UniSim Design as the calculation engine.

For example, the simulation of a plant can be easily hidden by a front- end created in Microsoft Excel. This front-end could be
a yield prediction program of some sort that uses a rigorous simulation underneath. Another example would be a proprietary
equipment sizing program that uses UniSim Design to generate fluid properties for the calculations.

When creating these programs, UniSim Design can be run invisibly. You do not need to know the source of the calculations,
nor do you need to deal with another program on the desktop.

Third party tools are not required to access the automation capabilities of UniSim Design. UniSim Design provides an
Internal Macro Engine that supports the same syntax as Microsoft Visual Basic. With this engine, you can automate tasks in
UniSim Design without the need for another program.

1.3.1 UniSim Design & the Macro Language Editor


The Macro Language Editor is accessed by selecting the Macro Language Editor command from the Tools menu in the
Simulation environment.

TIP
For more information on the Macro Language Editor, consult the online help that accompanies the editor. You can find
the online help in the Help menu in the Editor’s menu bar.

- 10 -
Chapter 1 - Introduction

Figure 1.1

The editor is an interactive design environment for developing, testing and executing WinWrap Basic automation scripts. The
editor, which uses a syntax that is very similar to Microsoft®’s Visual Basic, allows you to write code that interacts with
UniSim Design.

Two objects can be accessed directly from any point in a macro:

l Application
l ActiveCase

These special commands allow you to generalize your macros so that they can be run under many different situations. If you
reference the ActiveCase object, your macro works for any Simulation Case that is currently open in the UniSim Design
environment.

The Macro Language Editor now has two new features:

l Autocompletion feature, which helps you complete the user variable codes and helps you debug the program with
flyby evaluation.
For example, if you want to specify “SimulationCase”, you just need to type up the first few letters of the variable, and
the autocompletion feature will display all variables with similar names in a drop-down list.

Figure 1.2

l List command feature, which shows you a list of valid methods or properties depending on the context (type of
expression) you enter.
For example, if you type ActiveObject and type the period, a drop-down list appears displaying a list of methods
that are applicable to the current object.

Figure 1.3

- 11 -
Chapter 1 - Introduction

1.3.2 Programming UniSim Design from External Programs


UniSim Design can be accessed from external programs using Automation. Programs such as Microsoft Visual Basic and
Microsoft Excel can use UniSim Design as a calculation engine, allowing you to create new applications that invisibly use
UniSim Design in the background.

Two UniSim Design objects can be created by an external program:

l The UniSim Design Application object


l The UniSim Design SimulationCase object

The Application object can be created using the UniSim [Link] ProgID. Simulation Cases can be created using
the UniSim [Link] ProgID, or by calling GetObject and passing the name of a Simulation Case. For
example, this is how you would create an Application object and a SimulationCase object from Visual Basic:

Dim App as Object


Set App = CreateObject(“[Link]”)
Dim HYCASE as Object
Set HYCASE = GetObject(“c:\UniSim Design\cases\[Link]”)

Once the Application and Case objects have been created, other UniSim Design objects can be accessed through them. For
example, from the Case's flowsheet object (accessed through the flowsheet property of the Case), you can create new
Process Streams and Unit Operations.

[Link] VBA

Microsoft Excel and related products make use of Visual Basic for Applications (VBA). VBA is a high level programming
language that is oriented around an object framework and event driven execution. Visual Basic is termed “visual” because
most applications are created around a graphical interface and Visual Basic is designed to allow code associated with the
interface to be added easily and intuitively.

Event driven programming is quite different from typical structured programming. In a structured program, execution begins
at the top of the program and executes for the most part in a sequential manner. When the bottom of the program is reached
the application exits and is finished. In event driven programming, the path of execution from the beginning of the program to
the end depends almost entirely on how the end user interacts with the application.

Visual Basic for Applications is a large sub-set of the Visual Basic language. It is a macro language that is integrated tightly in
to supporting applications. The syntax and functionality is identical to straight Visual Basic.

- 12 -
CHAPTER

2 AUTOMATION

2.1 Introduction
Automation, defined in its simplest terms, is the ability to drive one application from another. For example, the developers of
Product A have decided in the design phase that it would make their product more usable if they exposed Product A’s
objects, thereby making it accessible to Automation. Since Products B, C and D all have the ability to connect to applications
that have exposed objects, each can programmatically interact with Product A.

In the early product planning stages, the UniSim Design development team had the vision to begin exposing objects. That,
makes UniSim Design a very powerful and useful tool in the design of hybrid solutions. Since access to an application
through Automation is language- independent, anyone who can write code in Visual Basic, C++ or Java, to name three
languages, can write applications that interact with UniSim Design. There are a number of applications that can be used to
access UniSim Design through Automation, including Microsoft Visual Basic, Microsoft Excel and Visio. With so many
combinations of applications that can transfer information, the possibilities are numerous and the potential for innovative
solutions is endless.

2.2 Objects
The key to understanding Automation lies in the concept of objects. An object is a container that holds a set of related
functions and variables. In Automation terminology, the functions of an object are called methods and the variables are called
properties.

Consider the example of a simple car. If it were an object, a car would have a set of properties such as: make, colour, number
of doors, etc. The car object may also have methods such as: turn on, drive or open hood. By utilizing the properties and
methods of a car object it is possible to define, manipulate and interact with the object.

Figure 2.1

Each property of the car is a variable that has a value associated with it. The colour would be a string or hexadecimal number
associated with a specific colour. The gas mileage would be single floating point value. Methods are nothing more than
functions and sub-routines associated with the object.

- 13 -
Chapter 2 - Automation

An object is a container that holds all the attributes associated with it. An object could contain other objects that are logical
sub-set of the main object. The car object may contain other objects such as engine or tire. These objects would have their
own set of independent properties and methods. An engine would have properties related to the number of valves and the
size of the pistons. The tires would have properties such as tread type or model number.

2.2.1 Object Hierarchy


The path that is followed to get to a specific property may involve several objects. The path and structure of objects is
referred to as the object hierarchy. In Visual Basic the properties and methods of an object are accessed by hooking together
the appropriate objects through a dot operator (.) function. Each dot operator in the object hierarchy is a function call. In
many cases it is beneficial to reduce the number of calls by setting intermediate object variables.

For instance, expanding on our previous example involving the car, suppose there existed an object called Car and you
wanted to set the value of its engine size. You could approach the problem in one of two ways.

Direct specification of object property

[Link] = 4

Indirect specification of object property

Dim Eng1 as Object


Set Eng1 = [Link]
Eng1 = 4

If the Engine size is a property you wanted to access quite often in your code, using the indirect method of specification may
be easier as it reduces the amount of code thereby reducing the possibility of error.

2.2.2 UniSim Design Type Library


In order to do anything with objects it is first necessary to know what objects are available. When an application is exposed
for Automation, a separate file is usually created that lists all the objects and their respective properties and methods. This file
is called the type library and nearly all programs that support Automation have one of these files available. With the help of an
Object Browser, such as the one built in to MS Excel, you now have a way to view all the objects, properties, and methods in
the application by examining the type library.

The UniSim Design type library reveals over 340 objects that contain over 5000 combined properties and methods. For
every object, the type library shows its associated properties and methods. For every property, the type library shows its
return type. For every method, the type library shows what type of arguments are required and what type of value might be
returned.

Accessing a specific property or method is accomplished in a hierarchical fashion by following a chain of exposed objects.
The first object in the chain should be an object from which all other objects can be accessed. This object is typically the main
application or one of the open documents. In UniSim Design, the starting objects are the SimulationCase and Application
objects. All other objects are accessible through these two starting objects.

2.2.3 Object Browser


The type library itself does not exist in a form which is immediately viewable to you. In order to view the type library, you
require the use of an application commonly referred to as an Object Browser. The Object Browser interprets the type library
and displays the relevant information. Microsoft Excel and Visual Basic both include a built in Object Browser.

- 14 -
Chapter 2 - Automation

[Link] Accessing the Object Browser in Excel 2007

1. Open the Developer panel.


2. Press ALT F11 (or select Visual Basic option from Code group).
3. Within the Visual Basic Editor, open the Tools menu.
4. Select the References command.
5. Check the checkbox next to the UniSim Design Type Library.
6. Click the OK button.
7. Open the View menu and select the Object Browser command (or press F2).
8. Open the <All Libraries> drop-down list and select UniSimDesign.

[Link] Navigating Through the type Library

This section shows how to navigate through the type library in order to determine the object hierarchy necessary to access a
particular property. Consider the desired property is the temperature of a stream called “Feed_Stream”.

The first step is to begin with one of the starting objects. The Application and SimulationCase objects are the starting points
in UniSim Design. You can visualize what is available from the Application object by picturing the UniSim Design application
view when the program is first started. You can do the same with the SimulationCase object by thinking of all the information
contained within a case. Nearly all the objects of interest are accessed from the SimulationCase object.

Figure 2.2

Selecting the SimulationCase object in the browser reveals all of its related properties and methods. Examining the list of
properties does not reveal any type of stream like object so there must be a connection through another object. The
properties that are links to other objects can be determined by looking at the type shown when a property is selected. If the
type shown is not a string, Boolean, variant, double, integer, or long then it is most likely an object. The object type shown is
found somewhere in the object list and is the next step to determining the object hierarchy.

- 15 -
Chapter 2 - Automation

With prior experience in UniSim Design the flowsheet object is a logical choice. Selecting the flowsheet object in the object
list shows the associated properties and methods. There is an EnergyStreams property, a MaterialStreams property, and a
Streams property. All three of these properties are of type Streams and are therefore objects. In this case some previous
experience in using UniSim Design would suggest that MaterialStreams is the object of interest.

Figure 2.3

The MaterialStreams object is of type Streams. Examining the Streams object does not reveal any temperature properties.
The Streams object is a collection object, which is simply an object that is a collection of other objects with some properties
and methods for navigating through the collection.

In this case the Streams object is a collection of ProcessStream objects.

- 16 -
Chapter 2 - Automation

Figure 2.4

The individual members of a collection object can be accessed by index number (like an array) or directly by name. Either
approach can be used through the Item property. Examining the ProcessStream object shows a property called
TemperatureValue, which is of type Double. This is the desired property.

Figure 2.5

The resulting syntax for the desired property is:

[Link].
Item(“Feed_Stream”).TemperatureValue

- 17 -
Chapter 2 - Automation

2.3 Automation Syntax


2.3.1 Declaring Objects
An object in Visual Basic is another type of variable and should be declared. Objects can be declared using the generic type
identifier object. The preferred method however uses the type library reference to declare the object variables by an explicit
object name.

Early Binding:

Dim|Public|Private objectvar As ObjectName as specified


in the type library

Late Binding:

Dim|Public|Private objectvar As Object

Once a reference to the type library has been established, the actual name of the object as it appears in the type library can
be used. This is called early binding. It offers some advantages over late binding, including speed and access to Microsoft’s
Intellisense® functionality when using Visual Basic or VBA.

Example: Late Binding

Public usdCase As Object


Public usdStream As Object

Example: Early Binding

Public usdCase As SimulationCase


Public usdStream As ProcessStream

2.3.2 Set Keyword


Connections or references to object variables are made by using the Set keyword.

Syntax:

Set objectvar = object.[object…].object | Nothing

The example below assumes usdcase is set to the SimulationCase object.

Example: Set

Dim usdStream As ProcessStream


Set usdStream = [Link](0)

- 18 -
Chapter 2 - Automation

2.3.3 GetObject, CreateObject


In order to begin communication between the client and server applications, an initial link to the server application must be
established. In UniSim Design this is accomplished through the starting objects: Application or SimulationCase. The typical
ActiveX object structure supplies a starting object to access the application interface and another to access the documents
within the application.

Syntax for creating an instance of an application:

CreateObject(class)
GetObject([pathname] [, class])
where:
class = the starting object as specified in the type library.
In UniSim Design there are two objects that can be used for the class statement:
[Link] or
[Link].

The CreateObject function starts a new instance of the main application. CreateObject is used in UniSim Design with the
UniSim [Link] class as specified in the type library. This connects to the main application interface of UniSim
Design.

The GetObject function opens a specific document in the currently running instance of the server application. If the
application is not running then a new instance of the application starts. If a specific document is not specified with the
GetObject function the current instance of the application is connected or a new instance of the application is started.

For application objects or document objects the codes are shown below:

Example: CreateObject and GetObject

Set applicationobj = CreateObject(“[Link]”)


or
Set applicationobj = GetObject(,“[Link]”)
Set documentobj = GetObject(“c:\filepath”, “[Link]”)

In the example below, usdCase is declared as type object so it is using late binding. The usdCase variable is connected to a
UniSim Design case by using the GetObject function and the Set keyword. The second argument in the GetObject function is
the starting object.

Example 1: Starting a UniSim Design case through Automation

Dim usdCase As Object


Set usdCase = GetObject(“c:\samples\[Link]”, “[Link]”)

The second example is identical to the first except that the object variable usdCase is declared using the actual object name
as it appears in the type library. This assumes that a reference to the type library has already been set.

Example 2: Starting a UniSim Design case through Automation

Dim usdCase As SimulationCase


Set usdCase = GetObject(“c:\samples\[Link]”,“[Link]”)

- 19 -
Chapter 2 - Automation

The third example uses early binding in the object declaration. The CreateObject command is used to bring up an instance of
UniSim Design. The starting object here is the UniSim [Link] object since a case is not initially being opened.
The SimulationCases object is accessed through the Application object and the Open method of SimulationCases is used to
bring up a specific UniSim Design case. The usdCase object is set to the active case through the ActiveDocument property
of usdApp.

Example 3: Starting a UniSim Design case through Automation

Dim usdCase As SimulationCase


Dim usdApp As [Link]
Set usdApp = CreateObject(“[Link]”)
[Link](“c:\UniSimDesign\samples\[Link]”)
Set usdCase = [Link]

Sometimes it is desirable to run UniSim Design as an "engine" with minimal interruptions. Popup message boxes that can
occur under normal operation would interrupt the workflow and there are ways to limit these. Message boxes can be
reduced by making this call (note usdApp can be obtained in various ways - one way is shown in example 3 (above):

[Link]

If very important to avoid message boxes (i.e. running USD via aservice and any message box would block execution
invisibly), then this use-at-your-own risk method can be used:

[Link]("DisableAllMessageBoxesAtUsersRisk", True)

The above call should only be used in conjunction with ChangePreferencesToMinimizePopupWindows to ensure we
respond to known prompts intelligently. This last technique is not guaranteed to operate reliably because it will answer some
prompts arbitrarily with a False value - which may or may not be the best choice given the context.

2.3.4 Object Properties, Methods, & Hierarchy


The sequence of objects is set through a special dot function. Properties and methods for an object are also accessed
through the dot function. It is preferable to keep the sequence of objects to a minimum since each dot function is a call to link
between the client and the server application.

Syntax for setting objects and accessing properties:

Set objectvar = object.[[Link]...].object


Variable = object.[[Link]...].property

Syntax for accessing methods:

Function Method
returnvalue = [Link]([argument1,argument2,...])
Sub-routine Method
[Link] argument1, argument2

The object hierarchy is an important and fundamental concept for utilizing Automation. A particular property can only be
accessed by following a specific chain of objects. The chain always begins with either the Application or SimulationCase
object and ends with the object containing the desired property.

The methods of an object are accessed in the same fashion as properties by utilizing the dot function. A method for a
particular object is nothing more then a function or sub-routine whose behaviour is related to the object in some fashion.

- 20 -
Chapter 2 - Automation

Typically the methods of an object require arguments to be passed when the method is called. The type library provides
information about which arguments are necessary to call a particular method. A function returns a value.

TIP
Sub-routines in Visual Basic do not require parentheses around the argument list.

The example below, starts up UniSim Design and opens a specific case. The temperature value of a specific stream is then
obtained. The temperature value is obtained through a connection of three objects: SimulationCase, Flowsheet, and
MaterialStreams.

Example 1: Accessing UniSim Design object properties

Dim usdCase As SimulationCase


Dim TempVal As Double
Set usdCase = GetObject(“c:\[Link]”,”[Link]”)
TempVal = [Link](0).Temperature Value
MsgBox TempVal

The example below, also accesses the temperature value of a specific stream but creates some intermediate objects so that
when the temperature value is actually requested the chain of objects only contains one object.

Example 2: Accessing UniSim Design object properties

Dim usdCase As SimulationCase


Dim usdFlowsheet As Flowsheet
Dim usdStream As ProcessStream
Dim TempVal As Double
Set usdCase = GetObject(“c:\samples\[Link]”,“[Link]”)
Set usdFlowsheet = [Link]
Set usdStream = [Link](0)
TempVal = [Link] MsgBox TempVal

2.3.5 Collection Objects


A collection object is an object that contains a set of other objects. This is similar to an array of objects. The difference
between an array of objects and a collection object is that a collection object contains a set of properties and methods for
navigating and manipulating the objects in the collection.

Syntax: Typical Properties of a Collections Object

Item(index) Access a particular member of the collection by number.

Item(name) Determines the index number for a member in the collection by its name.

Count Returns the number of objects in the collection.

Syntax: Enumeration of Objects

For Each element In group


[statements]
[Exit For]

- 21 -
Chapter 2 - Automation

[statements]
Next [element]

The most commonly used properties are:

l Index. The Index property takes in a name and returns a number value associated with the object’s name.
l Item. The Item property takes an index value or name or integer number as the argument and returns a reference to
the object within the collection.
l Count. The Count property returns the number of items in the collection.

A special type of For loop, called For Each, is available for enumerating through the objects within the collection. The For
Each loop provides a means for enumerating through the collection without explicitly specifying how many items are in the
collection. This helps avoid having to make additional function calls to the Count and Item properties of the collection object in
order to perform the same type of loop.

The example below, connects to a collection of streams by setting the usdStreams object. A For loop is created that uses the
Count and Item properties of a collection in order to display a view that contains the stream name. The items in the collection
are indexed beginning with 0. The Count property returns the actual number of objects in the collection so it is necessary to
subtract one in order to access all the objects in the collection.

Example 1: Accessing Collection Objects

Dim usdStreams As Streams


Dim usdStream As ProcessStream
Set usdStreams = [Link]
For j = 0 To [Link] - 1
MsgBox [Link](j).name
Next j

The example below, is identical to the first example except that a For Each loop is used instead of the standard For loop in
order to enumerate through the Streams collection.

Example 2: Accessing Collection Objects

Dim usdStreams As Streams


Dim usdStream As ProcessStream
Set usdStreams = [Link]
For Each usdStream In usdStreams
MsgBox [Link]
Next usdStream

2.3.6 Variants
A property can return a variety of variable types. Values such as temperature and pressure are returned as doubles or 32-bit
floating- point values. The stream name property returns a string value. Visual Basic provides an additional variable called a
variant. A variant is a variable that can take on the form of any type of variable including, Integers, Double, String, Array, and
Objects.

Syntax for using variant values

Dim myvariant as Variant


myvariant = {[Link]}

To determine the upper and lower bound of the variant:

- 22 -
Chapter 2 - Automation

UBound(arrayname[,dimension])
LBound(arrayname[,dimension])

If the property of an object returns an array whose size can vary depending upon the case, then a variant is used to access
that value. For example, the ComponentMassFractionValue property of a ProcessStream returns an array of doubles sized
to the number of components associated with that stream.

In Visual Basic, if a variable is not explicitly declared then it is implicitly a variant. Variants have considerably more storage
associated with their use, so for a large application it is good practice to limit the number of variants being used. It is also just
good programming practice to explicitly declare variables whenever possible.

The dimensions of the array depend upon what property is being called. The following table lists the most common
properties that return arrays and what is the dimension of the array.

Common Variant of UniSim Design Returning Property

Component Mass Fractions One Dimensional array

Column Component Fraction Values Two Dimensional array

Interaction Parameters Two Dimensional array

The example below, shows how to get an array of stage pressures in a column. The usdOp object is declared as a
ColumnOp as specified in the type library. The operations collection is filtered to only include columns by using the word
“ColumnOp”. UsdOp is set to the first column in the operations collection. UsdStagePressure is set equal to an array of
doubles returned by the ColumnOp object. Since the number of stages in this column may not be known the Ubound function
is used to determine the upper bound of the one dimensional array. A view prints out the pressure value for each stage in the
column.

Example 1: Using Variants in UniSim Design

Dim usdOp As ColumnOp


Dim usdStagePressure As Variant
Set usdOp = [Link](“ColumnOp”).Item(0)
usdStagePressure = [Link]
For j = 0 To UBound(usdStagePressure)
MsgBox “Stage “ & j +1 & “ Pressure = “ &
usdStagePressure(j)
Next j

The example below, accesses the VapourComponentFraction property of a column. The array is set to usdStageCompFrac.
This array is two- dimensional. The first dimension represents the components in the systems as specified in the fluid
package. The second dimension represents the stages in the column. A view displays the vapour fraction of component 1 for
each stage of the column.

Example 2: Using Variants in UniSim Design

Dim usdOp As ColumnOp


Dim usdStageCompFrac As Variant
Set usdOp = [Link](“ColumnOp”).Item(0)
usdStageCompFrac = [Link]
For j = 0 To UBound(usdStageCompFrac,2)
MsgBox “Stage “ & j +1 & “ Component 1 Vapour Fraction = “ & usdStageCompFrac(0,j)
Next j

- 23 -
Chapter 2 - Automation

2.4 Key UniSim Design Objects


2.4.1 UniSim Design Object Overview
There are over 340 automation objects exposed in UniSim Design. These objects collectively contain of over 5000 properties
and methods. One of the more time consuming and difficult tasks in learning to use Automation objects is determining what
objects are available and how to get at a property of interest.

The following sub-sections are designed to explore key UniSim Design objects in more detail and hopefully provide the
necessary information required to access nearly any object, property, or method in UniSim Design. Because of the large
number of key objects and their attributes, the objects within UniSim Design have been divided in seven distinct categories.
These object categories are: Container Objects, Support Objects, Oil Objects, Basis Objects, Stream Objects, Operation
Objects, Extension Objects, and PFD Objects.

2.4.2 Container Objects


This category refers to objects that house other objects or form the basis from which a large number of objects are derived.
For instance, the Application object can contain several SimulationCase objects. The SimulationCase object contains all the
remaining objects associated with that case. The flowsheet object is a repository for all the streams and unit operations of the
case. The flowsheet can also contain another flowsheet, Application or SimulationCase.

[Link] Application and SimulationCase

The Application object is the top most object in UniSim Design and represents the UniSim Design program itself. From the
Application object, nearly all the objects listed in the UniSim Design type library can be accessed. The SimulationCase object
is the starting object for accessing or opening specific simulation cases.

Syntax: Connecting to the Application

Set usdApp = CreateObject(“[Link]”)

Syntax: Connecting to the Simulation Case

' Through GetObject


Set usdCase = GetObject(“filepath”,“[Link]”)
' Through the Application Object
Set usdCase = [Link]
' Through SimulationCases Collection Object
Set usdCase = [Link](“CaseName”)

The SimulationCase object and the Application object can be created directly through the GetObject function in Visual Basic.
The CreateObject function can also be used to access the Application object. In general the starting object for most
Automation procedures is the SimulationCase object.

The example below, uses the GetObject function to start-up UniSim Design with the specified case.

Example 1: Accessing the UniSim Design Container Objects

Dim usdCase As SimulationCase


Set usdCase = GetObject(“c:\UniSim Design\cases\c- [Link]”,“[Link]”)

The example below, connects to the UniSim Design Application object and enumerates through all the currently open cases.
If a case name matches the specified string then a SimulationCase object is set to that case. The FOR loop cycles through
the list of cases based on the count value. In Visual Basic arrays and collections are base 0 unless otherwise specified.

Example 2: Accessing the UniSim Design Container Objects

- 24 -
Chapter 2 - Automation

Dim usdApp As [Link]


Dim usdCases As SimulationCases
Dim usdCase As SimulationCase
Set usdApp = CreateObject(“[Link]”)
Set usdCases = [Link]
For j = 0 To [Link] - 1
If [Link](j).name = “[Link]” Then
Set usdCase = [Link](j)
End If
Next j

[Link] Flowsheet(s)

The main flowsheet object is accessed through the SimulationCase object. The flowsheet object is a container of all the
ProcessStream and Operations objects as well as a link to the FluidPackage object associated with that flowsheet. Each
flowsheet and sub-flowsheet can have its own fluid package and likewise its own property package and set of components.
Sub-flowsheets can be accessed from the main flowsheet object through the flowsheet collection object.

Syntax: Flowsheet Object

Dim usdFlowsheet As Flowsheet


Set usdFlowsheet = [Link]

The above syntax, shows how to connect to the flowsheet object of the UniSim Design case. This assumes the usdCase
variable is already set to the SimulationCase object in UniSim Design. The remaining examples in this module assume a
SimulationCase object 'usdCase' is already set.

The example below, shows how to connect to a sub-flowsheet of a flowsheet. Sub-flowsheets are accessed from the main
flowsheet. The main flowsheet is accessed through the SimulationCase.

Example: Connecting Flowsheets

Dim usdFlowsheet As Flowsheet


Dim usdSubFlowsheets As Flowsheets
Dim usdSubFlowsheet As Flowsheet
Set usdFlowsheet = [Link]
Set usdSubFlowsheets = [Link]
Set usdSubFlowsheet = [Link](0)

2.4.3 Basis Objects


The Basis objects refer predominantly to objects handled by the UniSim Design BasisManager. The BasisManager object in
UniSim Design is responsible for handling the global aspects of a UniSim Design simulation case. These objects include
reactions, components, and property packages.

The BasisManager object is accessed through the SimulationCase object. From the BasisManager object the
FluidPackages and HypoGroups collection objects are accessed. Changing the objects accessed directly or indirectly
through the BasisManager such as FluidPackages, PropertyPackage, Components, and Hypotheticals requires notification
to the UniSim Design simulation environment. The BasisManager object contains methods that allow changes to the basis to
take place smoothly. The following methods must be used on the outer limits of any code that makes changes to Basis
objects.

Syntax: Changing Basis Values

[Link]... changes to components, interaction

- 25 -
Chapter 2 - Automation

parameters, reactions, etc.


[Link]

[Link] FluidPackage(s)

Although both examples of syntax shown below lead you to a FluidPackage object, there are differences that exist which are
only apparent when attempting to use the fluid package.

Syntax: Accessing FluidPackages

From the BasisManager


[Link](0)
From the Flowsheet
[Link]

The FluidPackages object returned by the BasisManager object is a collection object containing all FluidPackage objects in a
case. Each FluidPackage object can have its own PropertyPackage object and Components object. When you access the
fluid package in this way, changes can be made to the property package and the list of components.

When obtaining a reference to the FluidPackage object from the flowsheet object, you are accessing the one fluid package
associated with the flowsheet. You can view the property package or component list of the FluidPackage object, however
you are not able to make any changes.

The example below, displays the number of FluidPackage objects in a case and sets a FluidPackage object to the first
member of the FluidPackages collection.

Example: FluidPackage

Dim usdFluidPackages As FluidPackages


Dim usdFluidPackage As FluidPackage
Set usdFluidPackages = [Link]
MsgBox “Number of Fluid Packages = “ & [Link]
Set usdFluidPackage = [Link](0)

[Link] OLE Interface for Phase Property and Derivatives

This interface is implemented in the FluidPackage object and by QueryInterface from FluidPackage, user can access to this
interface

Interface Name

PhasePropertyDerivatives

Interface Functions

Function to calculate phase enthalpy, entropy, cp and volume with derivatives, defined by DerVars.

Function

PhaseEnthWithDerivatives(
[in] double Temperature, [in] double Pressure,
[in] VARIANT Compositions, [in] PhaseType phType,
[in] DerivativeType DerType, [in] VARIANT DerVars,
[in, out] double* Enthalpy, [in, out] double* Entropy,
[in, out] double* HeatCapacity, [in, out] double* MolarVolume,

- 26 -
Chapter 2 - Automation

[in, out] VARIANT* DEnthalpy, [in, out] VARIANT* DEntropy,


[in, out] VARIANT* DHeatCapacity, [in, out] VARIANT*
DMolarVolume)

Arguments

l Temperature - in K
l Pressure - in kPa
l Compositions - Mole composition
l phType - Phase Type
l DerType - Derivative Type
l DerVars - Derivative Variables
l Enthalpy - Enthalpy kJ/kgmole
l Entropy - Entropy kJ/kgmole.K
l HeatCapacity - Heat Capacity kJ/kgmole.C
l MolarVolume - Molar Volume m^3/kgmole
l DEnthalpy - Derivative for enthalpy
l DEntropy - Derivative for entropy
l DHeatCapacity - Derivative for heat capacity
l DMolarVolume - derivative for molar volume

Function for calculate phase LnFugacity with one derivative defined by DerVar

Function

PhaseLnFugacityWithDerivatives(
[in] double Temperature,
[in] double Pressure, [in] VARIANT Compositions,
[in] PhaseType PhaseType, [in] DerivativeType DerType,
[in] DerivativeVariable DerVar, [in,out] VARIANT* LnFugacity,
[in, out] VARIANT* DLnFugacity)

Arguments

l Temperature - in K
l Pressure - in kPa
l Compositions - Mole composition
l phType - Phase Type
l DerType - Derivative Type
l DerVar - Derivative Variable
l LnFugacity - Ln fugacities for the compounds
l DLnFugacity - Derivatives for the ln fugacities

Derivative Options

Users have to pass one of following options to calculate the properties and derivatives.

- 27 -
Chapter 2 - Automation

l Numerical: Using this option user can obtain derivatives numerically even though analytical derivative is available for
requested property.
l Analytical: Using this option user can obtain derivatives analytically.
l Numerical Backup: Using this option user can obtain derivatives numerically ONLY when analytical derivatives are
not implemented for respective property derivative. If analytical derivatives are available for the property, then it will
be obtained. For example, assume dh/dt is available analytically and dh/dp is not available analytically. Using
"Numerical Backup" option, user can obtain dh/dt calculated analytically and dh/dp calculated numerically.
l NoDerivative: Derivatives will not be calculated, only phase properties will be calculated.

Limitations

The following limitations are for UniSim Design R430, more functionality will be realized in future development.

l In current version, analytical derivative are supported ONLY by Peng Robinson property package.
l Volume derivative gets calculated ONLY when user chooses "Use EOS Density" option (Exclusive of Volume
Translation).
l Enthalpy derivative gets calculated ONLY when user chooses "Equation of State" option.
l The derivatives are ONLY limited to Temperature and Pressure. Derivatives with respect to composition are NOT
supported

[Link] PropPackage (PropertyPackage)

The PropPackage object is accessed through the FluidPackage object. Each FluidPackage object can have a single
PropPackage object. The type of property package can be determined through the PropPackage TypeName property or
through the PropertyPackageName property of the FluidPackage object. Each property package has a set of unique
properties and methods along with the common ones shared among all property packages.

Syntax to determine the type of property package

[Link].
[Link](0).Pro [Link]
or
[Link].
[Link](0).Pro pertyPackageName

The example above, connects to the FluidPackages collection object and checks each member FluidPackage to see if it
contains the PengRobinson property package.

Example: Property Package

Dim usdFluidPackages As FluidPackages


Dim usdFluidPackage As FluidPackage
Dim usdBasis As BasisManager
Dim usdPropPackage As PropPackage
Set usdBasis = [Link]
Set usdFluidPackages = [Link]
For Each usdFluidPackage In usdFluidPackages
If [Link] = “PengRobinson” Then
MsgBox “PengRobinson Property Package is Present”
Set usdPropPackage = [Link]
End If
Next usdFluidPackage

OLE Interface

New OLE interface named as PropertyDerivatives is supported for property derivatives.

- 28 -
Chapter 2 - Automation

Interface Name Derived From Methods

PropertyDerivatives IUnknown EnthalpyDerivatives

FugacityDerivatives

Figure 2.6

HRESULT EnthalpyDerivatives(
[in] double Temperature,
[in] double Pressure,
[in] VARIANT CompositioCurrns,
[in] VARIANT PhaseTypes,
[in] VARIANT PhaseFractions,
[in] DerivativeType DerType,
[in, out] VARIANT* Enthalpy,
[in, out] VARIANT* Entropy,
[in, out] VARIANT* HeatCapacity,
[in, out] VARIANT* MolarVolume,
[in,out] VARIANT* DEnthalpy,
[in, out] VARIANT* DEntropy,
[in, out] VARIANT* DHeatCapacity,
[in, out] VARIANT* DMolarVolume);

S/No Argument Name Type Description

1 Temperature Scalar User Input

2 Pressure Scalar User Input

3 Compositions Vector User Input

Vector Size = Number of Phase * No of Component

Example:

Number of Phase is 3 and Number of Component is 3.

Vector Size is = 3 * 3 = 9.

Compositions[0] to Composition[2] is the placeholder for Vapor Phase .

Compositions[3] to Composition[5] is the placeholder for Liquid Phase .

Compositions[6] to Composition[8] is the placeholder for Liquid2 Phase.

If there are only Liquid Phase and three components. Then composition vector
will populate as given below.

Set composition for vapor phase and Liquid2 phase to 0 and set the correct
composition to liquid phase as shown below.

Compositions[0] = 0

Compositions[1] = 0

Compositions[2] = 0

Compositions[3] = 0.1

- 29 -
Chapter 2 - Automation

S/No Argument Name Type Description

Compositions[4] = 0.5

Compositions[5] = 0.4

Compositions[6] = 0

Compositions[7] = 0

Compositions[8] = 0

4 PhaseTypes Vector User Input

5 PhaseFraction Vector User Input

6 DerivativeType Scalar User Input. User can select an option from below list.

l Analytical
l Numerical
l NumericalBackup

For details refer to the section Derivative Options.

7 Enthalpy Vector Output: Phase Molar Enthalpies

8 Entropy Vector Output: Phase Molar Entropies

9 HeatCapacity Vector Output: Phase Molar Heat Capacities

10 MolarVolume Vector Output: Phase Molar Volumes

11 DEnthalpy Vector Both Input and Output.

Details are explained in the sectionDerProp Structure .

Vector Size = 4 + 3 * (2 + Number of Components)

12 DEntropy Vector Same as above

13 DHeatCapacity Vector Same as above

14 DMolarVolume Vector Same as above

HRESULT FugacityDerivatives(
[in] double Temperature,
[in] double Pressure,
[in] VARIANT Compositions,
[in] VARIANT* LnFugacity,
[in] VARIANT PhaseTypes,
[in] DerivativeType DerType,
[in, out] VARIANT* DLnFugacity);

S/No Argument Name Type Description

1 Temperature Scalar User Input

2 Pressure Scalar User Input

3 Compositions Vector User Input

4 LnFugacity Vector Output

- 30 -
Chapter 2 - Automation

S/No Argument Name Type Description

5 PhaseTypes Vector User Input

6 PhaseFraction Vector User Input

7 DerivativeType Scalar Users can select an option from below list.

l Analytical
l Numerical
l NumericalBackup
For details refer to section Derivative Options.

8 DLnFugacity Vector Both Input and Output.

Details are explained in the section DerProp Structure .

Vector Size = 4 + 3 * (2 + Number of Components) * Number of Components.

DerProp Structure

typedef struct
{
int Tdev;
int Pdev;
int Xdev;
int Ndev;
double TdevVar[3];
double PdevVar[3];
double* XdevVar[3];
double* NdevVar[3];
double* TdevVarVec[3];
double* PdevVarVec[3];
double** XdevVarVec[3];
double** NdevVarVec[3];
}DerProp;

Data Member Details

Tdev User option for temperature dependent property derivatives 0/1

1 indicates to calculate derivatives.

0 indicates derivatives are not required.

Pdev User option for pressure dependent property derivatives 0/1.

1 indicates to calculate derivatives.


0 indicates derivatives are not required.

Xdev User option for mole fraction dependent property derivatives 0/1.

1 indicates to calculate derivatives.


0 indicates derivatives are not required.

TdevVar[3] d/dT(Property) for all three phases

PdevVar[3] d/dP(Property) for all three phases

XdevVar[3] d/dxi(Property) for all three phases and for all components

TdevVarVec[3] d/dT(Fugacity Property) for all three phases

- 31 -
Chapter 2 - Automation

Data Member Details


PdevVarVec[3] d/dP(Fugacity Property) for all three phases

XdevVarVec[3] d/dxi(Fugacity Property) for all three phases and for comps

Derivative Options

Users have to pass any one of following options to calculate the derivatives.

l Numerical: Using this option user can obtain derivatives numerically even though analytical derivative is available
for requested property.
l Analytical: Using this option user can obtain derivatives analytically. User has to note analytical derivatives can be
obtained only when users sets the flags like Tdev, Pdev and XDev flags for respective properties as shown below.

' Set the derivative flags for Tdev, Pdev and XDev to 1.
' Enthalpy
dh(1) = 1 ' Tdev
dh(2) = 1 ' Pdev
dh(3) = 1 ' Xdev

l Numerical Backup: Using this option user can obtain derivatives numerically ONLY when analytical derivatives
are not implemented for respective property derivative. If analytical derivatives are available for the property, then it
will be obtained.
For example, assume dh/dt is available analytically and dh/dp is not available analytically. Using "Numerical Backup"
option, user can obtain dh/dt calculated analytically and dh/dp calculated numerically.

- 32 -
Chapter 2 - Automation

Sample Code to calculate Enthalpy Derivatives

- 33 -
Chapter 2 - Automation

l Declaration of Variables
In this sample code we had assume there are ONLY three components.

Dim fpack As FluidPackage


Dim ppack As PropPackage
Dim pder As PropertyDerivatives

Dim tinK As Double


Dim pinkpa As Double

Dim molfrac(1 To 3) As Double '3 : Number of Components

Dim phaseflag(t To 3) As long '3 : Fixed Size


Dim phasefrac(1 To 3) As Double '3 : Fixed Size

Dim h(1 To 3) As Double '3 : Fixed Size


Dim s(1 To 3) As Double '3 : Fixed Size
Dim cp(1 To 3) As Double '3 : Fixed Size
Dim v(1 To 3) As Double '3 : Fixed Size

Dim dh(1 To 19) As Double '19 -> 4+3 * (2 + Number of Components)


Dim ds(1 To 19) As Double '19 -> 4+3 * (2 + Number of Components)
Dim dcp(1 To 19) As Double '19 -> 4+3 * (2 + Number of Components)
Dim dv(1 To 19) As Double '19 -> 4+3 * (2 + Number of Components)

l Initialization of Process Conditions and call to enthalpy derivative

' Set process conditions for a 3 component system


tinK = 25 + 273.15
pinkpa = 101.13
molfrac (1) = 0.2
molfrac (2) = 0.3
molfrac (3) = 0.5
phaseflag (1) = 1
phaseflag (2) = 0
phaseflag (3) = 0

phasefrac (1) = 1
phasefrac (2) = 0
phasefrac (3) = 0

' Set the derivative requirement flags


' Enthalpy
dh(1) = 1 ' Tdev
dh(2) = 1 ' Pdev
dh(3) = 0 ' Xdev
dh(4) = 0 ' Ndev
' Entropy
ds(1) = 1 ' Tdev
ds(2) = 1 ' Pdev
ds(3) = 0 ' Xdev
ds(4) = 0 ' Ndev
' Specific Heat
dcp(1) = 1 ' Tdev
dcp(2) = 1 ' Pdev
dcp(3) = 0 ' Xdev
dcp(4) = 0
' Volume
dv(1) = 1 ' Tdev
dv(2) = 1 ' Pdev
dv(3) = 0 ' Xdev
dv(4) = 0 ' Ndev

- 34 -
Chapter 2 - Automation

Call [Link](tinK, pinkpa, molfrac, phaseflag, phasefrac, Analytical, h, s, cp, v,


dh, ds, dcp, dv)

l Outputs Variables
Output vector organization for dh variable

Position in Results Vector


Variable Length
From To

TDev 1 1

PDev 1 2

XDev 1 3

NDev 1 4

Temperature NoOfPhases(3)(Vapor, Liquid, 5 4 + NoPhases


derivatives Liquid2)

Pressure derivatives NoOfPhases(3)(Vapor, Liquid, 5 + NoPhases 4 + 2 * NoPhases


Liquid2)

Composition NoOfPhases(3)(Vapor, Liquid, 5 + (2 + 4 + (2 + CmpIdx) *


Derivatives Liquid2) CmpIdx NoPhases
- 1) *
NoPhases
NOTE
For all CmpIdx = 1 toNoComp

Similarly User can obtain the values for other property derivatives.

Sample Code to calculate Fugacity Derivatives

l Declaration of Variables
In this sample code we had assumed there are ONLY three components.

Dim LnF(1 To 9) As Double


Dim dLnF(1 To 9) As Double ' 49 -> 4 + 3 * (2 + NoComp) * NoComp = 4+3*(2+3)*3 = 49
Dim nocomp As Integer

l Initialization and call to figacity derivative function

' **********************************
' Fugacity derivatives
' **********************************
dLnF(1) = 1 ' Tdev
dLnF(2) = 1 ' Pdev
dLnF(3) = 1 ' Xdev
dLnF(4) = 0 ' Ndev

Call [Link](tinK, pinkpa, lolfrac, LnF, Phaseflag, Numerical, DlnF)

Output vector organization for dLnf variable.

- 35 -
Chapter 2 - Automation

Position in Results Vector


Variable Length
From To

TDev 1 1

PDev 1 2

XDev 1 3

NDev 1 4

Temperature NoOfPhases(3)(Vapor, 5 + NoPhases (CmpIdx – 1) * 4 + NoPhases * CmpIdx


derivatives Liquid, Liquid2)

NOTE
For all CmpIdx = 1 to
NoComp

Pressure NoOfPhases(3)(Vapor, 5 + NoPhases (NoComp + 4 + (NoComp + CmpIdx) *


derivatives Liquid, Liquid2 CmpIdx – 1) * NoPhases

NOTE
For all CmpIdx = 1 to
NoComp

Composition NoOfPhases(3)(Vapor, 5 + NoPhases 4+


Derivatives Liquid, Liquid2) ((IndCmpIdx+1)NoComp + ((IndCmpIdx+1)NoComp +
CmpIdx – 1) * + CmpIdx) * NoPhases

NOTE
For all CmpIdx = 1 to
NoComp

For all IndCmpIdx = 1 to


NoComp

Limitation of Peng-Robinson Property Derivatives

l Volume derivative gets calculated ONLY when user chooses “Use EOS Density” option (Exclusive of Volume
Translation).
l Enthalpy derivative gets calculated ONLY when user chooses “Equation of State” option.
l In current version, analytical derivative are supported ONLY to Peng Robinson property package. The derivatives
are ONLY limited to Temperature and Pressure.
l Derivatives with respect to composition are NOT supported.
l In current version, numerical derivatives are not reported properly due to internal numerical issues for repetitive calls
on property calculations. If required, users are suggested to compare analytical derivatives obtained by manually
triggering independent variables and get required numerical derivative.
l Numerical derivative values for dcpdp and dlnfidp are not coming near to analytical derivative values.

[Link] Component(s)

The Components object is accessed through the FluidPackage object.

- 36 -
Chapter 2 - Automation

Each FluidPackage can have its own unique set of Components.

Syntax for accessing components

From the BasisManager


[Link](0).Components
From the Flowsheet
[Link]

The example below, shows how to access the Components object associated with a particular FluidPackage object. In this
example each component's normal boiling point is checked and a tally of all the components whose boiling point is below 0°C
is counted.

Example: Components

Dim numComp As Integer


Dim usdFluidPackage As FluidPackage
Dim usdBasis As BasisManager
Dim usdComponents As Components
Dim usdComponent As Component
Set usdBasis = [Link]
Set usdFluidPackage = [Link](0)
Set usdComponents = [Link] = 0
For Each usdComponent In usdComponents
If [Link] < 0 Then
numComp = numComp + 1
End If
Next usdComponent
MsgBox numComp & “ components have NBP below 0"

[Link] Hypotheticals

The HypoGroups collection object is accessed from the BasisManager. This object contains a collection of HypoGroup
objects, each of which provides access to a HypoComponents object. A HypoComponent can be entirely specified through
Automation and added to a UniSim Design simulation case. Methods for the HypoComponent object are used to estimate
properties based on the minimum data requirement.

Syntax: Hypotheticals

[Link](0).HypoCo [Link](0)

TIP
Hypotheticals have a '*' appended to the name once they are created.

The example below, adds a hypothetical component and sets its boiling point value in order to estimate the remaining
properties. The StartBasisChange and EndBasisChange methods are invoked prior to adding this hypothetical to the case.

Example: HypoComponent

Dim hypGroups As HypoGroups


Dim hypoComp As Object
[Link]
Set hypGroups = [Link] [Link] “myhypo”
[Link](“myhypo”).[Link] “mycomponent”, “userhypo”
Set hypoComp = [Link](“myhypo”).

- 37 -
Chapter 2 - Automation

[Link](“mycompo nent*”)
[Link] = 300
[Link]
MsgBox [Link]
[Link]

2.4.4 Oils Objects


Oils objects refer to the objects accessed through the Oil Manager. The OilManager object is set through the BasisManager
and contains Assay and Blend objects.

[Link] OilManager

Set through the BasisManager, the OilManager object provides access to the oils environment. Like changes made to the
objects accessed through the BasisManager, notification to the simulation environment is required when modifying assays or
blends. This is accomplished by calling the StartOilChange and EndOilChange methods. Calling the StartOilChange method
before calling the StartBasisChange method by default causes the StartBasisChange method to be invoked.

TIP
Assays and Blends are not estimated until the EndOilChange method is invoked.

Example: Accessing the Oil Manager Environment

Public usdOil As OilManager


[Link]
[Link]
Set usdOil = [Link]
'//code to manipulate oil manager objects
[Link]
[Link]

[Link] AssaysCollection & Assays

The AssaysCollection object is accessed through the OilManager object and contains the assay objects available within a
particular UniSim Design case. There are eight types of assays available and each of them has a specific set of properties
and methods. The properties associated with the hypocomponents generated by the OilManager can be accessed through
the Assay object.

TIP
AssayTypes:

l at_ASTMD2887 = 4
l at_BulkPropertiesOnly = 7
l at_Chromatograph = 5
l at_D1160 = 2
l at_D86 = 1
l at_D86D1160 = 3
l at_EFV = 6
l at_TBP = 0

Syntax: Assays

- 38 -
Chapter 2 - Automation

Referencing a Collection
Set usdAssays = [Link]
Referencing a Member
Set usdAssay = [Link](“name”)
Adding an Assay
[Link] “name”, AssayType

Below is an example on creating an assay.

Example: Creating Assays

Dim usdAssay As AssayTBP


Dim usdBasis As BasisManager
Set usdAssay = [Link](“AssayName”,
“TBP”)
With usdAssay
.Basis = ab_LiquidVolumeFraction
.BulkMolecularWeight = 300
.[Link] 783, “API” Dim
usdValue As Variant
Dim usdPercent As Variant
usdPercent = Array(0,10,20,30,40,50,60,70,80,90,98)
usdValue = Array(26.67,123.89,176.11,221.11,275
,335,399, 490.56,590.56,691.67,795.56)
.AssayPercentForBoilingTemperature = usdPercent
.BoilingTemperatureValue = usdValue
.Calculate
End With

[Link] Blend(s)

Blends are created through the BasisManager and can be completed by specifying at least one assay. Multiple assays can
be used in a blend as long as flow rates for each of the assays is specified. A large number of blend properties for the
hypocomponents created can be viewed.

Syntax for Blends

Referencing a Collection
Set usdBlends = [Link]
Referencing a Member
Set usdBlend = [Link](“blendname ”)
Adding Assay to Blend
[Link] “AssayName”
Installing to a ProcessStream
[Link] “StreamName”

The example below, creates a blend, assigns one assay to the blend, and then prints out the TBP values for the blend. The
blend is also assigned to a stream in the UniSim Design case.

Example: Blends

Dim usdBlend As Blend


'//create blend and assign assay
Set usdBlend = [Link](“BlendName”)
[Link] “AssayName”
'//print out some properties
Dim usdVar As Variant
usdvar = [Link]
For i = 0 To UBound(usdVar)

- 39 -
Chapter 2 - Automation

[Link] usdVar(i)
Next i
[Link] “Blend_Stream”

2.4.5 Stream Objects


The main objects of the stream category are the ProcessStream and Fluid objects. The Fluid object is a type of Stream
object that is not connected to operations but can be derived from a ProcessStream. The Fluid object can be manipulated
without effecting the operations and streams within the case. The ProcessStream object can be accessed from either the
flowsheet or the operation to which it is connected.

[Link] ProcessStream

The Streams object is a collection object returned by the flowsheet. The Streams collection contains one or more
ProcessStream objects. There are approximately 124 properties associated with the ProcessStream, including attributes
such as temperature, pressure, density, and viscosity. These properties return values of type Double. The ProcessStream
object also returns arrays as variants for properties such as ComponentMassFraction. The Fluid object contains a similar set
of properties and methods.

Syntax for accessing the ProcessStream object

By Name
[Link](“streamname”)
[Link](“stream name”)
By Index
[Link](j)

In most instances the collection object and member object of the collection have nearly similar names. The name of the
collection object is normally the member name with an “s” at the end. The Streams collection is an exception to this
statement, since it contains a collection of ProcessStream objects. The flowsheet returns three stream collections;
MaterialStreams, EnergyStreams, and Streams. All three stream collections accessed through the flowsheet are Streams
objects. The difference between the Streams collection objects relates to how the member ProcessStream objects are
filtered.

The example below, shows how to access a particular stream in the system by index and how to retrieve the temperature
value. The remaining properties are accessed in a similar fashion.

Example 1: ProcessStream

Dim usdFlowsheet As Object


Dim usdStream As Object
Set usdFlowsheet = [Link]
Set usdStream = [Link](0)
MsgBox “Stream Temperature = “ & usdStream.
TemperatureValue

The example below, shows how to access the MassFractionValue for each component in the stream. An array of doubles is
returned to the variant usdCompFrac. The Ubound function is used to determine the upper bound of the array and thus the
number of components. A separate object is set for the component collection. The indexing between the array of mass
fractions and the list of components in the FluidPackage is identical so it is easy enough to match the values with the
appropriate components.

Example 2: ProcessStream

- 40 -
Chapter 2 - Automation

Dim usdFlowsheet As Flowsheet


Dim usdStream As ProcessStream
Dim usdComponents As Components
Dim usdCompFrac As Variant
Set usdFlowsheet = [Link]
Set usdComponents = [Link](0).Components
Set usdStream = [Link](2)
usdCompFrac = [Link]
For j = 0 To UBound(usdCompFrac)
MsgBox “Component “ & [Link](j) & “ Mass
Fraction = “ & usdCompFrac(j)
Next j

[Link] Fluid

A Fluid object is derived from a single ProcessStream through the DuplicateFluid method. A Fluid object is essentially an
internal copy of the ProcessStream that can be manipulated for property calculation purposes. The ProcessStream and
Fluid share many of the same properties. A Fluid however can be flashed without interfering with the simulation case.

Syntax for creating a fluid

[Link](“streamname”).DuplicateFluid

The example below, shows how to create a Fluid off of a stream and use the Fluid to perform a flash calculation. The
DuplicateFluid method returns a Fluid object. A variety of flashes could have been performed, but in this case a pressure-
vapour fraction flash is run with the desired pressure and vapour fraction used as arguments to the method.

Example: Fluid

Public Sub FluidExample(pressureval As Double)


Dim usdFluid As Fluid
Dim usdStream As ProcessStream Set usdStream =
[Link](0)
Set usdFluid = [Link]
[Link] pressureval, 0
MsgBox “Bubble Point Temperature = “ &
[Link]
End Sub

[Link] FluidPhase(s)

The FluidPhases collection object is derived from the Fluid object. Each FluidPhase in the collection contains a set of
properties and methods that are similar to the Fluid itself except that the properties correspond to a specific phase of the
Fluid. The PhaseType property of the FluidPhase objects can be accessed to determine the type of phase.

- 41 -
Chapter 2 - Automation

TIP
PhaseTypes (constants):

l ptUnknownPhase
l ptCombinedLiquidPhase
l ptCombinedPhase
l ptLiquid2Phase
l ptLiquidPhase
l ptPolymerPhase
l ptSolidPhase
l ptVapourPhase

Syntax: FluidPhase(s)

Through Collection
Set usdFluidPhase = [Link](0)
HeavyLiquidPhase
Set usdFluidPhase = [Link]
LightLiquidPhase
Set usdFluidPhase = [Link]
VapourPhase
Set usdFluidPhase = [Link]

The example below, enumerates through the FluidPhases of a Fluid and displays the phase type for each fluid in a view.

Example: FluidPhase

Dim i As Integer
Dim usdCase As SimulationCase
Dim usdfluid As Fluid
Dim usdstream As ProcessStream
Dim usdPhase As FluidPhase
Dim usdPhases As FluidPhases
Set usdstream = [Link](0)
Set usdfluid = [Link]
Set usdPhases = [Link]
i = 1
For Each usdPhase In usdPhases
If [Link] = ptVapourPhase Then
MsgBox “Phase “ & i & “ is the vapour phase” i = i + 1
End If
Next

2.4.6 Operation Objects


A majority of the unit operations in UniSim Design are accessible as Automation objects. Operations can be accessed
through the flowsheet object. Each operation typically has a characteristic set of properties and methods.

[Link] Operations

All operations have a few properties and methods in common. Operation objects contain properties for determining the
feeds, products, and additional objects connected to the operation. The operation objects also contain methods for adding
and removing the operations from the flowsheet and the UniSim Design case.

Syntax for accessing operations

- 42 -
Chapter 2 - Automation

Getting all the operations on the flowsheet


[Link]
Getting a specific collection of operations
[Link](“PumpOp”)
Getting to a specific operation by name
[Link](“UnitName”)
Determining the type of operation
[Link](0).TaggedNam e

The Operations collection object obtained from the flowsheet returns a collection of all the operations on that flowsheet. It is
possible to filter the collection of operations returned by specifying the operation type. It is important to note however that the
operations object always returns a collection and not an individual operation. The objects in the collection need to be checked
in order to find a specific type of operation.

The example below, enumerates through all the operations on the flowsheet and displays the unit type in a view.

Example: Operation

Dim i As Integer
Dim usdOperations As Operations
Set usdOperations = [Link]
For i = 0 To [Link] - 1
MsgBox “Operation “ & [Link](i).name &
“ is unit type - & [Link](i).TypeName
Next i

[Link] ColumnOp & ColumnFlowsheet

The column operation is a special kind of operation in UniSim Design and actually contains its own flowsheet. The
ColumnFlowsheet is accessed either from the Columnop object or as a member of the flowsheets object accessed through
the main flowsheet. In order to access the various temperatures, pressures, and specifications for a column the
ColumnFlowsheet must be accessed.

Syntax: Accessing Columns

Set objColumn = [Link](“ColumnOp”).Item( 0)


Set objColumnSubFlow = [Link]

The ColumnFlowsheet object contains a considerable amount of information regarding the column. A variant is used to
receive an array of column pressure information and displays a stage by stage breakdown of the pressure values.

Example: Column Operation

Dim usdColumn As ColumnOp


Dim usdColumnSubFlowsheet As ColumnFlowsheet
Dim Pressure_Profile As Variant
Set usdColumn = [Link](“ColumnOp”).Item(0)
Set usdColumnSubFlowsheet = [Link]
Pressure_Profile = [Link]
For i = 0 To UBound(Pressure_Profile)
MsgBox “Stage “ & i + 1 & “ pressure = “ & Pressure_Profile(i)
Next i

- 43 -
Chapter 2 - Automation

[Link] ColumnSpecification(s)

A column is solved based on matching specifications related to the available degrees of freedom. The ColumnSpecifications
collection object is accessed through the ColumnFlowsheet. The ColumnSpecification contains information such as the goal
value, current value, and status.

Syntax: ColumnSpecification

Set usdColumn = [Link](“ColumnOp”).Item(0)


Set usdColumnFlowsheet = [Link]

By Index:
Set usdColumnSpec = [Link](0)

By name:
Set usdColumnSpec = [Link](“specname”)

The example below, enumerates through all the column specifications and displays in a view whether the specification is
active or an estimate.

Example: ColumnSpecification

Dim usdColumnSpec As ColumnSpecification


Dim usdColumnSpecs As ColumnSpecifications
Dim usdColumn As ColumnOp
Dim usdColumnFlowsheet As ColumnFlowsheet
Set usdColumn = [Link](“ColumnOp”).Item(1)
Set usdColumnFlowsheet = [Link]
Set usdColumnSpecs = [Link]
For Each usdColumnSpec In usdColumnSpecs
If [Link] Then
MsgBox “Column spec '" & usdColumnSpec
& “' is active.”
Else
MsgBox “Column spec '" & usdColumnSpec
& “' is an estimate.”
End If
Next usdColumnSpec

[Link] ColumnStage(s) & SeparationStage

The ColumnStages object is a collection of ColumnStage objects accessed through ColumnFlowsheet. SeparationStage is
an object of ColumnStage and provides a variety of properties related to the fluids residing on a particular column stage.

Syntax: ColumnStage(s)

By Index:
Set usdColumnStage = [Link](0)

By Name:
Set usdColumnStage = [Link](“1_Main TS”)

Syntax: SeparationStage
Set usdSepStage = [Link]

The example below, loops through each feed stage and displays in the Debug view its molar liquid flows.

Example: ColumnStage

- 44 -
Chapter 2 - Automation

Dim usdColumn As ColumnOp


Dim usdColumnFlowsheet As ColumnFlowsheet
Dim usdFeedStage As Object
Dim usdSepStage As SeparationStage
Set usdColumn = [Link](“ColumnOp”).Item(0)
With [Link]
For Each usdFeedStage In .FeedStages [Link]
“Stage “ &.ColumnStages([Link])
StageNumberValue & “ Molar Liquid Flow (kgmole/hr) is
“ &.ColumnStages([Link]).
[Link]
Next usdFeedStage
End With

2.4.7 Support Objects


Support objects are used primarily to perform a function or service to an object in UniSim Design. Support objects may not
have a visible equivalent in a UniSim Design case when viewed within the simulation environment. The support objects can
be accessed by several of the objects in UniSim Design. The two most commonly accessed objects in this category are
FixedAttachments and RealVariable.

[Link] RealVariable/RealFlexVariable

The RealVariable object provides additional information about a particular variable such as its units and whether it is
calculated or set. UniSim Design performs all calculations in SI units regardless of how the user preference settings are set.
By default, the values returned through Automation are also in SI units. It becomes your responsibility to handle how units
are handled when writing applications. A RealVariable contains a property called GetValue and SetValue which allows one
to specify the units that are to be used when returning or setting the value.

Syntax for using RealVariable

[Link](0).prop erty

RealVariable Properties/Methods

GetValue Gets the value in a specified unit.


SetValue Sets the value in a specified unit.
Status Returns calculated or specified
Value Value in SI units.

The RealVariable object also contains a property called Value. The Value property returns the actual value in SI units within
the UniSim Design case. Many of the objects that return a RealVariable for a given property also have a similarly named
property with the word value concatenated to it. The alternative property allows direct access to the actual variable in SI units
with one less function call. An example for the ProcessStream object would be the Temperature property that returns a
RealVariable and the TemperatureValue property, that returns a value in °C.

TIP
The presence of “Flex” in the object name indicates the possibility of a dynamic array (i.e., has a “variable” size,
depending on what is being returned.)

The RealFlexVariable contains roughly the same properties and methods as the RealVariable but is used for array values
returned to variants.

The example below, shows how to get a stream property value in a specific unit using the RealVariable method GetValue.

- 45 -
Chapter 2 - Automation

Example 1: RealVariable

Dim usdStream As ProcessStream


Dim TemperatureVal As Double
Set usdStream = [Link](0)
TemperatureVal = [Link](“F”)
MsgBox [Link] & “ temperature(F) = “ & TemperatureVal

The example below, shows how to set a stream property value in a specific unit using the RealVariable method SetValue.

Example 2: RealVariable

Dim usdStream As ProcessStream


Dim TemperatureVal As Double
Set usdStream = [Link](0)
TemperatureVal = 150
[Link] 150, “F”

The example below, checks how the temperature value of a stream is determined by examining the state property. The
constants vsCalculated, vsSpecified, and vsDefaultedValue are integer variables specified in the type library.

Example 3: RealVariable

Dim usdstream As ProcessStream


Set usdstream = [Link](0)
Select Case [Link]
Case vsCalculated
MsgBox “Temperature value is calculated.”
Case vsSpecified
MsgBox “Temperature value is specified.”
Case vsDefaultedValue
MsgBox “Temperature value is default.”
End Select

[Link] Fixed Attachments

The FixedAttachments object is a collection object accessed from Operations or Stream objects. The FixedAttachments
collection object contains a set of objects related to the feeds, products, or connected operations.

Syntax: Using FixedAttachments

Set FixAtch = [Link](0).


AttachedF eeds

Set usdStream = [Link](0)

Types of objects a FixedAttachments Collection

AttachedFeeds - ProcessStream
AttachedProducts - ProcessStream
AttachedLogicalOps - UnitOperation
AttachedOpers - UnitOperation

The example below, shows how to determine the streams attached to a specific unit operation. This example selects the first
column in the operations collection object and then sets an object to the attached feeds of the column. The names of the feed
streams to the column appear in a view.

- 46 -
Chapter 2 - Automation

Examples: FixedAttachments

Dim usdFeeds As FixedAttachments


Dim usdOp As ColumnOp
Set usdOp = [Link](“ColumnOp”).Item(0)
SetusdyFeeds = [Link]
For j = 0 To [Link] - 1
MsgBox “FeedStream “ & j & “ Name = “ & [Link](j).name
Next j

[Link] Solver & Integrator

The Solver is accessed from the SimulationCase object. The Solver object can be used to turn the calculations on and off.

Syntax for the Solver and Integrator

Solver
[Link] = False
[Link] = True
Integrator
[Link] = True
[Link] = False

When accessing UniSim Design through Automation it is important to note that UniSim Design does not allow
communication while it is solving. If information is sent to UniSim Design from a client application, UniSim Design does not
return control to the calling program until calculations are complete. If it is necessary to pass a large amount of information to
UniSim Design it is best to turn the solver off first and then turn it on once the information is sent. Otherwise, UniSim Design
calculates after each piece of information is sent and it takes much longer to transfer the data.

Example: Starting/Stopping the Solver

Dim usdstream As ProcessStream


Set usdstream = [Link](0)
[Link] = False
[Link] 100, “F”
[Link] 1, “atm”
[Link] 1000, “lb/hr”
[Link] = True

[Link] SpreadsheetOp & SpreadsheetCell(s)

The SpreadsheetCells object is a collection of SpreadsheetCell objects. The cell properties allow access to information
related to the UniSim Design variable being imported or exported, the formulas associated with the cell, and the value within
the cell.

Syntax: SpreadsheetOp and SpreadsheetCell(s)

Set usdSS = [Link](“spreadsheetname”)


Set usdCell = [Link](columnindex, rowindex)

By utilizing the spreadsheet operation, it is possible to access nearly every property or value in UniSim Design even if the
object associated with that property is not exposed as an Automation interface.

Example: Accessing Spreadsheet Cells

- 47 -
Chapter 2 - Automation

Dim usdSS As SpreadsheetOp


Dim usdCell As SpreadsheetCell
Set usdSS = [Link](“spreadsheetop”).Item(0)
Dim x As Variant, y As Variant
For i = 0 To 5
x = 1 ' col #
y = i ' row #
Set usdcell = [Link](x,y)
[Link] “CELL VALUE = “ & [Link]
[Link] “CELL FORMULA = “ & [Link]
[Link] “CELL PROPERTY = “ &
[Link] & “ (“ & [Link] & “)”
Next i

2.4.8 PFD Objects


PFD objects are used for the manipulation and automation of PFDItems. A PFDItem is any item that is found on the UniSim
Design PFD, such as a unit op or a stream. You can use PFD objects to Move, Size, Mirror, Rotate, Hide, etc. any PFDItem.
PFD objects also allow you to import and display a selection of PFDItems in to Visio, a CAD application or Excel (what items
you get depends on what parameters you specify). In addition to manipulating the PFD you can use the PFDConnection
object for such things as finding the “stream line” route between two PFDItems.

Example: Nozzle Type

If [Link] = pfdInletFromMaterialStream
Or
[Link] = pfdOutletToMaterialStream Or
[Link] = pfdInletFromStream Or
[Link] = pfdOutletToStream Then
[Link] = RGB(0, 0, 128)
[Link] = RGB(128, 128, 128)
ElseIf [Link] = pfdInletFromEnergyStream
Or
[Link] = pfdOutletToEnergyStream Then
[Link] = RGB(128, 0, 0)
[Link] = RGB(128, 128, 128)
ElseIf [Link] = pfdMaterialStreamInlet Or
[Link] = pfdMaterialStreamOutlet Then
[Link] = RGB(0, 0, 128)
[Link] = RGB(0, 0, 128)
[Link] = RGB(0, 0, 128)
ElseIf [Link] = pfdEnergyStreamInlet Or
[Link] = pfdEnergyStreamOutlet Then
[Link] = RGB(128, 0, 0)
[Link] = RGB(128, 0, 0)
[Link] = RGB(128, 0, 0)
Else
[Link] = RGB(0, 255, 0)
End If

2.5 Example 1: The Macro Language Editor


In this example, you use the UniSim Design Macro Language Editor to build a macro tool that displays the Mach number for
a selected stream over a number of different pipe sizes. The speed of sound in the stream fluid also appears. The fluid
velocity calculated for each pipe size is the average fluid velocity; no attempt is made to estimate the maximum velocity.

- 48 -
Chapter 2 - Automation

TIP
This complete example has also been pre-built and is located in the UniSim Design\Samples\OLE\ma cros\mach
directory.

1. Begin by opening UniSim Design and the Macro Language Editor which is found under the Tools menu.

Figure 2.7

2. Add a function that returns the Stream object that you choose from a list. Creating separate functions allows for easy
re-use in other programs.

Code Explanation

Function SelectStream(simcase As Object) As Object Signifies the


beginning of the
SelectStream
function. This
function takes a
SimulationCase
object and
prompts the user
to select a Stream
from a list of
streams in the
case, returning an
interface to the
Stream.

Acquire the case


Set FS = [Link] flowsheet.

Acquire the
Set Strms = [Link] collection of

- 49 -
Chapter 2 - Automation

Code Explanation

Streams from the


Dim strmnames() flowsheet.
strmnames = [Link]
Begin Dialog UserDialog 390,210,”Streams in “ +
Build a string
Right$([Link], Len([Link])-
Len([Link])) array of the
ListBox 20,35,350,119,strmnames(),.listsrc Stream names.
Text 20,14,360,14,”Select a Stream for Mach
number estimation:” Generate a user
OKButton 140,175,90,21
CancelButton 270,175,90,21 view containing a
End Dialog list of Streams
Please notice that
the first button
created
automatically
becomes the
default.
Use the
Language Help
option provided in
the Help menu to
explore the use of
UserDialogs.

Finally, run the


Dim dlg As UserDialog Dialog and
If Dialog(dlg) = 0 Then End
terminate the
macro if the user
cancels (i.e.,
Dialog function
returns 0).

Set the function's


return value to the
Set SelectStream = Strms([Link]) user selected
stream interface.

End Function Signifies the end


of the function.
This line does not
need to be added.

3. At this time it is probably a good idea to globally declare some constants that are used in the Main sub-routine as
shown below.

- 50 -
Chapter 2 - Automation

Figure 2.8

4. You can now begin defining the Main sub-routine. Enter the following code:

Code Explanation

Sub Main Signifies the


beginning main
sub-routine.

Defines an array
of pipe sizes (in
pipeSizes(1) = 2 inches).
pipeSizes(2) = 3
pipeSizes(3) = 4
pipeSizes(4) = 6
pipeSizes(5) = 8
pipeSizes(6) = 10
pipeSizes(7) = 12
pipeSizes(8) = 16

Looks for an
open active case.
Dim simcase As Object If there is no
Set simcase = ActiveCase active case, it
If simcase Is Nothing Then alerts the user
MsgBox “No UniSim Design case is open.”
End and terminates.
End If

Calls the
SelectStream
Dim strm As Object function to select
Set strm = SelectStream(simcase) a stream in the
simcase.

- 51 -
Chapter 2 - Automation

Code Explanation

Check to see if
the selected
Set flow = [Link] stream has a
If [Link] Then defined mass
flowValue = [Link](“lb/hr”) flow rate. If the
flowValue = flowValue / 3600
Else flow rate is
GoTo NoFlow known, convert
End If
the flow rate in to
“lb/s”.

Checks to see if
the stream’s
Set rho = [Link] mass density has
If [Link] Then been calculated.
rhoValue = [Link](“lb/ft3”)
Else
GoTo NoRho
End If

Calculates
volumetric flow
flowValue = flowValue / rhoValue rate.

Proceeds to an
error trap if the
On Error GoTo NoCv Cv value of the
Cv = [Link] / [Link] stream has not
been calculated.

Proceeds to an
error trap if the
On Error GoTo NoZ compressibility of
Z = [Link] the stream has
not been
calculated.

Proceeds to an
error trap if the
On Error GoTo NoTemp absolute
T = [Link] + 273.15 temperature of
the stream
cannot be
calculated.

Proceeds to an
error trap if the
On Error GoTo NoMolWt molecular weight
MolWt = [Link] / 1000.0 of the stream
cannot be
calculated.

- 52 -
Chapter 2 - Automation

Code Explanation
Calculates the
soundVel = Sqr(Z*R*T/MolWt*(1.0+Z*R/Cv)) Speed of Sound
soundVel = soundVel / 0.3048
soundVelTxt = Format(soundVel, “###,###,###.###”) of the stream and
Dim DispText() As String converts it from
ReDim DispText(nPipes + 2) m/s to ft/s.
DispText(0) = “Pipe Size (in) Mach
Number “
DispText(1) = “---------------------------------
Declares an
------------------------------” array of String
types. The “+2”
leaves room for a
two line header.
The two header
lines are
assigned.
Please note
there are
eighteen spaces
between “(in)”
and “Mach” and
four spaces after
“Number”. There
are
approximately
seventy dashes
in the line
DispText(1) = “--
-...”

For each pipe


size, the Mach
For num = 1 To nPipes number is
rSquared = pipeSizes(num) * pipeSizes(num)/ 144.0/4.0 calculated,
Mach = flowValue / pi / rSquared / soundVel formatted and
sizetxt = Format(pipeSizes(num), "###,###,###.###")
Machtxt = Format(Mach, "###,###,###.#####") stored in the
DispText(num + 1) = Format$(sizetxt, "@@@@@@@@@@@@@@@") + " " + previously
Format$(Machtxt, "@@@@@@@@@@@@@@@")
created array of
Next num
strings.
Please notice
that there are
eighteen spaces
between the
quotation marks
in the sixth line of
code (ninth line
displayed).

Create a user
view that displays
Begin Dialog UserDialog 360,217 the Speed of
ListBox 10,49,340,133,DispText(),.Field5 Sound value as
OKButton 250,189,90,21 well as the Mach
Text 30,14,150,14,"Speed of Sound (ft/s):",.Field2
number for each

- 53 -
Chapter 2 - Automation

Code Explanation

of the pipe sizes.


TextBox 190,14,90,21,.Field1
End Dialog Use the
Dim dlg2 As UserDialog Language Help
dlg2.Field1 = soundVelTxt option provided
Dialog dlg2
End in the Help menu
to explore the
use of
UserDialogs.

This is where you


define the error
NoFlow: trap instances.
MsgBox "Unknown mass flow in stream " + [Link]

End NoRho:
MsgBox "Unknown density in stream " + [Link]

End NoCv:
MsgBox "Unknown heat capacity in stream " + [Link]

End NoZ:
MsgBox "Unknown compressibility in stream " + [Link]

End NoTemp:
MsgBox "Unknown temperature in stream " + [Link]
End NoMolWt:
MsgBox "Unknown molecular weight in stream " + [Link]
End

End Sub Signifies the end


of the method.

5. Once you have finished adding this code, you should be ready to run the program. First ensure that UniSim Design
has a case loaded with at least one fully defined stream. You can start the program using one of the following ways:
l Right-click on any area of the Macro Language Editor view, select Macro | Run command from the Object
Inspect menu.

l Clicking the Start/Resume icon on the tool bar.

You should see a view similar to the one shown below:

- 54 -
Chapter 2 - Automation

Figure 2.9

6. Select a stream from the list and click the OK button. This should result in a view similar to the one shown below.

Figure 2.10

7. Be sure to save the program by doing one of the following:


l Right-click on any area of the Macro Language Editor view, select File | Save from the Object Inspect
menu.
l Press the CTRL S hot key combination.

l Clicking the Save icon in the tool bar.

2.6 Example 2: Automation in Visual Basic


In this example UniSim Design is used as the Automation server for a unit conversion program. More specifically, you are
accessing an object called the UnitConversionManager which manages unit conversion within UniSim Design.

TIP
This complete example has also been pre-built and is located in the UniSim Design\Samples\OLE\vb\ ucsm directory.

NOTE
Although Visual Basic 6.0 is recommended for this example, you can create this Automation application in Visual Basic
Editor provided in MS Excel 97® and MS Word 97®.

- 55 -
Chapter 2 - Automation

1. Open a new project in Visual Basic 6.0® and from the New tab of the New Project view select the Standard EXE

icon and click the Open button.


Your screen should appear similar to the figure below.

Figure 2.11

2. By default you should have a form associated with the project. Begin, by giving the form a name. In the Name field of
the Properties tiled view give the form the name: frmUCSM.
3. In the Caption field type: UNIT CONVERSION MANAGER. This caption should now appear in the Title Bar of
the form.
4. Before adding objects to the form, resize the view to accommodate the different objects that are required. In the
Width field found in the Properties tiled view change the width of the form to 12600 or so that the form is sufficiently
wide enough to contain all the objects you are adding (see figure after step 11).

5. From the toolbox select the Combo Box icon and create a combo box on the form as shown below.

Figure 2.12

6. Ensure that the combo box is the active control. This can be done in one of two ways:
l Select the combo box on the form so that the object guides appear around the object.
l From the drop-down list found at the top of the Properties tiled view select the name of the combo box you
have just created.

- 56 -
Chapter 2 - Automation

7. In Properties tiled view, set the name of the Combo Box as ddUnitSet in the Name field. If you want, you can also
change the default text that appears inside the combo box by entering a new name in the Text field.

8. You can add a Label to the form (i.e., to identify the object from others), by clicking the Label icon and drawing a
label on the form just above the combo box you have just created.

Figure 2.13

9. Ensuring that the Label control is active using one of the methods suggested in #6, go to Properties tiled view and
change the text in the Caption field to Unit Conversion Set.
10. Now add an Text Box next to the Combo Box you created. Use the method described in Steps #6 - #7 to name this
Text Box ebFromValue. Repeat Steps #8 - #9 to add a Label above the ebFromValue Text Box that reads From
Value.

Figure 2.14

11. Add the following objects to the view using the previously described methods.

Figure 2.15

12. Only two more objects are required on the form. Select the Command icon control from the toolbox and add
two buttons to the view as shown below.

- 57 -
Chapter 2 - Automation

Figure 2.16

13. You are now ready to begin defining the events behind the form and objects. You can enter the code environment
using a number of methods:

l Click the View Code icon in the Project tiled view.


l Select the Code command from the View menu.
l Double-click the frmUCSM form.
The following view should appear:

Figure 2.17

- 58 -
Chapter 2 - Automation

TIP
The Private Sub Form_Load() method definition is only visible if you enter the code environment by double-
clicking the form.

14. Begin by declaring the following variables under the Option Explicit declaration.

Figure 2.18

TIP
If you attempt to use an undeclared variable, an error occurs at compile time.

15. The first sub-routine should already be declared. The Form_Load sub-routine is the first sub-routine called once the
program is run. It is usually used to initialize the variables and objects used by the program. Enter the following code
in to the Form_Load sub-routine.

Code Explanation

Private Sub Form_Load() Signifies the Start of the form load sub-
routine. You do not have to add it as it
should already be there.

Clear the default text found inside the


ddUnitSet, ddFromUnit and ddToUnit
[Link] combo boxes.
[Link]
[Link]

Connects to UniSim Design and the


UniSim Design Unit Conversion Set
Set usdApp = CreateObject("[Link]") Manager.

- 59 -
Chapter 2 - Automation

Code Explanation

Set UCSM = [Link]

For each Unit Conversion Set found in the


Unit Conversion Set Manager add the Unit
For Each UCS In UCSM Set to ddUnitSet combo box list.
[Link] [Link]
Next UCS

Indicates no item is currently selected in


the ddUnitSet combo box.
[Link] = -1

Clears the text that appears in the


ebFromValue text box and the
[Link] = "" lbToValue label.
[Link] = ""

End Sub Signifies the end of the initialization sub-


routine. This line does not need to be
added.

16. The next section of code to be added tells the program what is to occur when an option is selected in the ddUnitSet
combo box.

Code Explanation

Private Sub ddUnitSet_Click() Signifies the Start of the sub-routine.

Clears any list entries in the ddFromUnit


and ddToUnit combo boxes.
[Link]
[Link]

Connects to UniSim Design and the


UniSim Design Unit Conversion Set
Set usdApp = CreateObject("[Link]") Manager.
Set UCSM = [Link]

Once the selection is made in the


ddUnitSet combo box, the UCSNumber
UCSNumber = [Link] variable holds the internal UniSim Design
index number of the selected Unit Set.

Find the selected Unit Conversion Set in


Unit Conversion Manager.
Set UCS = [Link](UCSNumber)

- 60 -
Chapter 2 - Automation

Code Explanation
For each Unit Conversion type (UC) in the
Unit Conversion Set, add the Unit type to
For Each UC In UCS both the ddFromUnit combo box (the unit
[Link] [Link] type the program is converting from) and
[Link] [Link] the ddToUnit (the unit type the program is
Next UC
converting to).

Indicates no items are currently selected in


the ddFromUnit and ddToUnit combo
[Link] = -1 box.
[Link] = -1

Clears any text that appears in the


lbToValue label.
[Link] = ""

End Sub Signifies the end of the sub-routine. This


line does not need to be added.

17. The next 2 sub-routines reset the lbToValue label whenever an option is selected in either the ddFromUnit or
ddToUnit combo box.

Code Explanation

Private Sub ddFromUnit_Click() Signifies the Start of the sub-routine.

Clears any text that appears in the lbToValue label.

[Link] = ""

End Sub Signifies the end of the sub-routine. This line does not
need to be added.

Code Explanation

Private Sub ddToUnit_Click() Signifies the Start of the sub-routine.

Clears any text that appears in the lbToValue label.

[Link] = ""

End Sub Signifies the end of the sub-routine. This line does not
need to be added.

18. The final two sub-routines define the actions of the two buttons:
btConvert and btExit.

- 61 -
Chapter 2 - Automation

Code Explanation

Private Sub btConvert_Click() Signifies the Start of the sub-routine.

Connects to UniSim Design and the


UniSim Design Unit Conversion Set
Set usdApp = CreateObject("[Link]") Manager.
Set UCSM = [Link]

Takes the value entered in the


ebFromValue text box and converts in to
FromValue = CDbl(Val([Link])) a numerical variable type.

Set ebFromValue text box text equal to


FromValue double.
[Link] = CStr(FromValue)

Gets current selection in the three drop-


down lists (combo boxes).
UCSNumber = [Link]
FromNumber = [Link]
ToNumber = [Link]

If no selection is made in either the


ddFromUnit or ddToUnit combo boxes,
If FromNumber < 0 Or ToNumber < 0 Then exit the sub-routine.
[Link] = ""
Exit Sub
End If

Chooses a specific UCS from UCSM. It


takes the Unit conversion type you want to
Set UCS = [Link](UCSNumber) change from, and the Unit Conversion type
Set FromUC = [Link](FromNumber) you want to change to.
Set ToUC = [Link](ToNumber)

Converts the contents of the


ddFromValue combo box from the
Intermediate = [Link](FromValue) FromUC units to UniSim Design internal
ToValue = [Link](Intermediate) units (Intermediate). It then converts the
[Link] = CStr(ToValue) Intermediate value from internal units to
the ToUC units. It then displays the
converted value in the lbToValue label.

End Sub Signifies the end of the sub-routine. This


line does not need to be added.

- 62 -
Chapter 2 - Automation

Code Explanation

Private Sub btExit_Click() Signifies the Start of the sub-routine.

Unloads the form and ends the program.

Unload Me
End

End Sub Signifies the end of the sub-routine. This line does not
need to be added.

19. You are now ready to compile and run the program. Before you begin, please ensure that you have a copy of UniSim
Design on the computer.
20. To compile the program do one of the following:

l Click the Start icon in the toolbar.


l Select Start command from the Run menu.
l Press F5 from the keyboard.

VB informs you of any errors that occur during compile time.

- 63 -
CHAPTER

3 EXTENSIBILITY

3.1 Introduction
UniSim Design provides the unique capability of enhancing its functionality through the addition of custom objects to a
simulation. With its open concept, the functionality of UniSim Design can be extended to include your unique or proprietary
calculations. Currently, you can add:

l Extension Unit Operations


l Extension Reaction Kinetics
l Extension Property Packages

Extensions are packaged in to two distinct files making them easy to transfer to different machines. The extension code
becomes part of a DLL (dynamic linked library), that hides its proprietary information, making it an excellent vehicle for
commercial distribution. Extensions become part of the simulation and participate in simulation calculations like any other
UniSim Design object. For example, each extension unit operation has a corresponding PFD icon and property view. Also,
the Extension has its Execute method called by the Steady-State Solver. Unlike applications which interact with UniSim
Design through Automation, extensions exist in process with the UniSim Design applications. New extensions can be written
in any language that supports Automation (formerly OLE Automation). This provides much flexibility to the end user, who can
develop the extension in languages such as C++ or Visual Basic. By its very nature, Visual Basic provides the easiest
development environment in which to create unit operation and kinetic reaction extensions. The Extension Property Package
interface must be implemented as a custom interface, therefore C++ must be used.

Each type of extension is represented in UniSim Design by an Extension Container. This object is the gateway through which
UniSim Design communicates with the extension. The Container can also provide a number of services to the extension,
such as performing Mass Balances or allowing access to the Status Bar.

Figure 3.1

UniSim Design finds extensions by looking for specific keys in the System Registry. When an extension is registered on a
computer, information about it is added to the Registry. Upon start-up, UniSim Design scans the Registry for this information,
and adds user-specified descriptions to the appropriate lists within the program. For instance, when a unit operation
extension is created with the description provided as “MY Unit Op”. This text appears in the UniSim Design UnitOp view in
the Available Unit Operations pane so that the user can create instances of them.

When the user asks for an extension to be created, UniSim Design instantiates the object and calls its Initialize method. At
this point, the extension code gains access to its Container. After the extension has been initialized, it behaves like any other
UniSim Design object of the same class.

All extensions must support at least two interfaces:

- 64 -
Chapter 3 - Extensibility

l The ExtensionObject interface


l At least one other interface particular to the type of extension

Containers support one interface, which is particular to the type of container.

3.2 Implementing Interfaces


An extension implements an interface if it supports the methods in that interface. There are two different ways of
implementing an interface.

3.2.1 Implementing an Interface Through a Dispatch Interface


An extension can implement interfaces through Dispatch interfaces. This can be done in Visual Basic if the extension is
implemented as a Visual Basic Class.

When an extension is implemented in this manner, only the methods of the interface that are required for minimal operation
of the extension need be used. All other methods may be ignored, or they can be provided if the extension implements that
functionality.

For example, an extension Unit Operation can be implemented by supporting only the Initialize and Execute methods. The
BasisChanged method need only be implemented if the extension needs to be notified when the Basis of the simulation has
changed.

3.2.2 Implementing an Interface Through a Custom Interface


An extension can also be implemented by overloading the Custom interfaces defined for the extension. For example, an
extension Unit Operation can be created by overloading the ExtensionObject interface and the ExtnUnitOperation interface.

When an extension is created in this manner, all methods of the interface must be overloaded (this is a requirement of the
C++ language definition). If a method does not contain any functionality, however, the error condition E_NOTIMPL should
be returned to indicate to UniSim Design that the method is not being used. Using the Extension Unit Operation as an
example once again; each of the methods in its two supported interfaces must be overloaded, but only the Initialize and
Execute methods need return anything other than E_NOTIMPL.

3.3 Data Types


This documentation for the most part uses Visual Basic syntax in its sample code and examples. The following table provides
a map of Visual Basic types to C++ types, for those that choose create extensions in C++.

Visual Basic Type C++ Type

Variant VARIANT

String BSTR

Boolean VARIANT_BOOL

Long long

Integer short

Double double

Single float

arrays SAFEARRAY

- 65 -
Chapter 3 - Extensibility

TIP
When sending an array of numbers to UniSim Design they should always be of type REAL or LONG.

3.4 Extension Development Kit


A number of tools are provided in the UniSim Design Extension Development Kit. These tools are not required to build
extensions for UniSim Design, but they make the job much easier. Included in the kit are the following:

File Description

[Link] The UniSim Design Type Library, that contains definitions for all objects exposed by UniSim
Design, as well as definitions for interfaces required by UniSim Design Extensions.
Programming languages such as Visual Basic use this file to determine what a particular
object contains. Many programs provide browsers to look at the contents of this file. For
example, Excel provides an Object Browser that can be used to view the properties of
methods of each object and to help navigate the object model. Unlike the other files in the
table, the UniSim Design Type Library is always installed, even when you do not install the
Extension Development Kit.

[Link] Contains constants defined by UniSim Design in a format that can easily be included in a
Visual Basic project. This allows the extension developer to refer to UniSim Design constants
through Const definitions, rather than through numbers. This information can also be read
from the UniSim Design Type Library, if your programming language supports this.

[Link] and Contain support code that can be included in a C++ project. They implement a ClassFactory
[Link] for any extensions in the project and also implement the DllRegisterServer and
DllUnregisterServer methods. These files compile in both Microsoft Visual C++ and Borland
C++.

[Link] Contains definitions of all the interfaces and enumerations found in the UniSim Design Type
Library. Including this file in your C++ source allows you to call methods on UniSim Design
interfaces.

[Link] Instantiates all of the GUIDs defined by UniSim Design. It can be included as part of a C++
project to allow reference to UniSim Design GUIDs.

The UniSim Design Allows you to:


View Editor
l Define extension information for the registration program.
l Define Variables for UniSim Design to create and manage on behalf of an extension.
l Create Views for an extension.

3.5 Creating an Extension


3.5.1 In Visual Basic
Creating an extension in Visual Basic is a very straightforward procedure. The following six steps can be used as a general
framework:

1. Create the Extension Definition.


2. Create the Object views.
3. Implement the Required Methods.
4. Register the Extension.

- 66 -
Chapter 3 - Extensibility

5. Debug the Extension.


6. Distribute the Extension.

These steps are explained in more detail in the following sections.

Class Definition required to create Dynamic extensions in C# .NET

Extensions created using .NET should follow the directions for VB, including deriving from VBExtnDynUnitOp when creating
a dynamic unitop extension.

For example use

public class MyClass: ExtnUnitOperation, ExtensionObject, VBExtnDynUnitOp

instead of

public class MyClass: ExtnUnitOperation, ExtensionObject, ExtnDynUnitOp

Only native (i.e. ‘unmanaged’) C++ extensions should use the ExtnDynUnitOp interface, since they can tolerate running on a
different thread to UniSim Design, whereas C# extensions in .NET cannot.

[Link] Create the Extension Definition

The EDF contains important information about an extension that is required by the extension's container in UniSim Design.
Specifically, it contains information about the variables that the extension own (that are managed by the container), and it
can also contain one or more Views for the object.

TIP
The extension definition file, which contains the definition of the extension is created using the View Editor.

For each extension, you must provide either a CLSID or a ProgID. Other information that can be provided at this point
includes: the extension description, from which you identify the extension within UniSim Design, the extension type and the
number of views. For extensions written in Visual Basic, you must specify a ProgID. The selection of the ProgID is explained
in the following sub-section entitled:Register the Extension.

TIP
It is possible to create an EDF with 0 views.

Once the preliminary definition information is provided, you specify the variables that the object owns and that are visible to
the user. These variables are of the following types:

Variable
Description
Type

Numeric l Represent numerical quantities and have a Variable Type that allows UniSim Design to manage Unit
Conversions for the user.
l May have zero, one, or two dimensions.
l Can also trigger the steady state solver when they are changed. If this is the case, the variable operates
like other UniSim Design variables in that the solver performs consistency checking when values are
changed. For a Dynamic Extension, the TriggerSolve will mean the variable is dynamic and will be

- 67 -
Chapter 3 - Extensibility

Variable
Description
Type

initialized when invoked via the Initialize From functionality. NoTriggerSolve means the variable is
"static/geometric" and will not be initialized.

Text l Represents a string.


l May be zero- or one-dimensional.

Message Usually associated with buttons in a view. Messages are sent through the VariableChanged method of an
extension.

TIP
For more information on the View Editor see Extension Editor.

Numeric Variables and Text Variables may or may not be persistent. If they are, their values are stored when the Simulation
Case containing the extension is saved.

[Link] Create the Object View(s)

A view for your extension is not necessary, but quite often you want the user to be able to interact with your object. The View
Editor can be used to create views for your object.

Views are created by adding widgets to the DefaultView form. Select a widget with the secondary mouse button, drag it on to
the DefaultView form, and drop it. You can then position the widget to your liking. Double-click the widget to access its
Properties view, from which you can specify detailed information for the widget. If necessary, you can associate a variable
with the widget.

TIP
A widget is an equivalent term for a Visual Basic control.

Each DefaultView form must have a unique name. The object’s default view must be called DefaultView as it is the view
UniSim Design attempts to open when the object is instantiated, provided the functionality of the OnView method is not
overridden.

[Link] Implement the Required Methods

To implement an extension from Visual Basic, you must create a project containing a Class Module. This Class Module must
implement whatever methods are required by the container. For example, to implement an Extension Unit Operation, you
must implement an Initialize method and an Execute method, and these methods must have the same parameters as
defined by the interface.

[Link] Register the Extension

Before you register your extension, you must ensure that the ProgID defined by your Visual Basic project is the same as that
which you entered in the EDF for this object. ProgIDs are defined by Visual Basic in the following form:

[Link]

where:

ProjectName = the name of the project (which is set on the Projecttab of the Options view in VB 5.0) ClassName = the
name of the class (which is set through the Name parameter of the class' property view).

- 68 -
Chapter 3 - Extensibility

For Example, a class called Extension1 in a project called HoneywellExtensionProject would have a ProgID of
HoneywellExtensionProject.Extension1.

TIP
For more information on extension registration see Registering Extensions.

You can register extensions on the Extensions tab of the Session Preferences property view.

[Link] Debug the Extension

To debug the extension, you can set breakpoints on just about any line in your Visual Basic class. Initially, you should
probably set a breakpoint on the Initialize method. Then, start the extension (via the Start button or the Start command in the
Run menu).

TIP
For more information on debugging, please consult your Visual Basic manual and help files.

Next, start UniSim Design and create an instance of your extension. This is done in the same manner as you would create
other objects of the same class. For example, extension Unit Operations can be created through the UnitOps view (accessed
though the F12 key).

When you create an instance of your extension, UniSim Design creates a container for it. This container first creates an
instance of your Visual Basic class, and then calls its Initialize method. At this point, your breakpoint in Visual Basic should be
reached. Now you can inspect variables and step through your code.

You can also use the Debug object in Visual Basic to print information to the Debug view while the extension runs.

[Link] Distribute the Extension

Once you are confident that your extension is behaving properly, you can create an ActiveX DLL file. Create the DLL file by
selecting the appropriate option from Visual Basic’s File menu. The end result of this step is an extension that you can
distribute without exposing any proprietary information or methods.

To distribute your extension, you must provide the DLL file, the EDF file, and any other files required by your extension (i.e., a
separate FORTRAN DLL called from your extension). You must register your extension on each individual machine that
uses the extension calculations. You can use the registration tool found on the Extensions tab of the Session Preferences
property view for this, or you can include this step in your own setup program.

3.5.2 In C++
The following six steps provide a framework for creating an extension in C++:

1. Create the Extension Definition.


2. Implement the Required Interfaces.
3. Implement the ClassFactory.
4. Create and Register the DLL.
5. Debug the Extension.
6. Distribute the Extension.

These steps are explained in more detail in the following sections.

- 69 -
Chapter 3 - Extensibility

TIP
For more information refer to In Visual Basic.

[Link] Create the Extension Definition

The EDF contains important information about an extension that is required by the extension's container in UniSim Design.
Specifically, it contains information about the variables that the extension own (that are managed by the container), and it
may also contain one or more Views for the object.

TIP
The extension definition file, which contains the definition of the extension is created using the View Editor.

For each extension, you must provide either a CLSID or a ProgID. Other information that can be provided at this point
includes: the extension description, from which you identify the extension within UniSim Design, the extension type and the
number of views. The selection of the ProgID is explained in the following sub-section entitled: Register the Extension.

TIP
It is possible to create an EDF with 0 views.

Once the preliminary definition information is provided, you specify the variables that the object owns and that is visible to the
user. These variables are of the following types:

TIP
For more information on the View Editor see Extension View Editor.

Variable
Description
Type

Numeric l Represent numerical quantities and have a Variable Type that allows UniSim Design to manage Unit
Conversions for the user.
l May have zero, one, or two dimensions.
l Can also trigger the steady state solver when they are changed. If this is the case, the variable operates
like other UniSim Design variables in that the solver performs consistency checking when values are
changed.

Text l Represents a string.


l May be zero- or one-dimensional.

Message Usually associated with buttons in a view. Messages are sent through the VariableChanged method of an
extension.

Numeric Variables and Text Variables may or may not be persistent. If they are, their values are stored when the Simulation
Case containing the extension is saved.

- 70 -
Chapter 3 - Extensibility

[Link] Implement the Required Interfaces

To create an extension in C++, you must create a class that implements the required interfaces. For example, an Extension
Unit Operation must implement the ExtensionObject interface and the ExtensionUnitOperation interface. This calculation
can be done through inheritance or aggregation. UniSim Design functions if either approach is taken, as long as the
interfaces are supported through the COM QueryInterface mechanism.

To implement an extension, you must provide code for the standard COM IUnknown methods (AddRef, Release,
QueryInterface), as well as any methods required by the interfaces you are supporting. Other methods may return E_
NOTIMPL if you choose not to implement them.

Definitions of the interfaces that you must implement (as well as any interfaces provided by UniSim Design objects) are
provided in the [Link] file, that is included in the Extension Development Kit. You must include this file in any
source files that access the defined interfaces.

[Link] Implement the Class Factory

When UniSim Design creates an instance of your extension object, it accesses the COM Library which calls the function
DllGetClassObject

which is contained in the DLL. DllGetObject creates the requested class factory. You can implement a ClassFactory yourself,
or you can use the one provided in [Link] (which is included in the Extension Development Kit).

If you choose to use the ClassFactory provided by [Link], you must implement the REGISTER_EXTENSION macro
somewhere in your code. This macro provides information to the ClassFactory on how to create an instance of your
extension. The syntax of this macro is:

REGISTER_EXTENSION(ClassName, clsid, VisibleDescription)

where:

ClassName = the C++ name of the class clsid = the CLSID of the class VisibleDescription= a string containing a description
of the class that a user can understand

You must implement this macro once for every extension in your DLL.

[Link] Create & Register the DLL

When you build your project, you must implement it as a 32-bit Dynamic Link Library (DLL). This DLL must contain code for
your extension, a ClassFactory to create your extensions, and a DllRegisterServer entry point.

The Extension Development Kit provides [Link], which contains a ClassFactory and an implementation of
DllRegisterServer. If you use this ClassFactory, you must include this file in your project.

You can register your DLL on the Extensions tab of the Session Preferences property view.

TIP
For more information on extension registration see Registering Extensions.

[Link] Debug the Extension

You can debug your extension by putting a call to the Win32 function DebugBreak in your code. When UniSim Design
executes this part of your code, you are allowed to start your debugger and debug the code from there. You are then able to
inspect variables, and trace the execution of your extension's code. You can also debug your extension in MS DevStudio by
setting breakpoints in the code. Specifying the path of the UniSim Design executable file in the Executable for debug session
field on the Debug tab of the Project Settings view and launch VC++ auto debug.

- 71 -
Chapter 3 - Extensibility

You can load your extension by starting UniSim Design and creating an instance of the extension. UniSim Design creates a
container, and this container then calls the extension's Initialize method.

[Link] Distribute the Extension

Once you are confident that your extension is behaving properly, you can create an ActiveX DLL file. The end result of this
step is an extension that you can distribute without exposing any proprietary information or methods.

To distribute your extension, you must provide the DLL file, the EDF file, and any other files required by your extension (i.e., a
separate FORTRAN DLL called from you extension). You must register your extension on each individual machine that uses
the extension calculations. You can use the registration tool found on the Extensions tab of the Session Preferences
property view for this, or you can include this step in your own setup program.

3.6 Registering Extensions


In order for UniSim Design to find extensions, they must be registered in the Extensions tab of the Session Preference view.
UniSim Design looks for extensions in the:

HKEY_CLASSES_ROOT\Software\Honeywell\UniSimDesign\1.1\Extension s key.

Each extension should have the following information under this key:

KeyName = Descriptive Name of Extension


ExtensionDefinitionFile = name of Extension Definition File
ExtensionType = type, class
CLSID = CLSID of Extension or
ProgID = ProgID of Extension

All this information is provided when the EDF is created in the View Editor.

TIP
See Extension View Editor for more information on creating an EDF.

Extensions can be registered with either a CLSID (Class Identifier) or a ProgID (Program Identifier). It is recommended that
ProgID be used for extensions created in Visual Basic, and CLSID be used for all other extensions.

TIP
Only one of the ProgID or CLSID values can be used.

The Extension Definition File entry gives the name of the Extension

Definition File for the object.

The type of the extension is given by the ExtensionType entry. The type can be UnitOperation, PropertyPackage or
KineticReaction. The class descriptor is optional, and currently is ignored if present.

3.6.1 Registering Extensions Written in C++


When you create an extension in C++, you must implement a DllRegisterServer function in the DLL containing the
extension. This function is called from UniSim Design when registering the extension. The file [Link] that is included
with the Extension Development Kit provides code that implements this function.

To register an extension written in C++, simply use the following procedure:

- 72 -
Chapter 3 - Extensibility

1. Start UniSim Design. From the Tools menu, select Preferences command. The Session Preferences view opens.
2. Go to the Extensions tab and click the Register an Extension button. This opens the Select an Extension to
be Registered view.
3. Use the File Path group to find the directory in which the DLL file is saved. Once you find the DLL file, select it and
click the OK button.

Figure 3.2

The Extensions tab should now appear similar to the figure below.

- 73 -
Chapter 3 - Extensibility

Figure 3.3

You are now ready to use the extension in UniSim Design.

TIP
Ensure that the EDF and extension DLL are in the same directory.

3.6.2 Registering Extensions Written in Visual Basic


Extensions written in Visual Basic may be run from within Visual Basic, or may be compiled to an ActiveX DLL file. Either
way, Visual Basic takes care of registering half of the information required for UniSim Design to find the extension. The
UniSim Design registration tool provided in the Session Preferences property view may be used to register the other half.

TIP
Refer to Registering Extensions Written in C++, for the step by step procedure for registering UniSim Design
extensions.

[Link] Running Within Visual Basic

If you are running your extension within the Visual Basic environment, Visual Basic temporarily adds information to the
registry every time the project is run. This information changes every time you run the project. The extra information needed
can be added by going to the Extensions tab of the Session Preferences property view and registering the EDF file. When
run this way, information about where to find an extension is added to the registry, but information on how to create it is not.

TIP
To view EDF files in Select an Extension to be Registered view, you must change the settings in the File Filter drop-
down list from Application Extensions (*.dll) to Extension Definition Files (*.edf).

[Link] Compiled DLL Files

When you compile your extension to an ActiveX DLL file, you must do both parts of the registration. You can use the
procedure described in the Registering Extensions Written in C++ to register the DLL files in the UniSim Design
Session Preferences.

UniSim Design loads the DLL file and registers it, and then it takes the name of the DLL file and looks for an Extension
Definition File with the same name in the same directory to complete the registration.

3.7 Extension Interface Details


Three types of extensions can currently be created for use within UniSim Design:

l Unit Operations
l Kinetic Reactions
l Property Packages

Each extension type is associated with a unique container interface derived from the ExtnContainer object. For instance Unit
Operation Extensions have an ExtnUnitOperation interface.

- 74 -
Chapter 3 - Extensibility

3.7.1 ExtnContainer Interface


Each type of extension has a unique container associated with it. Each container implements an interface that provides
methods and properties for the extension.

Derived from Properties Methods

IDispatch ExtensionInterface ClearStatusBar

FPStatus FindVariable

OnOleEnabledThread OpenContainerStorage

SimulationCase OpenView

StatusBar Trace

WaitForTurn

3.7.2 ExtensionObject Interface


Every extension must implement the ExtensionObject interface. This interface defines methods that are common to all
UniSim Design extensions. No methods in this interface are mandatory; that is, all methods may be ignored if the extension
does not implement them.

Derived from Properties Methods

IDispatch none OnHelp

Save

StatusQuery

Terminate

VariableChanged

VariableChanging

3.8 Extension Reaction Kinetics


You can add your own Reaction Kinetics expressions to UniSim Design though the Reaction Kinetics Extension. These
extensions appear to the user like any other UniSim Design reaction type. Additionally, you can specify which components
partake in the expression, as well as define new properties for the reactants.

To implement an extension Kinetic Reaction, you must implement two interfaces.

Interface Description

ExtensionObject Called when reaction extension is added to the simulation.

ExtnKineticReaction Called when the reaction extension is used.

The container for the extension supports the ExtnKineticReactionContainer interface. This acts as the interface to all the
widgets and variables in the UniSim Design standard kinetic reaction view.

These previously described interfaces allow a reaction to be implemented and associated with a UniSim Design case
through a fluid package. The Reaction Extension also requires the definition of two methods in order for the extension to be
viable:

- 75 -
Chapter 3 - Extensibility

Method Description Details

Initialize The Initialize method is called whenever the extension is first added or ByVal Container as
whenever a case containing the extension is reopened. This is also the ExtnUnitOperationContainer
procedure where you would usually set the state of the properties and The kinetic reaction container
define the reactants used. object.

ByVal IsRecalling as Boolean


Value related to the state of the
extension. False if created for the
first time. True if there is an
existing extension.

Initialize as Long (Return


Value)
Return value must be the current
UniSim Design build. A constant
extnCurrentVersion is provided in
the type library for this purpose.

Reaction Called when the reaction extension is used. The method is a function ByVal usdFluid as Fluid
Rate that returns true when successful and false if an error occurs. The Fluid based on the input stream
calculation involves returning a rate value through the ‘Rate’ argument to the operation.
while the UniSim Design solver iteratively calls the ReactionRate
ByVal RxnTemperatureInC as
method.
Double
Reaction Temperature in UniSim
Design internal units of Celsius.

ByVal
RxnVolumeInKmolPerM3 as
Double
Reaction volume in UniSim
Design internal units of cubic
meters.

Rate as Double
Rate value, passed by reference,
so its value can manipulated and
permanently altered within the
method.

ReactionRate as Boolean
True if rate could be calculated,
False if there is an error.

3.8.1 Extension Definition Files


An extension definition file is required for the kinetic reaction extension. Since UniSim Design uses a specific interface for
reaction extensions, the view within the EDF is not the primary view when the extension is accessed in UniSim Design. If you
do create a customized view in the View Editor, you can access it through the View Extension Parameters button found on
the Parameters tab.

- 76 -
Chapter 3 - Extensibility

Figure 3.4

3.8.2 ExtnKineticReaction Interface


The ExtnKineticReaction interface must be implemented by all extension kinetic reactions. In addition to the Initialize and
Reaction Rate methods which are mandatory, the interface also has the following associated properties and methods:

Derived from Properties Methods

IUnknown IsReady BasisChanged

ReactionRate2

3.8.3 ExtnKineticReactionContain er Interface


The ExtnKineticReactionContainer interface is passed to an extension Kinetic Reaction in its Initialize method.

ExtnContainer Properties Methods

ExtnContainer l BaseReactant l AddReactantProperty


l BasisConversion l RemoveReactantProperty
l MaxTemperature l SetReactionPropertyState
l MinTemperature
l Phase
l RateConversion
l Reactants
l ReactionBasis

3.8.4 Kinetic Reaction Example


In this example, you use Visual Basic 5.0 to build a reaction kinetics extension for a reaction involving vinyl acetate.

1. Create a new project in Visual Basic 5.0 from the New tab of the New Project view. Select the [Link] icon

as the project type and click the Open button.


2. Make sure that the UniSim Design 3.* Type Library is checked in the References view, which is accessed by
selecting the References command from the Project menu.

- 77 -
Chapter 3 - Extensibility

Figure 3.5

3. In the Properties tiled view, ensure that the Instancing drop-down list is set to 5-MultiUse.

Figure 3.6

4. In the Properties tiled view, rename the class module VinylAc.


5. Save the class and project by selecting Save Project command from the File menu. Save the class and project as
[Link] and [Link]
6. You are now ready to define the class. Begin by defining the global variables in the Project VinylAc Code view:

Code Explanation

Option Explicit Used to force explicit declaration of all variables in that module.

Declare the global UniSim Design objects. The usd prefix is a convention
to identify variables which come from UniSim Design.
Dim usdContainer As
Object
Dim usdBulkDens As Object

- 78 -
Chapter 3 - Extensibility

7. The first function declared is the Initialize function. It is called when the extension is first added to UniSim Design or
when a case containing the extension is loaded.

Code Explanation

Public Function Initialize(ByVal Container As Object, ByVal Initialize is called when the
IsRecalling As Boolean) As Long extension is first added to the
simulation or when a simulation
case containing the extension is
loaded.

Enable Error trapping.

On Error GoTo ErrorTrap

Declare
KineticReactionContainer
Dim usdReactant As Reactant variable.

Reference the current UniSim


Design version
Initialize = extnCurrentVersion

This reference lets the extension


interact with UniSim Design
Set usdContainer = Container through the extension container,
the
ExtnKineticReactionContainer
object.
Methods from the
ExtensionObject object are also
available.

Set an object reference to the


BulkDens variable, which is
Set usdBulkDens = [Link]("BulkDens").Variab created in the EDF file.
le

The variable IsRecalling is only


False when the extension is first
If IsRecalling = False Then added to the simulation. This sets
[Link] = 2700 a default for BulkDens (2700 kg
catalyst/m3 reactor volume).

Setting the remaining reaction


properties (usually found on the
[Link] = ptVapourPhase Basis tab of the Reaction view).
[Link] = rbPartialPressBasis The Phase of the reaction is to be
Vapour and the reaction Basis is
to be Partial Pressure.

This initializes the reactants list by

- 79 -
Chapter 3 - Extensibility

Code Explanation

removing any reactants that may


[Link] be specified.

Adds the component Ethylene


as a Reactant. It sets the
Set usdReactant = [Link]("Ethylene") stoichiometric coefficient of
[Link] = -1 ethylene as - 1 (i.e., 1 mole of
[Link] = usdReactant ethylene being consumed). You
are also specifying ethylene to be
the base reactant.

Adds the remaining components


and specifies their stoichiometric
Set usdReactant = [Link]("AceticAcid") coefficients.
[Link] = -1
Set usdReactant = [Link]("Oxygen")
[Link] = -0.5
Set usdReactant = [Link]("VinylAcetate")
[Link] = 1
Sets the Basis Conversion units
Set usdReactant = [Link]("H2O")
[Link] = 1 to psia.
[Link] = "psia" The Rate Conversion units is left
With usdContainer
in UniSim Design internal units of
.SetReactionPropertyState rpReactants,
vsCalculated kg mole/m3-s.
.SetReactionPropertyState rpStoichiometricCoefficients,
vsCalculated
.SetReactionPropertyState rpMinTemperature,
vsCalculated
.SetReactionPropertyState rpMaxTemperature,
vsCalculated Sets the property states as
.SetReactionPropertyState rpReactionBasis, Calculated so that they cannot be
vsCalculated
.SetReactionPropertyState rpReactionPhase, modified.
vsCalculated The With statement is used for
.SetReactionPropertyState rpBaseReactant, efficiency since each line uses the
vsCalculated
.SetReactionPropertyState rpBasisConversion, SetReactionPropertyState
vsCalculated method of the usdContainer
.SetReactionPropertyState rpRateConversion,
object.
vsCalculated
End With
End If

Line to which the On Error


statement branches if an error
ErrorTrap: occurs

End Function Signifies the end of the function.


This line does not need to be
added.

8. The other function that is required to implement a kinetic reaction extension is the ReactionRate function.

Code Explanation

Public Function ReactionRate(ByVal Fluid As Object, ByVal This function is called whenever

- 80 -
Chapter 3 - Extensibility

Code Explanation

RxnTemperatureInC As Double, ByVal RxnVolumeInKmolPerM3 As the extension is executed.


Double, rate As Double) As Boolean

Enable Error trapping.

On Error GoTo ErrorTrap

Declare local variables.

Dim TotalPressure As Double


Dim RxnTemperatureinK As Double
Dim EthyleneIndex As Integer
Dim AceticAcidIndex As Integer
Dim OxygenIndex As Integer
Dim WaterIndex As Integer
Dim ComponentFracs As Variant
Dim EthylenePP As Double
Dim AceticAcidPP As Double
Dim OxygenPP As Double
Dim WaterPP As Double

Check to see if the value of


usdBulkDens > 0. If not, then
If [Link] <= 0 Then sets it to the default value of
[Link] = 2700 2700 kg catalyst/m3 reactor
volume.

Gets the overall pressure of the


reaction in psia.
TotalPressure = [Link]("psia")

Get the temperature of the


reaction K.
RxnTemperatureinK = RxnTemperatureInC + 273.15

Get component index numbers.


These index numbers are later
EthyleneIndex = [Link]("Ethylene") used to reference the
AceticAcidIndex = [Link]("AceticAcid") components and their
OxygenIndex = [Link]("Oxygen") properties.
WaterIndex = [Link]("H2O")

Set ComponentFracs equal to


the component molar fractions of
ComponentFracs = [Link] the fluid.

Get partial pressure of


components in psia by
multiplying component mole
fraction by total pressure (Smith

- 81 -
Chapter 3 - Extensibility

Code Explanation

and Van Ness, p. 300).


EthylenePP = ComponentFracs(EthyleneIndex) * TotalPressure
AceticAcidPP = ComponentFracs(AceticAcidIndex) * TotalPressure
OxygenPP = ComponentFracs(OxygenIndex) * TotalPressure
WaterPP = ComponentFracs(WaterIndex) * TotalPressure

Calculate the reaction rate1.


The rate is in g mol AceticAcid
rate = 0.1036 * Exp(-3674 / consumed/min-g catalyst.
RxnTemperatureinK) * OxygenPP * EthylenePP * [Link] is
AceticAcidPP * (1 + 1.7 * WaterPP) / ((1 + multiplied by 1000 to convert it
0.583 * OxygenPP * (1 + 1.7 * WaterPP)) * (1 +
6.8 * AceticAcidPP)) * [Link] * 1000 to g catalyst/m3 reactor
volume.

Since the units required by


UniSim Design are kg mole/m3-
rate = rate / 1000 / 60 s, divide by 1000 g mol/kg mol
and divide by 60 s/min.

Tell UniSim Design that the


calculation worked as expected.
ReactionRate = True

Line to which the On Error


statement branches if an error
ErrorTrap: occurs.

End Function Signifies the end of the function.


This line does not need to be
added.

9. Select Make [Link] command from the File menu. The Make Project view appears.

- 82 -
Chapter 3 - Extensibility

Figure 3.7

10. Select the folder you want to save the [Link] file in, and click the OK button.

[Link] Creating the Extension Definition File (EDF)

In order to complete the Kinetic Reaction Extension, you must create an EDF. This is done through the Extension View
Editor.

NOTE
If it has been installed, the Extension View Editor is found in the same launch point in the Start menu as
UniSim Design. For more information on installing and accessing the View Editor, see Accessing the
View Editor.

1. Open the Extension View Editor and open a new EDF by doing one of the following:
l Select New command under the File menu in the menu bar
l Use the hot key combination CTRL N

l Click the New File icon


The default View Manager view appears as shown below:

Figure 3.8

2. Click the Objects Manager icon to open the Objects Manager view.
3. In the ProgID/CLSID field enter [Link] as the extension ID.
4. Enter an appropriate description for the extension in the Description field, such as Vinyl Acetate Reaction
Extension as shown in below figure.
5. Select Kinetic Reaction as extension type in the Type drop-down list.

- 83 -
Chapter 3 - Extensibility

6. Specify the information in the Variables of Selected Object group as shown below, and check the Persistent
checkbox.

Figure 3.9

7. Click the Close button. This returns you to the Views Manager view.

Figure 3.10

8. From the Existing Views list, select the DefaultView and click the Edit button. The DefaultView form appears. It
consists of several default objects that are not used in this example. These objects have to be deleted.
9. Begin by deleting the Page Tabs widget. Select the tabs found at the bottom of the DefaultView form as shown
below and press the DELETE key.

- 84 -
Chapter 3 - Extensibility

Figure 3.11

10. Delete the Name Static Text widget and the Object Name Text Entry widget using the method described in the
step above.
11. Resize the DefaultView form into a smaller view, as shown below.

Figure 3.12

Adding Widgets to the DefaultView form

1. From the Widgets Palette select a Numerical Input widget. Right- click, hold, and drag the widget into the
DefaultView form. When you find an appropriate part of the view to place the widget, release the mouse button and
the widget should drop into place.
2. Using the drag and drop method described in the above step to add the two Static Text widgets and a Button
widget as shown below.

- 85 -
Chapter 3 - Extensibility

Figure 3.13

3. Now the widgets must be defined. To open a widget’s properties do one of the following:
l Double-click on the widget
l Right-click the widget and select <Widget Type> Properties command from the Object Inspect menu,
where Widget Type would be Button for a Button widget.

4. For the upper Static Text widget specify properties as shown below. When you are finished click the OK button.

Figure 3.14

5. For the lower Static Text widget specify properties as shown below. When you are finished click the OK button.

- 86 -
Chapter 3 - Extensibility

Figure 3.15

6. For the Numerical Input widget specify properties as shown below. When you are finished click the OK button.

Figure 3.16

TIP
The Target Moniker field is specified by clicking the Ellipsis icon associated with the field and selecting
Bulk Density from the Select Number Variable view.

7. Open the properties view for the Button widget.


8. In the Label field specify the button label as &Close where the & indicates the hot key underscore designation (i.e.,
pressing ALT + hot key brings focus to this object).
9. Click the Ellipsis icon associated with the Message field to open the Edit Messages view.
10. Click the Insert button on the Edit Messages view. The Select Message view appears. Select the Close the View
message from the list.

Figure 3.17

11. Click the OK button to add this message to this button. The Edit Messages view appears as shown below.

- 87 -
Chapter 3 - Extensibility

Figure 3.18

12. Click the OK button on the Edit Messages view to close this view and return to the Button Properties view.
13. Specify the Name field as shown below. When you are finished click the OK button.

Figure 3.19

The view now appears as shown below.

Figure 3.20

14. Select Save command from the File menu and save the EDF file as “[Link]” in the same directory as the DLL
file.

- 88 -
Chapter 3 - Extensibility

[Link] Attaching the Extension to UniSim Design

You are now ready to attach the extension to UniSim Design. The following steps demonstrate how to attach an extension
within UniSim Design.

1. Start UniSim Design. From the Tools menu, select Preferences command. The Session Preferences view
appears.
2. Go to the Extensions tab and click the Register an Extension button. The Select an Extension to be Registered
view appears.
3. Use the File Path group to find the directory in which the [Link] file is saved in. Once you find the DLL file,
select it and click the OK button.

Figure 3.21

4. The UniSim Design Extension Registration view appears and displays whether the registration was successful or
not. Click the OK button to close the view.
The Extensions tab should now appear similar to the figure below.

- 89 -
Chapter 3 - Extensibility

Figure 3.22

5. You can now go to the Reactions tab of the Simulation Basis Manager view and add a VinylAcetate Reaction
Extension from the Reactions view.

Figure 3.23

3.9 Extension Property Packages


You can put your own physical property calculations into UniSim Design as an Extension Property Package, which appears
to the user as any other property package in the program.

UniSim Design makes calls to property packages under a number of different situations. Calls are made in both Steady State
and Dynamics mode.

To implement an Extension Property Package, you must implement two interfaces:

Interface Description

ExtensionObject Called when the property package extension is added to the simulation.

ExtnPropertyPackage Called when the property package extension is used.

Many different methods must be supported by Extension Property Packages; however, depending on what functionality is
supported, certain methods may be left unimplemented. The extension must let its container know which features it supports
through the ExtensionPPkgInit structure passed to the extension in its Initialize method.

- 90 -
Chapter 3 - Extensibility

The ExtnPropertyPackage interface is not a dual interface; for efficiency, non-ActiveX Automation compatible data types are
passed as parameters. This means that Extension Property Packages cannot be easily written in Visual Basic, and cannot
be implemented as Local Servers.

3.9.1 Initialization
When an Extension Property Package is initialized, it must fill in the ExtensionPPkgInit structure passed to it by its container.
This structure lets the container know which features the extension supports, such as requirements for a component slate
and whether or not the property package can handle changes to the component slate order.

An Extension Property Packages can be as simple as a steam table, or as complex as an activity model or equation of state
package. UniSim Design behaves differently for property packages of differing functionality. For example, if a given property
package cannot handle hypothetical components, you are not allowed access to the Oil Environment for that property
package.

[Link] Component Slates

If the Extension Property Packages has a fixed component slate, UniSim Design pre-selects those components, and does
not allow the user to remove them or add other components. The extension lets its container know of this restriction by
setting the NumberOfPreselectedComponents member of the ExtensionPPkgInit structure to a non-zero value. UniSim
Design then calls the extension's GetPreselectedCompIDs method at a later point. If zero is passed for the
NumberOfPreselectedComponents member, UniSim Design allows you to select whatever components are available.

Filtering of the component list is done through the implementation of the IsComponentAllowed method. This method returns
True if the component with the passed ComponentID is supported by the property package, or False if it is not. If the
extension has a fixed component slate (that is, it has returned a non-zero for NumberOfPreselectedComponents), the
container handles the implementation of the IsComponentAllowed method, allowing the extension developer to return E_
NOTIMPL for the method.

If the property package cannot handle changes to the component slate, the CanExchangeComponents flag can be set in the
ExtensionPPkgInit structure. If this flag has been set, UniSim Design only allows you to add or remove components from the
end of the list.

3.9.2 ExtensionPPkgInit structure


This structure is passed to an Extension Property Packages in its Initialize method. The extension must fill in the structure
according to its capabilities.

typedef struct
{
long StructSize;
long Version;
long NumberOfPreselectedComponents;
enum DynamicPropertyMethod DynPropMethod;
VARIANT_BOOL IsActivityModelType;
VARIANT_BOOL CanExchangeComponents;
VARIANT_BOOL CanCalculateFugacity;
VARIANT_BOOL CanCalculateLLE;
VARIANT_BOOL CanHandleOilHypos;
VARIANT_BOOL UseGFlashInDynamics;
VARIANT_BOOL CanHandleInsideOutPHFlash;
} ExtensionPPkgInit;

Data Member Details

StructSize This data member contains the size of the ExtensionPPkgInit structure.

Version This data member must be filled in with extnCurrentVersion.

NumberOfPreselectedComponents If the property package has a fixed component slate, this number should be a
non-zero value.

- 91 -
Chapter 3 - Extensibility

Data Member Details


DynPropMethod This must be set to the type of Dynamic Property Method to be used with the
property package. See DynamicPropertyMethod_enum in the type
library.

IsActivityModelType This should be set to True if the property package can be considered an
activity model property package. A number of flash algorithms in UniSim
Design optimize their algorithms based on the value of this data member.

CanExchangeComponents This member should be set to True if the property package can handle
changes to the location of components in the component slate.

CanCalculateFugacity This should be set to True if the property package has implemented the
ComputePhaseFugacities method. If it is set to False, this method is never
called.

CanCalculateLLE This should be set to True if the property package can calculate liquid-liquid
equilibrium calculations using the inside-out algorithm. If this is set to True, the
property package must implement the ComputeHInnerParamsLL and
ComputeKFactorsLL methods.

CanHandleOilHypos If the property package can handle Oil hypotheticals, this should be set to
True. If it is set to False, the user is not allowed in to the Oil Environment.

UseGFlashInDynamics This flag is used to optimize thermodynamic calculations in dynamics. If is


recommended that this be set to True unless the property package is an
equation of state.

CanHandleInsideOutPHFlash This flag disables the inside-out enthalpy flash if it is set to False. It is
recommended that this flag be set to True unless the property package
operates on a narrow temperature range.

3.9.3 ExtnPPkgContainer Interface


The ExtnPPkgContainer interface is passed to an Extension Property Package in its Initializemethod.

Derived from Properties Methods

ExtnContainer NumberOfComponents BuildPlot

BreakRequested BuildPlot2

ExtensionInterface BuildPlotWithCallback

FPStatus ClearStatusBar

name DeletePlot

OnOleEnabledThread FindVariable

SimulationCase GetComponent

StatusBar GetPlot

GetPlot2

OpenContainerStorage

OpenView
Trace WaitForTurn

- 92 -
Chapter 3 - Extensibility

3.9.4 ExtnPropertyPackage Interface


The ExtnPropertyPackage interface must be implemented by all Extension Property Packages. Only the Initialize method
must be supported, all others could return E_NOTIMPL.

Derived from Properties Methods

IUnknown none AddComponent CopyPropertyPackage

ComponentChanged DynTreatComponentAsInert

ComputeHInnerParamsLL EndBasisChange

ComputeHInnerParamsVL ExchangeComponents

ComputeKFactors ExchangeTwoPhases

ComputeKFactorsLL GetPreSelectedCompIDs

ComputeKFactorsVL GuessBubblePointTemperature

ComputeLiquidMolarDensity Initialize

ComputeLiquidSurfaceTension InitializeKFactors

ComputePhaseActivity IsComponentAllowed

ComputePhaseFugacities OrderPhases

ComputePhaseProperties QueryEndBasisChange

ComputePhaseThermalConductivity RemoveComponent

ComputePhaseViscosity StartBasisChange

NOTE
The ExtnPropertyPackage interface is not a dual interface, and methods of the interface will not be called through the
Dispatch Invoke mechanism.

3.10 Extension Unit Operations


You can implement Unit Operation calculations in UniSim Design by creating an Extension Unit Operation.

To implement an Extension Unit Operation, you must implement two interfaces:

Interface Description

ExtensionObject Called when unit operation extension is added to the simulation.

ExtnUnitOperation Called when the unit operation extension is used.

These objects allow the unit operation to function in the UniSim Design environment. The minimum requirements for the Unit
Operation Extensions is the definition of two methods:

Method Description

Initialize The Initializemethod is called whenever the extension is first added or whenever a case containing the
extension is reopened. The Initialize method is a function that expects the current build value of UniSim
Design to be returned. By referencing the UniSim Design Type Library it is possible to use the constant

- 93 -
Chapter 3 - Extensibility

Method Description

extnCurrentVersion to return the proper build value.


The Initialize method passes two arguments when it is called. The first argument is the extension container
object. With the extension container object, all the variables declared in the EDF can be accessed. The
second argument “IsRecalling” is used to determine if the extension is being added for the first time or if the
case already contained the extension. This flag can be used to set default values or to assure that the
values specified by the user are not overwritten by the default values.

Execute Extension Unit Operations perform their calculations within their Execute method. This method is called by
the Steady State Solver during the Execute Passes; it must not be called directly by the extension.
The Execute method is called whenever a stream connected to the extension is changed or when any of
the variables marked as trigger solve in the EDF are changed. UniSim Design automatically calls the
Execute method and pass the Forgetting argument. The Forgetting argument relates to how UniSim
Design solves based on the degrees of freedom approach. Whenever a variable is changed within UniSim
Design, all the values associated or utilizing that value as a basis for calculation must be forgotten. This
Forget process propagates throughout the simulation model. It is a good idea to check the Forgetting
argument prior to executing code. Especially if values that are forgotten are used in the calculation. A
forgotten value is set to the empty state, which, for UniSim Design is the number -32767.

3.10.1 Extension Definition Files


An extension definition file is required for the custom unit operation’s visual interface within the UniSim Design environment
and also for the object interface to the ActiveX Server DLL. Variables that are used through the interface need to be declared
in the EDF.

3.10.2 ExtnUnitOperationContainer Interface


The ExtnUnitOperationContainer interface is passed to an extension Unit Operation in its Initialize method.

Derived from Properties Methods

ExtnContainer BreakRequested AddSolverNotification FindVariable

ExtensionInterface Balance GetPlot

Flowsheet FPStatus BuildPlot GetPlot2

name BuildPlot2 OpenContainerStorage

OnOleEnabledThread BuildPlotWithCallback OpenView

SimulationCase ClearStatusBar RemoveSolverNotification

StatusBar CreateFluid DeletePlot SolveComplete


FindFluid Trace TriggerSolve

3.10.3 ExtnUnitOperation Interface


The ExtnUnitOperation interface must be implemented by all Extension Unit Operations. Only two methods (the Initialize
method and the Execute method) are mandatory.

Derived from Properties Methods

IDispatch none BasisChanged

Execute

Initialize

- 94 -
Chapter 3 - Extensibility

3.10.4 Passes
[Link] Execute Passes

The Solver performs steady state calculations in two passes: the Forget Pass and the Calculate Pass. Normally, extension
Unit Operations need not know which pass is underway, but an IsForgetting parameter is passed to the extension's
Execute method so the extension can optimize calculations if necessary.

The Solver propagates information through the flowsheet via the Solver Notification links that are set up when connections
are made between objects. Whenever a Unit Operation changes the value of a variable within a linked object, that object's
Execute method is called. If that object then changes the value of a variable in another object, the Solver then moves on to
that object.

The propagation of information is completed when no object can calculate any new information, or if calculated values are
within a tolerance of the value previously calculated. When new values are within the tolerance, the linked object does not
have its Execute method called.

If two objects calculate the same value in to an object, and these values are not within the tolerance, an Inconsistency
condition occurs. When this happens, the Solver stops and switches in to Hold Mode. To allow different objects to calculate
different values because of changes in the flowsheet, it is necessary that values that depend on another changing value be
forgotten. This forgetting occurs during the Forget Pass.

[Link] Forget Pass

When the value of a variable changes, the Solver first does one Solve Pass on the flowsheet with the value marked as
unknown. Each object that is linked to the object with the changed variable has its Execute method called, and the object
must perform as many calculations as it can with the remaining known information.

Any calculations that were performed based on the value of the newly forgotten variable in the last pass are not able to be
calculated during this pass. After the object has finished its Execute call, the Solver then determines which variables the
object calculated last time that have not been touched this time. These variables are then marked as unknown, and the
Solver propagates this information to other linked objects in the flowsheet.

Normally, an object need not behave any differently during the Forget Pass than during the Calculate Pass. In order to
prevent unnecessary propagation of forgotten information (and therefore the unnecessary recalculation of this information in
the Calculate Pass), the object must still calculate all that it can to ensure that the variables it calculated last time are touched.

[Link] Calculate Pass

After all information based on the previous value of a variable has been forgotten, the new value is set in to the variable and
the second Solver pass (the Calculate Pass) is started. In this pass, each object affected by the change in the variable has its
Execute method called. Any changes these objects make are propagated through the flowsheet as the variables in other
objects are touched.

The Execute method of an object can be called more than once in either of the Solve Passes, as variables in the object are
touched by other objects in the flowsheet.

3.10.5 Extension Unit Operation Example


In this example, you use Visual Basic 5.0 to build a unit operation extension that saturates a feed stream with Water.

1. Open a new project in Visual Basic 5.0 and from the New tab of the New Project property view select the

[Link] icon and click the Open button.


2. Make sure that the UniSim Design Type Library is checked in the References view, which is accessed by
selecting References command from the Project menu.

- 95 -
Chapter 3 - Extensibility

Figure 3.24

3. In the Properties tiled view, rename the class module Saturate, and ensure that the Instancing field is set to 5-
MultiUse.

Figure 3.25

4. Rename the project name to UnitOpExtn as shown.

- 96 -
Chapter 3 - Extensibility

Figure 3.26

5. Save the class and project by selecting Save Project command from the File menu. Save the class and project as
[Link] and [Link].
6. Begin by defining the global variables in the Project Code Editor:

Code Explanation

Option Explicit Used to force explicit declaration of all variables in that module.

Declare the global UniSim Design objects. The usd prefix is a


convention to identify variables which come from UniSim
Design.

l The extension unit operation container object.

Dim usdContainer As
ExtnUnitOperationContainer

l The extension feed stream object.

Dim usdFeedStrm As Object

l The extension product stream object.

Dim usdProdStrm As Object

l The extension water stream object.

Dim usdWatStrm As Object

Declare objects used internally:

l The UniSim Design Components collection object.

- 97 -
Chapter 3 - Extensibility

Code Explanation

Dim Components As Object

l A single UniSim Design Component object.

Dim Component As Object

l A fluid object used for calculations.

Dim WorkFluid As Object

l A water fluid object.

Dim WatFluid As Object

l An array of ProcessStream objects.

Dim Streams(0 To 2) As Object

l Object reference to the Extension Interface.

Dim myOp As Object

Declare variables used internally:

l Indicates if water is present.


Dim WaterPresent As Boolean

l The index for water.


Dim H2O As Integer

l Temporary variable.
Dim Temp As Variant

l Array of molar flows.


Dim MoleFl As Variant

l Count variable.

- 98 -
Chapter 3 - Extensibility

Code Explanation

Dim Count As Integer

l Count variable.
Dim i As Integer

l Are the feed streams in the array valid.


Dim IsKnownFeedArray As Variant

l Error level used to display status messages.


Dim CalcError(0 to 1) As Boolean

l Indicates if the unit op is ignored.


Dim IsIgnoredBool As Boolean

l -32767 is used internally by UniSim Design to represent an


Const conEmpty As Integer = -32767 empty value.

7. The first function declared is the Initialize function. It is called when the extension is first added to UniSim Design or
when a case containing the extension is loaded.

Code Explanation

Public Function Initialize(ByVal Container As Object, ByVal Initialize is called when the
IsRecalling As Boolean) As Long extension is first added to the
simulation or when a
simulation case containing the
extension is loaded.

Enable Error trapping.

On Error GoTo ErrorTrap

Initialize variables.

CalcError(0) = False
CalcError(1) = False

Reference the current UniSim


Design version.

- 99 -
Chapter 3 - Extensibility

Code Explanation

Initialize = extnCurrentVersion

Set usdContainer = Container


Set myOp = [Link] NOTE
During the Initialize call
the container interface
should be assigned to a
reference variable but
only used from other
extension methods, not
from inside Initialize.
This is because the
extension is being
prepared for use and not
all container methods
are available until after
initialization completes.

Get the list of components


that are currently attached to
Set Components = [Link] ts the fluid package. For each
WaterPresent = False component in the list,
For Each Component In Components determine if water is one of the
If [Link] = "H2O" Then
WaterPresent = True components. If water is
Next present, determine the
If WaterPresent Then
internal index number of
H2O = [Link]("H2O")
water.

Set an object reference to the


Feed, Product and Water
Set usdFeedStrm = [Link]("FeedStream"). stream attachment objects in
Vari [Link] the EDF.
Set usdProdStrm = [Link]("ProductStream").
V [Link]
Set usdWatStrm = [Link]("WaterStream").
Var [Link]

IsRecalling is False when


the extension is first added to
If IsRecalling = False Then End If the simulation, IsRecalling is
True when a saved simulation
case containing the extension
is loaded. The If statement
uses IsRecalling to set
defaults. Saturate has no
default values, so none are set
here.

- 100 -
Chapter 3 - Extensibility

Code Explanation

Line to which the On Error


statement branches if an error
ErrorTrap: occurs.

Signifies the end of the


function. This line does not
End Function
need to be added.

8. The other function that is required to implement a Unit Operation Extension is the Execute function.

Code Explanation

Public Sub Execute(ByVal Forgetting As Boolean) This sub-routine is called


whenever the extension is
executed.

Enable Error trapping.

On Error GoTo ErrorTrap

When a change is made to a


variable which affects the
If Not Forgetting Then extension, UniSim Design
performs a Forgetting pass
and two Calculation Passes.
The Forgetting pass is used
to identify the streams, unit
operations, etc. affected by
the change. The first
Calculation pass is used to
allow the extension to
complete its internal
calculations. The second
Calculation pass is made so
that external references
made by the extension use
correct values. If the
extension makes no external
references, then the second
pass can be bypassed using
the SolveComplete method
of the Container object. This
command is included later in
the code. For efficiency, no
calculations are made during
the Forgetting pass.

Determine if water is present


(ensure it hasn't been
removed).

- 101 -
Chapter 3 - Extensibility

Code Explanation

Set Components = [Link] nts


WaterPresent = False
For Each Component In Components
If [Link] = "H2O" Then
WaterPresent = True
Next Component
If Not WaterPresent Then
GoTo ErrorTrap

Get the index for water.

H2O = [Link]("H2O")

Set an object reference to


the Feed, Product and Water
Set usdFeedStrm = [Link]("FeedStream"). stream attachment objects in
Vari [Link] the EDF.
Set usdProdStrm = [Link]("ProductStream").
V [Link]
Set usdWatStrm = [Link]("WaterStream").
Var [Link]

If the streams are not


attached, then exit.
If usdFeedStrm Is Nothing Then GoTo ErrorTrap
If usdWatStrm Is Nothing Then GoTo ErrorTrap
If usdProdStrm Is Nothing Then GoTo ErrorTrap

Determine if the feed stream


has the information required.
If [Link] = conEmpty
Then GoTo ErrorTrap
If [Link] = conEmpty
Then GoTo ErrorTrap
If [Link] = conEmpty
Then GoTo ErrorTrap
Temp = [Link]
If (Temp(0) = conEmpty)
Then GoTo ErrorTrap

Create a duplicate fluid


object of usdFeedStrm and
Set WorkFluid = [Link] creates an array containing
Set WatFluid = [Link] the mole fraction of each
MoleFl = [Link] component in the fluid.

For every component in the


fluid, divide the mole fraction
For i = 0 To [Link] - 1 by a factor of 10. This means
MoleFl(i) = MoleFl(i) / 10 that the current composition
Next of the stream now only make
up 10% of the fluid

- 102 -
Chapter 3 - Extensibility

Code Explanation
composition. Make the
MoleFl(H2O) = 0.9 + MoleFl(H2O) remaining 90% water.
[Link] = MoleFl

Do a TP Flash on the fluid at


the temperature and
[Link] pressure of the stream
[Link], usdFeedStrm. If there is a
[Link] second phase then an error
If [Link] = 1 Then
CalcError(0) = True has occurred.
GoTo ErrorTrap
End If

Creates a temporary array


containing the component
Temp = [Link] molar fraction values of the
If Temp(0) = conEmpty Then stream object usdWatStrm
MoleFl = [Link] (the water stream).
If the mole fraction of the first
component in the stream is
not specified, then do the
following:

Set the mole fraction of every


component in the temporary
For i = 0 To [Link] - 1 array to be zero. Then set the
MoleFl(i) = 0 mole fraction of water to be 1.
Next i
MoleFl(H2O) = 1

Deletes the current


component molar fraction
[Link] values of the stream
[Link] MoleFl usdWatStrm. It then sets
the component fraction of the
stream to the contents of the
temporary array MoleFl.

Else if the mole fraction of


water in the stream
ElseIf Temp(H2O) = 0 Then usdWatStrm is zero then an
CalcError(1) = True error has occurred.
GoTo ErrorTrap
End If

Resets the water stream


temperature and pressure at
With usdWatStrm the new molar composition.
.[Link]
.[Link]
[Link]

- 103 -
Chapter 3 - Extensibility

Code Explanation

.[Link]
.[Link]
[Link]
End With

If the feed stream molar flow


is 0 then exit.
If [Link] = 0 Then
[Link] 0
GoTo EndCalcs
End If

Creates a duplicate fluid of


the feed and water streams
Set WorkFluid = [Link] and sets the counter variable
Set WatFluid = [Link] Count to zero.
Count = 0

If the number of phases in the


feed stream fluid is greater
If [Link] > 1 Then than 1, then set the molar
[Link] 0 flow of the water stream to
GoTo EndCalcs zero.
End If

Determine water stream flow


required to saturate feed
Do While [Link] = 1 stream.
Count = Count + 1 While the number of phases
Set WorkFluid = [Link] in the feed stream is still one,
[Link] = [Link] * (Count / 20)
[Link] WatFluid [Link] increase the molar flow of the
[Link], water stream. Add the feed
[Link] and water streams and
Loop
reflash the stream at the feed
stream’s temperature and
pressure.

Set MoleFl to the values of


the component molar flows of
MoleFl = [Link] the heavy liquid phase of the
fluid object WorkFluid.

Set the variable Temp to be


the difference between the
Temp = [Link] - MoleFl(H2O) flow rate of the water stream
If Temp < 0 Then and component molar flow
Temp = 0 [Link] Temp rate of water in the heavy
liquid phase of the saturated
stream. If the difference is
negative (i.e., no water is
required), set the molar flow

- 104 -
Chapter 3 - Extensibility

Code Explanation
rate of the water fluid to zero.

Begin the end calculations


procedure.
EndCalcs:

Erase contents of the fluid.

[Link]
[Link]

Set product stream


temperature and pressure
With usdProdStrm values.
.[Link]
.[Link]
[Link]
.[Link]
.[Link]
[Link]
End With

If feed stream molar flow is 0


then calculate product
If [Link] = 0 Then stream as feed stream.
[Link]
[Link]
[Link]
[Link]

If feed stream molar flow is


not 0, then perform a mole
Else balance.
Set Streams(0) = usdFeedStrm
Set Streams(1) = usdWatStrm
Set Streams(2) = usdProdStrm
[Link] btMoleBalance, 2, Streams
End If

This line prevents a second


Calculation pass, because it
[Link] is not required. See the
comment associated with the
If Not Forgetting Then line of
code at the beginning of the
code. Read the section on
the SolveComplete method
in Extending UniSim Design
Help file for more
information.

Reset error flags.

- 105 -
Chapter 3 - Extensibility

Code Explanation

CalcError(0) = False
CalcError(1) = False
End If

Line to which the On Error


statement branches if an
ErrorTrap: error occurs.

End Sub Signifies the end of the sub-


routine. This line does not
need to be added.

9. While the Initialize and Execute methods are required for the implementation of the unit operation extension, it is
strongly recommended you also include a Status Query method that accurately assesses how the extension is
performing.

Code Explanation

Public Sub StatusQuery(usdStatus As ObjectStatus) The StatusQuery sub-routine of the


extension is used to display appropriate
messages on the extension view (EDF
file) in UniSim Design. This sub-routine is
called whenever some change is made to
the extension, whether it is a result of a
solver pass or user interaction.

Declare and initialize the OK flag.

Dim OK As Boolean
OK = True

If there is no water present in the fluid


package, an error message appears
If WaterPresent = False Then telling you water is required.
Call
[Link](slMissingRequir
edInformation, 1, "Water is Required as a Component")
OK = False
End If

If there is no feed stream attached to the


unit op, an error message appears telling
If usdFeedStrm Is Nothing Then you that a feed stream is required.
Call
[Link](slMissingRequir
edInformation, 2, "Feed Stream Required")
OK = False
End If

If there is no water stream attached to the

- 106 -
Chapter 3 - Extensibility

Code Explanation

unit op, an error message appears telling


If usdWatStrm Is Nothing Then you that a water stream is required.
Call
[Link](slMissingRequir
edInformation, 4, "Water Stream Required")
OK = False
End If

If there is no product stream attached to


the unit op, an error message appears
If usdProdStrm Is Nothing Then telling you that a product stream is
Call required.
[Link](slMissingRequir
edInformation, 3, "Product Stream Required")
OK = False
End If

If the Ignored checkbox is checked then


send an Ignored message to the status
If [Link] = True Then bar.
Call
[Link](slWarning, 11,
"Ignored")
OK = False
End If

These next message can wait until the


connections are made so skip them.
If OK = False Then Exit Sub

If the feed stream temperature is not


known, then send an Unknown Feed
If Not [Link] Then Temperature message to the status bar.
Call
[Link](slMissingOption
alInformation, 5, "Unknown Feed Temperature")
OK = False
End If

If the feed stream pressure is not known,


then send an Unknown Feed Pressure
If Not [Link] Then message to the status bar.
Call
[Link](slMissingOption
alInformation, 6, "Unknown Feed Pressure")
OK = False
End If

If the feed stream molar flow rate is not


known, then send an Unknown Feed
If Not [Link] Then Flow message to the status bar.

- 107 -
Chapter 3 - Extensibility

Code Explanation

Call
[Link](slMissingOption
alInformation, 7, "Unknown Feed Flow")
OK = False
End If

Check to see if the feed stream’s


composition has been set. If it has not, an
IsKnownFeedArray = [Link]. error message is sent to the status bar
IsKnown indicating an Unknown Feed
If Not IsKnownFeedArray(0) Then Composition.
Call
[Link](slMissingOption
alInformation, 8, "Unknown Feed Composition")
OK = False
End If

If the first error flag has been tripped, it


sends a message to the status bar
If CalcError(0) Then indicating that the Feed Cannot be
Call [Link](slError, Saturated with Water.
9, "Feed Cannot be Saturated with Water")
OK = False
End If

If the second error flag has been tripped,


it sends a message to the status bar
If CalcError(1) Then indicating that Water is Required in the
Call [Link](slError, Water Stream.
10, "Water is required in Water Stream")
OK = False
End If

End Sub Signifies the end of the sub-routine. This


line does not need to be added.

10. Select Make [Link] command from the File menu.

[Link] Creating the Extension Definition File (EDF)

In order to complete the Unit Operation Extension, you must create an EDF. This is done through the UniSim Design
Extension View Editor.

NOTE
If it has been installed, the Extension View Editor is found in the same launch point in the Start menu as UniSim
Design. For more information on installing and accessing the View Editor, see Accessing the View Editor.

- 108 -
Chapter 3 - Extensibility

1. Open the Extension View Editor. Open a new EDF by doing one of the following:
l Select New command under File menu in the menu bar
l Use the hot key combination CTRL N

l Click the New File icon

Figure 3.27

2. Click the Objects Manager icon to view the Objects Manager view.
3. In the ProgID/CLSID cell enter [Link] as the extension ID.
4. Enter an appropriate description for the extension in the Description cell, such as Saturate Extension.
5. Select Unit Operation as the extension type in the Type drop-down list.
6. In the Variables of Selected Object group declare the following variables:

Attachment Flow N
Tag Description Type Persistent
Type Direction Dimensions

FeedStream FeedStrm Attachment Active Material Feed None


Stream

ProductStream ProductStrm Attachment Active Material Product None


Stream

WaterStream WaterStrm Attachment Active Material Feed None


Stream

The Object Manager view now appears similar to the figure below.

- 109 -
Chapter 3 - Extensibility

Figure 3.28

7. Click the Close button. This returns you to the Views Manager view.

Figure 3.29

8. From the Existing Views list, select DefaultView and click the Edit button. The DefaultView form appears.

- 110 -
Chapter 3 - Extensibility

Figure 3.30

Defining the Tabs

1. To open the properties view for the Page Tabs widget (or for any widget), do one of the following:
l Double-click on the widget
l Right-click the widget and select <Widget Type> Properties command from the Object Inspect menu,
where Widget Type would be Button for a Button widget.

2. The Page Tabs properties view appears. Click the Ellipsis icon associated with the Target Moniker field.
3. The Select Number Variable view appears. From the list select Current Page and click the OK button.

Figure 3.31

4. In the Label field of the Static Tabs group change the two entries Page1 and Page2 to Connections and
Worksheet, respectively.

- 111 -
Chapter 3 - Extensibility

Figure 3.32

5. Close the Page Tabs properties view by clicking the OK button.


6. Now controls must be added to the tabs. Open the Visibility Manager view by right-clicking the DefaultView form
background and selecting Open Visibility Manager command from the Object Inspect menu.

Figure 3.33

7. A default controller has already been set up for the page tabs called PageController. Click the Edit button to view
the Visibility Controller Properties view.
8. In the States matrix, you should notice two entries: Page1 and Page2. Rename these two states Connections and
Worksheet, respectively, to coordinate the states to respective tab names.

Figure 3.34

- 112 -
Chapter 3 - Extensibility

TIP
The names of the two radio buttons that appear in the PageController group have changed to the names of the
two page tabs.

9. Click the OK button to return to the Visibility Manager view.

Adding Widgets to Connections Tab

You are now ready to add widgets to the Connections tab on the DefaultView form.

1. From the Widgets Palette select the Attachment Name widget. Right-click, hold, and drag the widget on to the
DefaultView form. Move the widget to the left side of the view.
2. Add two more Attachment Name widgets to the view using the drag and drop method described in the step above.
Stagger the two widgets in the upper and lower corners of the right side as shown in the below figure.
3. Place a Static Text widget above each Attachment Name widget.

Figure 3.35

4. First the Feed widgets (i.e., the Attachment Name and Static Text widget on the left) is defined. For the Feed Static
Text widget specify properties as shown below. When you are finished click the OK button.

- 113 -
Chapter 3 - Extensibility

Figure 3.36

5. For the Feed Attachment Name widget specify properties as shown below. When you are finished click the OK
button.

Figure 3.37

TIP
The Target Moniker field is specified by clicking the Ellipsis icon associated with the field and selecting
FeedStrm from the Select Attachment view.

6. For the Water Stream (i.e., upper right) Static Text widget specify properties as shown below. When you are
finished click the OK button.

- 114 -
Chapter 3 - Extensibility

Figure 3.38

7. For the Water Attachment Name widget specify properties as shown below. When you are finished click the OK
button.

Figure 3.39

TIP
The Target Moniker field is specified by clicking the Ellipsis icon associated with the field and selecting
WaterStrm from the Select Attachment view.

8. For the Product Stream (i.e., lower right) Static Text widget specify properties as shown below. When you are
finished click the OK button.

- 115 -
Chapter 3 - Extensibility

Figure 3.40

9. For the Product Attachment Name widget specify properties as shown below. When you are finished click the OK
button.

TIP
The Target Moniker field is specified by clicking the Ellipsis icon associated with the field and selecting
ProductStrm from the Select Attachment view.

Figure 3.41

The DefaultView form now appears as shown in the figure below.

- 116 -
Chapter 3 - Extensibility

Figure 3.42

Adding Widgets to Worksheet Tab

The next step is to add widgets to the Worksheet tab on the DefaultView form.

1. In the Visibility Manager view, select the Worksheet radio button.

TIP
Open the Visibility Manager view by right- clicking the DefaultView form background and selecting Open
Visibility Manager command from the Object Inspect menu.

2. Insert a Matrix widget on the Worksheet tab. Resize the widget so that about 1 cm space appears between the
matrix and tab borders.

- 117 -
Chapter 3 - Extensibility

Figure 3.43

3. Open the Matrix Properties view. In the Fly By field enter Properties of connected streams.
4. In the Cells group change the value in the Width field to 46 and the value in the Wrap field to 2.
5. In the Labels group set the Labels drop-down list to Row, the Show Units drop-down list to Row, and the Left Width
field to 74.
6. Check the Vertical Direction checkbox. The Matrix Properties view should appear similar to the figure below.

Figure 3.44

7. The Data Set list should contain a default data set. Click the Insert button to open the Select a Data Type view and
add a new data set to the list.

- 118 -
Chapter 3 - Extensibility

8. On the Select a Data Type view, select Text as the data type and click the OK button.

Figure 3.45

9. A Text Data Set Properties view appears. Change the name of the data set to WRKName.

10. Click the Ellipsis icon associated with the Moniker field to open the Select Text Variable view.
11. On the Select Text Variable view, select WaterStrm from the Base Object drop-down list.
12. From the list select Object Name as shown in the figure below and click the OK button.

Figure 3.46

13. The Select Text Variable view closes, and you are returned to the Text Data Set Properties view.
14. In the Label group enter Name as the label associated with field and click the OK button to close the Data Set
Properties view.

Figure 3.47

15. Insert a Numeric data set as described in the above steps #7 and #8.
16. A Numeric Data Set Properties view appears. Change the name of the data set to WRKFlow.

- 119 -
Chapter 3 - Extensibility

17. Click the Ellipsis icon associated with the Moniker field to open the Select Number Variable view.
18. On the Select Number Variable view, select WaterStrm from the Base Object drop-down list.
19. From the list select Molar Flow and click the OK button. The Select Number Variable view closes, and you are
returned to the Numeric Data Set Properties view.
20. In the Label group enter Molar Flow as the label associated with field and click the OK button to close the Numeric
Data Set Properties view.

Figure 3.48

21. Click the OK button on the Matrix Properties view to close the view. The DefaultView form appears similar to the
figure shown below.

TIP
Other data sets can be added for other streams and other stream properties, however for the sake of brevity,
these are the only two cells defined.

- 120 -
Chapter 3 - Extensibility

Figure 3.49

22. Select Save command from the File menu and save the EDF as [Link] in the same directory as the DLL
file.

Attaching the Extension to UniSim Design

You are now ready to attach the extension to UniSim Design. The following steps demonstrates how to attach an extension
within UniSim Design.

1. Start UniSim Design. From the Tools menu, select Preferences command. The Session Preferences view
appears.
2. Go to the Extensions tab and click the Register an Extension button. The Select an Extension to be Registered
view appears.
3. Use the File Path group to find the directory in which the [Link] file is saved in. Once you find the DLL, select it
and click the OK button.
The Extensions tab now appears similar to the figure below.

Figure 3.50

4. You can now go in to the main Simulation environment and from the UnitOps view find the Saturate Extension in

- 121 -
Chapter 3 - Extensibility

the Available Unit Operations list.

Figure 3.51

3.11 References
"An Industrial Design/Control Study for the Vinyl Acetate Monomer Process", Luyben & Tyreus, p.4.

- 122 -
CHAPTER

4 EXTENSION VIEW EDITOR

4.1 Introduction
The View Editor can be used to create or modify Extension Definition Files (*.edf). Users that are accessing the automation
and extension capabilities of UniSim Design generally make use of EDF files. The extension definition file acts as the
interface view within UniSim Design as well as the point for variable declaration and storage.

Figure 4.1

4.1.1 Accessing the View Editor


Access to the View Editor is provided with each commercial release of UniSim Design. However, it is not available unless
you have selected the Extension SDK option during the UniSim Design installation.

TIP
The Extension Development SDK files option is not activated by default as it requires additional hard drive space.

- 123 -
Chapter 4 - Extension View Editor

Figure 4.2

During the installation procedure, UniSim Design adds the [Link] application to the directory that currently holds your
UniSim Design files. You can access the View Editor by either:

l Selecting the View Editor option in the Start menu where it should reside in the same launch group as UniSim
Design.
l Finding the directory name used to store your UniSim Design files and double-clicking on [Link] in File
Manager or Windows Explorer.

The View Editor appears as shown below:

Figure 4.3

- 124 -
Chapter 4 - Extension View Editor

You can now either open an existing EDF or create a new EDF.

4.1.2 Creating a New EDF File


Once the View Editor has been accessed, you can create a EDF by following this simple procedure:

1. Do one of the following:


l Select New command under File menu in the menu bar
l Use the hot key combination CTRL N

l Click the New File icon

The Views Manager view and the Widgets Palette appears as shown in the figure below.

Figure 4.4

2. Assuming, at this time, that only one view exists for this EDF file, click the Edit button to open the DefaultView form.

- 125 -
Chapter 4 - Extension View Editor

Figure 4.5

The DefaultView form contains three widgets: Text Entry widget, StaticText widget, and Page Tabs widget.
3. Delete these widgets if you do not require them. To delete a widget, simply click on the widget and do either of the
following:
l Right-click the widget and select the Delete command from the Object Inspect menu.
l Press the DELETE key.

4. Place the widgets you want on the DefaultView form and, if needed, modify the widget properties.
5. Move and resize the widgets if required.

6. Save your work by clicking the Save View File icon and providing an appropriate name for the EDF file.

4.1.3 Editing an Existing EDF File

TIP
To edit an existing file, its ‘write’ attribute must be enabled (it cannot be read-only).

1. To open an existing EDF file, do one of the following:


l Select Open under File in the menu bar.
l Use the hot key combination CTRL O.

l Click the Open View File icon .

2. Select the EDF file from the Open View File view and click the Open button.
3. Edit the EDF file and save the file before exiting the program.

- 126 -
Chapter 4 - Extension View Editor

4.2 Using the View Editor


4.2.1 Manipulating Widgets
[Link] Adding Widgets

You can add a widget to your view by using the following procedure:

1. Select the widget you want to add in the Widgets Palette.


2. Right-click, hold, and drag the widget to the location on the view where you want to place it.

3. When the widget can be properly placed on the view, the cursor changes to a Bull’s Eye . Release the mouse
button and the widget appears on the view.

The default sized widget appears on the DefaultView form where you released the mouse button. Re-sizing handles are
shown around the border of the widget, when the widget is selected.

Alternate Approach

An alternate approach to the above steps #2 through #3 is to check the Lock checkbox found at the bottom of the Widgets
Palette. Once checked, the mouse cursor changes in to a cross-hair cursor whenever the mouse cursor is placed over the
DefaultView form. You can then use the cross-hair cursor to draw the currently selected widget in the Widget Palette by
clicking and dragging the cursor in the DefaultView form.

With the Lock checkbox checked, you can add multiple widgets of the same type simply by clicking on the DefaultView form
multiple times.

- 127 -
Chapter 4 - Extension View Editor

Figure 4.6

[Link] Deleting a Widget

To delete a widget simply select the widget and do one of the following:

l Press the DELETE key.


l Right-click the widget and from the resulting Object Inspect menu, select the Delete <Widget Type> command.

[Link] Re-sizing a Widget

To re-size the widget using the mouse:

- 128 -
Chapter 4 - Extension View Editor

1. Select the widget.


2. Place the cursor over one of the re-sizing handles.

TIP
Notice the cursor changes to a double- headed arrow.

3. Hold down the primary mouse button and drag in one of the directions indicated by the double-headed arrow.

Figure 4.7

You can also select multiple widgets by dragging a frame around the widgets of choice or by selecting individual
widgets while holding down the CTRL key. You can then simultaneously resize all selected widgets by resizing the
anchor widget, which is the widget displayed with the resizing handles.

To re-size the widget using the Properties view:

1. Open the widget’s Properties view.


2. On the widget’s Properties view, enter the new width and height of the widget in the XY table shown in the figure
below.

Figure 4.8

[Link] Moving a Widget

To move a widget:

- 129 -
Chapter 4 - Extension View Editor

1. Select a widget.

TIP
You can also select multiple widgets by dragging a frame around the widgets of choice or by selecting
individual widgets while holding down the CTRL key.

2. Hold down the primary mouse button and drag the widget to a new location.

4.2.2 DefaultView Form Toolbar


When you are creating a new view or editing an existing view, there is a toolbar containing buttons on the DefaultView form.
These buttons can be used to access some of the widget properties without opening the particular widget property view.

[Link] Active Location Settings

Tab Order Icon

When this icon is clicked, an integer value appears over each widget on the DefaultView form that can capture the focus. The
sequence of the integer values determines the order in which the widgets attain the focus when the TAB key is pressed.

As widgets are placed on the DefaultView form, the View Editor assigns the next available integer value to the new widget. It
is possible for you to change the tab order that is assigned to the widgets.

A UniSim Design valve property view is shown in the figure below and it is used to demonstrate the re-arranging of the tab
order.

Figure 4.9

The tab order is indicated by the integer values in the black dots covering the widgets. From the Name field (#6), pressing
TAB moves the focus to the Ignored checkbox (#7), then to the Delete button (#8) and so on.

Notice that static text widgets such as Name, Inlet and Outlet also receive tab order values. These values should always be
one below the value on the widget with which the static text is associated. This enables the associated widget to get the focus
when the static text hot key is pressed. For example, when the user presses ALT N, the focus should be in the text entry cell
where the name can be input. Since the static text Name widget (#5) cannot accept the focus, the next integer value is used
(#6).

- 130 -
Chapter 4 - Extension View Editor

There are two approaches to changing the tab order. You can click either the Select #1 or the Select Sequentially button.
The following sections describe each buttons in detail.

Select #1 Button

When you click this button, the View Editor allows you to select a different widget to carry the value #1 in the tab order. When
a new #1 is selected, the tab order remains the same, but the integer values are rotated to accommodate the new #1
selection.

For example, if you clicked the Select #1 button for the valve view shown previously, and then selected the Text Entry Outlet
widget (current #3), this widget would become #1. All other widgets would have their integer values increase by 1 with the
old #1, the Static Text Inlet widget, becoming #8 (as shown in the figure below).

Figure 4.10

If this new order was not what you wanted, you could continue with a user selected order. Notice the Select Sequentially
button has changed to a selected Select #2 button. So you can select the widget that you would like to be #2 in the tab order.
After you select a widget to by #2, the Select #2 button changes to Select #3 button. So you can choose the #3 widget in the
tab order. The sequence number button increase with each selection until the highest number has been designated to a
widget.

When the highest number (like number 9 from the figure above) has been designated, the sequence number goes back to #1
and you can resequence the view again. You can keep resequencing the tab order until the Tab Order icon is clicked again or
the view is closed.

Select Sequentially Button

When you click the Select Sequentially button, the View Editor allows you to select a current widget tab order value which
begins the sequence of values for changes. For instance, if you clicked this button and then clicked the #4 widget, the Select
Sequentially button would change in to a Select #5 button. Once you selected the widget that you would like to be #5 in the
tab order, the button would change to a Select #6 button. This continues until the Tab Order icon is clicked again or the view
is closed.

- 131 -
Chapter 4 - Extension View Editor

[Link] Sizing Icons

Stretch Width

Clicking the Stretch Width icon toggles the X-direction Stretch checkbox (found in the widget’s Properties view) for the
selected widget. When the Stretch checkbox is checked, the width of the widget increases as the DefaultView form is
expanded horizontally. Stretching is related to the Tie To Corner and the Tie Reference properties.

Stretch Height

Clicking the Stretch Height icon toggles the Y-direction Stretch checkbox (found in the widget’s Properties view) for the
selected widget. This icon is disabled for those widgets that are not designed to stretch vertically (vertically-challenged
widgets). When the Stretch checkbox is checked, the height of the widget increases as the DefaultView form is expanded
vertically. Stretching is related to the Tie To Corner and the Tie Reference properties.

[Link] Alignment Icons

These icons are disabled unless you select multiple widgets on a DefaultView form. The icons that become available
depends on the orientation of the widgets that you have selected.

For instance, if you select two static text widgets, one being below the other, the icons that become available allow you to
choose a left, centre or right alignment according to the widget that is chosen as the anchor widget.

Figure 4.11

The anchor widget is the widget that serves as the basis for alignment and is identified by the resizing handles around its
outline. The other widgets in the group selection become the widgets that are moved. To change the anchor widget, simply
select another of the selected widgets. This changes the selected widget’s outline from the solid black line to a thinner outline
with resizing handles.

The Alignment icons that are available:

Name Description Icon

Align to Lines up the selected widgets according to the leftmost point of the anchor widget.
Left

Align to Lines up the selected widgets according to the rightmost point of the anchor widget.
Right

- 132 -
Chapter 4 - Extension View Editor

Name Description Icon

Align to Lines up the selected widgets according to the topmost point of the anchor widget.
Top

Align to Lines up the selected widgets according to the bottommost point of the anchor widget.
Bottom

Align at There are two of these icons, although only one is shown at any given time. The one that appears
Centre depend on the orientation of the selected widgets.
Clicking the icon lines up the selected widgets according to the centre point of the anchor widget,
either in a vertical (X-axis centre point) or horizontal (Y-axis centre point) fashion, depending on the
icon being shown.

Equally There are two of these icons, although only one is shown at any given time. The one that appears
Space depend on the orientation of the selected widgets.

For this icon to become available, at least three widgets must be selected. Clicking the icon vertically
or horizontally spaces the widgets, depending on the icon being shown.

4.2.3 Visibility Manager


The Visibility Manager is used when you want to show or hide certain parts of your view at specific times. In other words, it
allows you to discretely select what is to be shown based on the conditions of the view (i.e., static - done by the view
designer) or the state of the application (i.e., dynamic - manipulated through code).

For instance, many UniSim Design views have tabs along the lower part of the view which enable different information to be
grouped and shown at different times. When the second tab on a view is selected, the information from the first tab is typically
hidden and the information specific to the second tab is shown.

Figure 4.12

Although the Visibility Manager is used mainly with tabs, it can be used with other widgets. Other selection devices, such as
radio buttons and checkboxes can prompt the use of this tool to selectively show and hide information.

The Visibility Manager can be accessed by right-clicking anywhere on the DefaultView form and selecting the Open Visibility
Manager command from the Object Inspect menu.

The Visibility Manager largely consists of the Create Controller button and the controls you have created. A control is
denoted by the presence of a group containing an Edit and Delete button. Each control allows you to create States, or
instances when widgets or events occur. The default view of the Visibility Manager, shown in the figure below, consists of a
default PageController control which controls the visibility of the two tabs.

- 133 -
Chapter 4 - Extension View Editor

Figure 4.13

An example, if you were to select the Page2 radio button, you would see the Page 2 tab. Only the widgets placed on this tab
would automatically set to be visible on the tab in the DefaultView form.

Clicking the Create Controller button adds a new controller group to the Visibility Manager view. The name of the control is
the name shared by the group. You can delete a controller by clicking the Delete button associated with the controller group.
You can also edit the controller by clicking the Edit button.

Figure 4.14

Clicking the Edit button opens the Visibility Controller Properties view.

Figure 4.15

The Visibility Controller Properties view is where individual object states are set. The view consists of 10 objects:

Object Description

Name The controller name. The name entered in to this field is the name of that appears in the Visibility
Manager.

Moniker Clicking the Ellipsis icon associated with this field, opens the Select Number Variable view. You can
select the moniker type you want to associate to the controller using the Select Number Variable view.
See Moniker Specification sub-section from Widget Properties for more information.

States This group has three different fields that require specification:

l Name. The name of the state. This appears as a radio button in the controller group on the Visibility

- 134 -
Chapter 4 - Extension View Editor

Object Description

Manager view.
l Low. The low value for the state.
l High. The high value for the state.

Insert State Click this button to add a new state to the list.

Delete Select a state and click this button to delete the currently selected state.
State

Apply Click this button to apply any changes made on the Properties view to the Visibility Manager view.

Select Click this button to open the Visibility Controller Widget Selections view which allows you to associate
Widgets widgets with the state.

Activation Click this button to open the Visibility Controller Activation view which allows you to create a hierarchy of
visibility states.

[Link] Using Tabs

A view created through the View Editor can contain multiple tabbed sections within the same view. Double-clicking on the
tabs of a view opens the tab Properties view. Labels are added for each new tab to be displayed.

1. To add a tab to a view, right-click, hold, and drag the Page Tab widget from the Widget Palette into the DefaultView
form.
2. Resize the tab size to your specifications.

Figure 4.16

3. Right-click the DefaultView form background and select Open Visibility Manager command from the Object
Inspect menu.

Figure 4.17

4. The Visibility Manager view appears. Click the Create Controller button.
5. A VisController group appears above the Page Controller group as shown in the figure below.

- 135 -
Chapter 4 - Extension View Editor

Figure 4.18

6. Click the Edit button in the VisController group, to open the Visibility Controller Properties view.

Figure 4.19

7. Click the Ellipsis icon associated with Moniker field to open the Select Number Variable view.
8. Select Current Page from the list in the Select Number Variable view, and click the OK button.

Figure 4.20

9. Enter a name for the first tab in the Name column of the States group.
10. Enter an integer value in the Low and High cells beside the Name cell from the above step. The integer value for both
Low and High cells have to be the same.

- 136 -
Chapter 4 - Extension View Editor

If the values entered for the Low and High cells is not for the first tab, increment the values by one for each tabbed
sheet (i.e., High and Low for first tab is 0, High and Low for second tab is 1).

Figure 4.21

NOTE
It is required that the High/Low values provided (in #10) for each tab match the Value for each tab in the Static
Tabs group of the tab Properties view. It is highly recommended that you match the tab Name (#9) in the
Visibility Controller Properties view with the Label in the tab Properties view.

11. Repeat #9 and #10 for each tab.


12. Click the Select Widgets button. Check the checkbox under the appropriate tab name for each widget that appears
only on that tab. For widgets that appears on all tabs, do not check any checkboxes.

Figure 4.22

High and Low Integer Values

The values for High and Low in the Visibility Controller Properties view do not always have to be the same. You can use the
Visibility Manager to selectively show widgets according to values in the application. For example, if you want to show a static
text widget when the pressure of a specific stream was between 150 and 200 kPa, you could specify the moniker
representing the stream pressure in the Moniker field of the Visibility Controller Properties view and then use the Low and
High cells to specify the pressure range.

- 137 -
Chapter 4 - Extension View Editor

4.2.4 The Objects Manager View


The Objects Manager provides a view in which you can enter crucial information related to extensions. This information is
used to register an extension properly and to declare the variables and objects used by the extension.

You can access the Objects Manager view by either:

l Clicking the Objects Manager icon on the Views Manager view.


l Selecting Objects Manager under View in the menu bar.

Figure 4.23

[Link] Object Definition Matrix

The Object Definition matrix consists of four columns:

Column Description

ProgID/ The entry in this cell identifies the name of the object that owns the views shown in the Existing Views
CLSID group of the Views Manager view. This information must match what is in the registry and is used by
UniSim Design to access the proper DLL file.

Description This is the text that appears in the appropriate location within UniSim Design in order to select the
extension.

Type This specifies the type of extension. The choices include:

l Unit Operation
l Property Package
l Kinetic Reaction
l Exchanger Design, Base
l Exchanger Design, End Point
l Exchanger Design, Simple
l Exchanger Design, Weighted
l DeltaP (Pressure Drop) Correlation
l Sim Case Translator
l ExternalAddIn
l Pipe Deposition Correlation
l Property Balance
l Mixing Rule

- 138 -
Chapter 4 - Extension View Editor

Column Description

This selection impacts the list of internal Honeywell variables that are visible when the Ellipsis icon is
clicked on a widget Properties view.

Views The number of views associated with this extension.

[Link] Attributes of Selected Object Group

The Attributes of Selected Object group allows you to transfer the attributes of operation types to your unit operation
extension. This allows you to find your extension unit operation not only under the Extension categories but also under the
category of the operation whose attributes you have selected. For instance if you add the attributes of the Reactor to your
extension, when you want to find your extension in the UnitOp view, you are able to find it by selecting either the Reactors or
Extensions radio buttons.

[Link] Variables of Selected Object Group

In the Variables of Selected Object group, you can specify all variable- related information for the selected object in the
ProgID/CLSID cell. Once these variables are created, you can use them as monikers to associate a particular variable with a
widget on your view. Variables are defined in the table that contains three columns:

Column Description

Tag Represents the internal name of the variable that is stored to disk (usually input as the same as Name). You
cannot have 2 identical tags for the same object.

Name Represents the variable name which is visible on views in the program (usually the same as Tag). This name
should be unique such that you can identify it in the program. Unlike the Tag, spaces are allowed in this text
string.

Type Variable types include:

l Real Number. Numeric variable for which you can specify the dimensions and unit type.
l Enumeration. A related set of identifiers, each of which is associated with an integer value; you can
specify the dimensions and create the enumeration through the Enumeration Values button.
l Text. A string variable for which you can specify the dimensions.
l Attachment. Represents a variable associated with an object that is attached to another object (i.e., a
feed stream is attached to the inlet of a pump, so the feed stream name is of type Attachment); allows you
to specify the dimensions, attachment type and flow direction.
l Message. A variable holding information passed when a button is clicked.

The group also consists of several additional objects that, depending on the type of the currently selected variable in the
matrix:

Object Description

Persistent Check this checkbox if you want this variable value to be saved with the simulation case. Pertains to all
variables except Message variables.

Triggers Solve Check this checkbox if you want changes in the variable to set off a smart solve (solve whatever needs
to be solved). The checkbox is enabled for all variables ONLY when the object in question is a Unit
Operation. For Real Number and Enumeration types, this checkbox is checked by default.

Attachment For Attachment variables, you can specify the attachment type as one of the following:
Type
l Stream. Generic specification, implying that the stream can be either material or energy.
l Material Stream. The attachment is a material stream and cannot be an energy stream.

- 139 -
Chapter 4 - Extension View Editor

Object Description

l Energy Stream. The attachment is an energy stream and cannot be a material stream.

Flow Direction The choice for Flow Direction impacts the PFD in its presentation of nozzles for unit operations in
Attach Mode. For Attachment variables, you can specify the flow direction as one of the following:

l Unknown. The PFD does not know until run-time if the attachment is a feed or product; depends if
the attachment is already attached to something.
l Feed. Only feed nozzles are presented by the PFD.
l Product. Only product nozzles are presented by the PFD.
l Unknown (any flowsheet). Accepting objects from any flowsheet in case; otherwise, same as
Unknown.
l Feed (any flowsheet). Only feed nozzles from any flowsheet in case.
l Product (any flowsheet). Only product nozzles from any flowsheet in case

Numeric Type For variables of type Real Number, a unit type can be specified. This guarantees that the appropriate
value appears by the view according to the user specified unit set.

N Dimensions For all variable types except Message, the variable dimensions can be specified as one of the following:

l None. Single value.


l Vector. One dimensional array.
l Matrix. Two dimensional array.
l Cube. Three dimensional array.
Only the Real Number variable type has access to all dimension types. The other variable types have
access to only None and Vector.

Offset Tags For variables that are Vector or Matrix, optional Offset Tag variables may be chosen in order to provide
specific offset names when user is browsing for variables. The Offset Tags Var field appears for
vector or matrix variables and the chosen text vector variable should hold descriptions for entries (or
rows in matrix). The Offset 2 Tags Var field appears just for matrix variables and; likewise, the
chosen text vector variable should hold descriptions for columns in matrix.

Enumeration When you click the Enumeration Values button, the Enumeration Values view appears (as shown in
Values Button the below figure), on which you can create your enumeration. Simply enter the labels and the integer
values with which the labels are associated.

Auto- The AutoCompress attribute of an extension array variable will automatically remove NULL values
Compress from the array.
Vector
Specifically, assigning a value of NULL to an entry in the array will remove that entry and shorten the
array.

- 140 -
Chapter 4 - Extension View Editor

Figure 4.24

4.2.5 Views Manager


The View Manager view consists of two groups: View File and Selected Object.

Figure 4.25

NOTE
Each *.edf file can have an unlimited number of objects associated with it, each of which can have an unlimited number
of views.

Selected Objects Group

The Selected Object group consists of a drop-down list with an associated Objects Manager icon and the Existing Views
list. The drop- down list allows you to select one of the objects defined in the Objects Manager view. The Objects Manager
icon opens the Objects Manager view.

The Existing Views list displays all of the existing views associated with the selected object.

From the Views Manager view, you can click any of the buttons that pertain to the Existing Views list:

Button Description

Edit Opens the selected view and the Widget Palette.

Test Allows you to test the view.

Add Adds a new view to the object.

Copy Creates a copy of the selected view.

Remove Removes the selected view from the object.

4.3 Widget Properties


As mentioned earlier in this guide, a view is the interface seen within the UniSim Design environment. Views can contain
several tabs and pages of information. The controls placed on the view are referred to within the View Editor as widgets.
These include many of the typical control features associated with windows programs such as text fields/ cells, checkboxes,
drop-down lists, buttons, etc.

- 141 -
Chapter 4 - Extension View Editor

The Properties view of a specific widget can be accessed by either:

l Double-clicking on the widget


l Right-clicking the widget and selecting <Widget Type> Properties command from the Object Inspect menu, where
Widget Type would be the Button for a button widget.

The properties of the DefaultView form itself can also be accessed in either of the aforementioned ways.

When dealing with the properties of a widget and where applicable, you can access options for the cell/field by clicking the
Ellipsis icon . A view is presented from which you can make a selection that is appropriate for the widget property.

For extensions, the most important feature involves associating the widget item to a particular variable declared in the
Objects Manager view. This is accomplished through the Moniker, which is another name for a variable. For most widgets
the Target Moniker option is used to assign a specific variable to the widget.

Common widget properties are discussed in the next section, followed by widget specific properties. In the section describing
the specific widget properties, an example of each widget (as well as its respective Properties view) is shown.

4.3.1 Moniker Specification

Moniker (or variable) specification is usually done via the Ellipsis icon that is usually associated with the moniker field.
There are usually three types of monikers specified:

Variable
Description
Type

Number Numerical variables are selected via the Select Number Variable view which appears when the Ellipsis
Variables icon is clicked. These variables:

l Represent numerical quantities and have a Variable Type that allows UniSim Design to manage Unit
Conversions for the user.
l Can have zero, one, or two dimensions.
l Can trigger the steady state solver when they are changed. If this is the case, the variable operates like
other UniSim Design variables in that the solver performs consistency checking when values are
changed.

Text Text variables are selected via the Select Text Variable view which appears when the Ellipsis icon is
Variables clicked. These variables:

l Represent string quantities.


l Can be zero- or one-dimensional.

Message Text variables are selected via the Edit Messages view which appears when the Ellipsis icon is clicked.
Variables These variables do not represent any particular quantification, but can be associated with buttons in a
view. Messages are sent through the VariableChanged method of an extension.

The Select Number Variable and Select Text Variable view are very similar in their appearance and operation. Both consist
of a list that displays the available variables in the variables set (or sub-set) selected in the Base Object drop-down list.

- 142 -
Chapter 4 - Extension View Editor

Figure 4.26

The Base Object drop-down list contains variable sets and sub-sets. The drop-down list acts as a path to object and object
sub-sets. The default option is the <Form’s Base Object>.

Notice the angle brackets around the Form’s Base Object. This indicates that the options appearing below it in the drop-
down list are all variable sub-sets. For example, the options that appear below the Form’s Base Object option are all variable
sub-sets of the DefaultView form. If such a tributary option is selected, the drop-down list hierarchy immediately changes.
While the selected option appears in the field, when the drop- down list appear, the selected variable sub-set appears just
below the Form’s Base Object option surrounded by square brackets. Drop-down list options that appear above the current
selection allow you to return to a higher level of the variable hierarchy. The options that appear below are in turn sub-sets of
that selection. The display field that appears above the list displays the variable set path.

An example, suppose a stream variable was selected in the Base Object drop-down list. As shown in the figure below,
FeedStrm, the material stream selected, appears in the display field.

Figure 4.27

The list above the Base Object drop-down list displays all variables that belong to this sub-set. Selecting the drop-down list
shows that the list has changed. The <Form’s Base Object> option is placed at the top of the list. If you wanted to return to a
higher level of the object hierarchy you would select this option. Below it is the current selection in the field, FeedStrm, in
square brackets. The options that appear below the Feedstrm option are all variable sub-sets of the material stream variable
set.

- 143 -
Chapter 4 - Extension View Editor

4.3.2 Common Widget Properties


Each of the widgets listed in the Widgets Palette has a set of common properties listed on its respective Properties view.
Even though all widgets have access to these properties, not all of the listed properties apply to all widgets. The common
properties are shown in the figure below and described in the table:

Figure 4.28

Object Description

Name Each widget is named automatically when it is placed on the DefaultView form. You can replace the
default name with one that is more descriptive or meaningful.

Fly By Place text in this field to have a message appear in the UniSim Design status bar and/or as a tool tip
when the cursor is placed over the widget. The ‘\n’ (newline sequence) is used to differentiate status bar
output and tool tips. Multiple newlines allow for multi-line tool tips.
For example, with the Fly By input of “Performs an action.\nThe sky is blue”, the message to the left of
the newline sequence, “Performs an action”, would appear in the status bar and the message to the
right of the newline sequence, “The sky is blue” would appear as a tool tip. If the newline sequence is not
used, the whole message appears in the status bar.

Position The X and Y values represent the co-ordinate values of the top left corner of the widget with the
reference point being the top left corner of the DefaultView form. Co-ordinate units are 1/8 of a
character for the Y direction or height and 1/4 of a character for the X direction or width, where the
character in question is of the size seen on a button widget.

Size The X and Y values represent, respectively, the horizontal and vertical size of the widget. Co-ordinate
units are 1/8 of a character for the Y direction or height and 1/4 of a character for the X direction or
width, where the character in question is of the size seen on a button widget.

Stretch When the X-direction Stretch checkbox is checked, the width of the widget increases as the
DefaultView form is expanded horizontally. When the Y-direction Stretch checkbox is checked, the
height of the widget increases as the DefaultView form is expanded vertically.
Stretching is related to the Tie To Corner and the Tie Reference properties.

Background Double-click the field to opens the Select A Colour view. The Select A Colour view allows you to select
Colour the background colour of the widget from all listed internal widget colours.

Enable Allows you to provide or select a variable that allows you to control whether or not the widget is
Moniker disabled/enabled (greyed out or normal) at certain times. When the variable is true, the widget is
enabled.

On False Check this checkbox to force a reverse effect for the Enable Moniker variable. The widget is enabled
when the selected variable is false.

Tie To Corner Select one of the radio buttons, which represents the corner to which the widget is bound. If the
DefaultView form is stretched, you may want the widget to remain stationary relative to a certain corner
of the DefaultView form. For example, a button that is placed near the lower right corner of the
DefaultView form can have the lower right radio button selected. So the button is always the same
distance from the lower right corner of the DefaultView form if the DefaultView form is stretched
vertically or horizontally.
This property is dependent on the selection for the Tie Reference property as well as the Stretch

- 144 -
Chapter 4 - Extension View Editor

Object Description

properties.

Tie From this drop-down list, you can choose another widget to which the currently selected widget is
Reference bound. This can be useful when you do not want to have stretching widgets overlap on a DefaultView
form. Otherwise, use the default selection, which is the DefaultView form.

OK Click this button to close the widget’s Properties view and accept the properties setting in the Properties
view for the widget.

Cancel Click this button to close the widget’s Properties view without accepting any current changes made to
the properties setting on the Properties view.

Apply Click this button to apply changes to the widget without closing the widget’s Properties view. This button
is only available after you made at least one change to the properties setting.

Visibility The Visibility button opens the Widget Visibility Control view, which is similar to the Visibility Controller
Properties view. Refer to the Visibility Manager.

4.3.3 DefaultView Form Object


The DefaultView form object has its own set of properties that control the appearance and functions performed by of the
DefaultView form. To view and change the attributes associated with the DefaultView form you must access the Object
Inspect menu of the DefaultView form.

Figure 4.29

[Link] The DefaultView Form Object Inspect Menu

The DefaultView form Object Inspect menu has five commands:

Menu Option Description

Form Opens the Form Properties view of the DefaultView form. For more information of this view see the
Properties following Form Properties View sub-section.

Open Opens the Visibility Manager view, from which you can create controllers. Refer to the Visibility
Visibility Manager for more information.
Manager

Snap Grid This option offers a sub-menu from which you can enable and disable snapping to the DefaultView form
background (Snap All, Snap Selected, Disable), hide the snap grid or resize the grid (2x2, 4x2, 4x4). The
default is a 2x2 grid with snapping enabled.

Test Select this to view a test of your DefaultView form. Normally, this option is used to test the visibility options

- 145 -
Chapter 4 - Extension View Editor

Menu Option Description


for widgets on the tabs and the resizing of the DefaultView form (i.e., stretching and tying of widgets).

Revert Selecting this option allows you to undo all changes since your last saved version for the active view only.

Form Properties View

The DefaultView form is the only object that has a unique properties layout. It does not have the common properties listed
previously.

Figure 4.30

The following table contains a description of the objects in the Form Properties view.

Object Description

Form Title The text entered in this field, appears in the title bar of the DefaultView form. The default is a format
string (%s) that simply uses the object name.

Name Source Allows you to choose from a list of sources for the DefaultView form name. By default, the object name
is the source.

Help Panel This entry provides a link between the view and the help system, such that a certain help topic appears
when F1 is pressed and the particular view has focus. For extensions, this is normally left blank.

Form Icon The choice of icon appears in the upper left corner of the DefaultView form. Double-clicking on the icon
brings up a view from which you can choose an icon from a list of internal UniSim Design icons.

Background Double-clicking on the associated cell brings up a view from which you can choose a DefaultView form
Colour background colour from a list of UniSim Design colours.

Form Style In this group, you can choose one of the radio buttons that assigns characteristics to the DefaultView
form:

l Normal. A DefaultView form similar to most property view in UniSim Design.


l Modal. A DefaultView form that always stays on top of others and does not allow access to other
views until it is closed or de- pegged; can be pegged or not, depending on the Peggable checkbox
selection.

- 146 -
Chapter 4 - Extension View Editor

Object Description
l Floating. A DefaultView form similar to the object palette, that remains on top but does not restrict
access to other views.

The following checkboxes are also within the Form Style group:

l Small Caption. Activating this checkbox reduces the height of the caption area to that of a UniSim
Design face plate or the object palette. The checkbox is available as a choice only to Normal style
views. The checkbox is checked by default for Floating style views.
l Peggable. Activating this checkbox allows a modal DefaultView form to become non-modal by
placing a peg in the upper right corner of the view. The checkbox is available to Modal style views
only.
l Cached Data. Activating this checkbox allows changes to be made on the DefaultView form
without the object below knowing it until the time when: FlushCache is called; this allows a user to
make changes to the DefaultView form and then click Cancel without having the changes accepted;
an example of using this is on the New Object Type form, which can be accessed from the Setup
view of the Workbook. The OK button sends both the FlushCache and CloseView messages. The
checkbox is available to Modal style views only.

Action Allows you to specify a message to be sent, much like when a button is clicked, but in this case, when
Messages the user double-clicks the background of the DefaultView form (Double Click), opens the DefaultView
form (Form Open) or closes the DefaultView form (Form Close). Clicking the Ellipsis icon brings up
a view on which you can add, edit or delete the messages.

Form Default Select a button name from either the Enter or Escape drop-down list to have the button display its
Buttons message when either the ENTER key or ESC key is pressed, respectively. Normal use is having the
ENTER key associated with a Close button and having the ESC key associated with a Cancel button.

The Enter drop-down list is available with Normal and Modal DefaultView forms, while the Escape
drop-down list is only available for Modal DefaultView forms.

File/Print The Widget to Print drop-down list allows the selection of a particular widget on the DefaultView form to
Override be printed instead of the whole DefaultView form. The drop-down list changes the way Print command
under the File menu works. An example of its use is on the PFD. When the PFD is printed, all you get is
the PFD, not its toolbar, tabs or the DefaultView form surrounding the PFD.

Borders Allows you to specify the distance that the top, bottom, left, and right edges of the DefaultView form are
from the outermost widgets. The minimum size of the DefaultView form is dictated by the placement of
the widgets on the DefaultView form.

Units of measure are 1/8 of a character for the height and 1/4 of a character for the width, where the
character in question is of the size seen on a Button widget.

Advanced When you click the Advanced button, the Advanced Form Properties view appears.

- 147 -
Chapter 4 - Extension View Editor

Object Description

Figure 4.31

The following are options available in the view:

l Can Open Multiple. If not checked, the existing DefaultView form is always opened; if checked,
the action of opening the DefaultView form opens a new instance each time.
l Preserve Placement. If checked, the DefaultView form re- opens in the same location where it
was before it was closed.
l Can Crop Width. If checked, allows you to resize the view to a width smaller than minimum
required width. The minimum required width value is set to show all the widgets on the view.
l Can Crop Height. If checked, allows you to resize the view to a height smaller than minimum
required height. The minimum required height value is set to show all the widgets on the view.
l Use Crop Scroll Bars. This option only makes sense with one or both of the above crop settings
checked. The cropped scroll bars appear to allow you access at the cropped area of the view.
l Disable Close. If checked, UniSim Design greys out the Close icon and the close option from
the Object icon menu. UniSim Design still allows CloseView messages.
l Page Limits. This group contains options that allow you to specify a widget which serves as the
page bottom or top reference point. These values control where the page’s bevelled edges are
drawn. Usually, the top is left blank and the bottom is specified as a tabs widget.
l Suggested Size. This group contains fields that allow you to enter width and height values for a
useful size, which can be larger than the minimum DefaultView form size; minimum DefaultView
form size is, as described previously, a function of the widget placement on the DefaultView form.

4.3.4 Button Widget


The button widget is used to send specific instructions to its base object when it is clicked by the user.

The Button Properties view appears as shown in the figure below.

- 148 -
Chapter 4 - Extension View Editor

Figure 4.32

TIP
To access the Button Properties view do one of the following:

l Double-click the button widget.


l Right-click the button widget, and select the Button Properties command from the Object Inspect menu.

[Link] Button Properties

The properties available for a Button widget are described in the table below:

Object Description

Label Whatever is entered in this field, is shown on the face of the button. Place an ampersand (&) before the
character that gets the hot key (underscore) designation.

Message This is the command(s) that will be executed/fired when the button is clicked. Common examples include:
Delete and CloseView. You can click the Ellipsis icon to access the Edit Messages view, which provides
a list of the current messages that are being used for the particular button. From this view, you can add new
messages, delete existing ones, edit the list or re-arrange the order in which the messages are fired. If you
have created variables of type Message in the Objects Manager, these are available for addition to the Edit
Messages view.

Source Allows you to choose a widget that provides required information when the button is clicked. It is used to
Widget ‘populate’ the arguments for the Message.

For example, the Simulation Basis Manager view shows a list of fluid packages in the Current Fluid
Packages group. The View button opens a fluid package according to the selection made in the Current
Fluid Packages group. Thus the text list widget (list of fluid packages) acts as a source widget for the View
button.

Target Allows you to choose a widget which holds a collection of objects. The selected object or multiple selected
Widget objects will be affected by the clicking of the button.

This is illustrated by the Delete button. This button has the attachments list widget, which displays all of the
column specifications, as its target widget. By clicking the Delete button, you are indirectly affecting the
attachments list widget by passing the: Delete message to a particular Specification object. The target
widget is not deleted, but is updated after the selected Specification object is deleted.

- 149 -
Chapter 4 - Extension View Editor

Object Description

Requires Activating this checkbox limits selection in the source widget to a single item. Continuing the example cited
Single in the Source Widget discussion, activating this checkbox allows you to select only a single fluid package in
Source the list.

Requires Activating this checkbox limits selection in the target widget to a single item. If the button deletes items from
Single a list, you may want to limit the user to only a single deletion per button click.
Target

4.3.5 Static Text Widget


Use this widget to show read-only text on the application’s view.

Figure 4.33

[Link] Static Text Properties

The properties available for a Static Text widget are described in the table below:

Object Description

Type of Select one of the radio buttons to specify the type of static text widget:
Text
l Fixed. Makes the Fixed Text field available. An example of the use of this radio button is the
descriptive text seen beside a numerical input field.
l Source. Makes the Source Moniker field and Source Widget drop-down list available. An example of
the use of this radio button is the status text seen at the bottom of each unit operation property view.
There is also a Framed checkbox that you can checked if you want the static text widget to have a frame.
Unframed static text widgets can usually be seen next to numerical or text input widgets. An example of a
framed version is the status text for each unit operation.

Fixed Text This is available only when the Fixed radio button is selected. Allows you to enter a string in the Fixed Text
input field that does not change at run-time.

Source This is available only when the Source radio button is selected. Allows you to select a text variable that
Moniker provides the string for the static text widget. Any variables of type Text that you have set up in the Objects
Manager are available when you click the Ellipsis icon . For a UniSim Design property view status bar,
the usual selection is Description of Highest Status Condition.

Source Available only when the Source radio button is selected. This is rarely used in UniSim Design, but it allows
Widget you to choose a widget that supplies the static text with information. For example, you could select the

- 150 -
Chapter 4 - Extension View Editor

Object Description
tabs widget and have the tab label appear in the static text widget.

Alignment Select a radio button to determine the justification of the text in the static text widget. Choose Left, Centre,
or Right.

Colour Allows you to select a variable that determines the background colour of the static text widget at run time.
Variable Click the Ellipsis icon for current options. For a UniSim Design property view status bar, the usual
selection is Colour for Current Status.

Ellipsis The selection in this drop-down list instructs the static text widget how to show its information when the
Style text is too long to be fully shown. This should only apply to Source text, not Fixed text, since you know the
length of fixed text and can adjust the size of the widget to accommodate it. You can choose from three
available options:

l None. The text is cropped according to the widget size.


l Path. Applies to file names; as much of the path name as possible is shown; for instance, the path
c:\program files\UniSim Design\cases\[Link] may be shown as c:\,...\cases\[Link].
l End. As much as possible is shown with an ending … if the text cannot fit.

4.3.6 Text Entry Widget


Use this widget to allow the user to input text on the view.

Figure 4.34

[Link] Text Entry Properties

The properties available for a Text Entry widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Text that you have created in the Object Manager.

Message This is the command(s) that will be executed/fired when the ENTER key is pressed or the space bar is
pressed, depending on the radio button selection in the Send Message After group.

- 151 -
Chapter 4 - Extension View Editor

Object Description

Send Select the Enter Key radio button to send the command specified in the Message input after the ENTER
Message key has been pressed, or select the Token radio button to send the Message command after the space bar
After has been pressed.

Multi-Line Check this checkbox if you would like the text entry widget to hold more than a single line of text. Scroll
bars are added automatically. For more than a single line to be shown at a time, you must resize the
widget accordingly.

Word Wrap Available only when the Multi-Line checkbox is checked. Check this checkbox if you would like the widget
to start a new line of text when the width of the widget has been reached. If this checkbox is unchecked,
you must use the ENTER key to proceed to the next line.

Update When this checkbox is checked, an update (Viewable methods SpecifyText and TextValue called) is
Each performed after each character is entered. This is used in the Match cell for component selection,
Character Components tab of the Fluid Package view.

Allow When this checkbox is checked, the text entry widget is read-only.
Viewing
Only

Push When this checkbox is checked, pressing the ENTER key sends the message for the DefaultView form’s
Default default button. This is a convenience feature that allows the user to enter a text string, press ENTER and
Button have the DefaultView form react as though the default button had also been pressed. It is rarely used, but
can be used to have the DefaultView form accept the text input and close the DefaultView form at the
same time. The default button is specified in the DefaultView form properties.

Mono Check this checkbox to have characters line up perfectly in the vertical direction when using the Multi-Line
Space Font functionality.

This is equivalent to selecting Mono Space as a font in the Session Preferences (Tools-Preferences).

Target By making a selection from this drop-down list, you are instructing the text entry widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must correspond
to a variable associated with the target widget.

For example, you could select an attachment list (i.e., a list of product streams) as the target widget and
have the selected item in the list, an object, appear in the text entry widget. You would then have to link the
Target Moniker to the object variable type associated with the attachment list.

4.3.7 Rich Text Entry Widget


Use this widget to allow the user to enter text and change the text’s attributes (i.e., font, colour).

Figure 4.35

- 152 -
Chapter 4 - Extension View Editor

[Link] Rich Text Entry Properties

The properties available for a Rich Text Entry widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Text that you have created in the Object Manager.

Get/Set Check this checkbox if you would like all input to the widget to be treated as text. This is useful if you will be
As Text passing the moniker to a method that requires a text parameter. The entered text loses any formatting that
might bet attached to it (i.e., strips RTF).

Hide Checking this checkbox hides the toolbar that accompanies the rich text entry widget.
Toolbar

4.3.8 Format Entry Widget


Use this widget to allow the user to choose the format for certain values on the application’s view.

Figure 4.36

[Link] Format Entry Properties

The properties available for a Format Entry widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any applicable variables that you have created in the Object Manager.

Format This is the variable that represents the default format for the widget. It is called when the user presses either
Moniker the DELETE key in the widget or the Use Default button on the Real Format Editor view.

4.3.9 Numerical Input Widget


Use this widget to allow the user to input numerical values on the application’s view.

- 153 -
Chapter 4 - Extension View Editor

Figure 4.37

[Link] Numerical Input Properties

The properties available for a Numerical Input widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Real Number or Enumeration that you have created in the Object Manager.

Format Specify the format for the value in the numerical input widget. Clicking the Ellipsis icon brings up the Real
Format Editor view.

Empty If the value held in the widget becomes -32767, whatever is input in the Empty Text field is shown.
Text

View Check this checkbox to make the widget read-only.


Only

Hidden If the value held in the widget becomes -32768, whatever is input in the Hidden Text field is shown.
Text

Time If using a target moniker with time units, specify the format to be shown.
Format

Units There are three particulars in the Units group:

l Var Type Moniker. This is for historical purposes only and is no longer relevant (the method
GetEDVarType is used internally).
l Show Unit. Check this checkbox if you want to show the unit associated with the moniker with the value
in the widget.
l Fixed Unit Type. Enter a unit here if you want to force the value in the widget to remain as this unit type
regardless of the unit set selection in the Session Preferences. For a temperature moniker, you could
enter ‘C’ and have the value always in Celsius.

- 154 -
Chapter 4 - Extension View Editor

Object Description

TIP
For information concerning the format of entries in this field, refer to Section 12.3.1 - Units Page
from the UniSim Design User Guide.

Target By making a selection from this drop-down list, you are instructing the Numerical Input widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must correspond
to a variable associated with the target widget.
For an example, see the Target Widget property for the text entry widget.

Use Check this checkbox if you want the edit bar to pop up beside the numerical input widget as opposed to
Popup below the view’s title bar.
Edit Bar

Disable Check this checkbox if you want to disable the fly by description that appears when the cursor is over the
Fly By Numerical Input widget.

4.3.10 Matrix Widget


Use this widget to display related information in an organized fashion.

Figure 4.38

[Link] Matrix Properties

The properties available for a Matrix widget are described in the table below:

Object Description

Data Sets In this list, you can Edit or Delete a selected data set or Insert a new data set by clicking the appropriate
button. The View Editor requires a minimum of one data set at all times for the matrix widget.

When the Insert button is clicked, you must choose the type of data set from the Select a Data Type view.
Each type has its own set of properties. Only the most frequently used data set types are described:

l Attachment. For objects such as streams, pump curves, etc.

- 155 -
Chapter 4 - Extension View Editor

Object Description

l Boolean. Shows a checkbox (or other designated symbol) for true/false type situations.
l Enumeration. Shows the enumeration label for the given enumeration value.
l Numeric. For any numeric value, real or integer.
l Text. For text values or labels.
l Unit. Used to show and specify the unit being used (i.e. for time units, choose between seconds,
minutes, hours, etc.) for other data in the matrix; provides a link for overriding the Session
Preferences unit set for other matrix data.

Vertical If this checkbox is checked, data sets are added one below the next (vertical direction).
Direction

Multi- If this checkbox is checked, you are able to select multiple cells in the matrix, horizontally, vertically, and
Selectable diagonally.

Sticky Last If this checkbox is checked, placing the focus on the last entry will keep the focus on the last entry in the
Entry matrix even when additions are being made to the matrix. For instance, while the solver is performing
iterations, run time data can enter a matrix. If you always wanted to see the last entry in the list, you would
check the Sticky Last Entry checkbox and place the focus on the last entry in the matrix. Placing the focus
anywhere but on the last entry will keep the focus on that particular entry, which is also the behaviour
which is exhibited if the checkbox is unchecked.

Position Allows you to assign different monikers to the x and y locations in the matrix so you can keep track of the
Track exact location of the focus. An example of this functionality is in the Workbook. The Show Name Only
Monikers button compresses all the stream information to show only the names of the streams. The current focus
can be on any of the stream properties (i.e., name, temperature, molar flow) when uncompressed
information is shown. When the Show Name Only button is clicked the focus moves to the name of the
stream that held the focus, which would be a different row number.

Labels The Labels group has two drop-down lists, a numerical entry cell and a cell for a label moniker:

l Unnamed. The first drop-down list is unnamed, but allows you to choose where you would like labels
shown in the matrix. Your options are None, Row (place the labels in the left column on each row),
Column (place the labels along the top row on each column) and Both.
l Show Units. A drop-down list from which you can choose to display units along with the label on the
Row, in the Column, or on Both, or choose None. This will likely coincide with your choice of whether
or not to display units.
l Left Width. Enter a value for the leftmost column when labels are present.
l Moniker. Assign a variable for the labels. An example of its use is the assignment of labels to a matrix
at run time, when you could have a variety of names in a matrix. If you are adding column
specifications to the column property view, you will have no idea what specs will be added until run
time, so by retrieving the spec names through a running label moniker at run time, you can perform
this action.

Cells In this group, you can set global Width, Height and Wrap values for the matrix widget. The cell width can
be overridden in the individual data set properties. The cell height of 9 is the standard that is used in all
UniSim Design views. The value for Wrap allows you to force a particular number of columns of data to
be displayed in the matrix. After this value is reached the next column of data starts at the far left. An
example of this behaviour is on the Worksheet tab of the Column unit operation (its value is set to 5).

Enter Select a direction for the focus movement when the ENTER key has been pressed in the matrix. The
Motion options include:

l None. Stay in the same cell.

- 156 -
Chapter 4 - Extension View Editor

Object Description
l Right. Move to the cell to the right.
l Down. Move to the cell directly below.
l Complement. Move to the complementary matrix cell (i.e., if focus is in row 2, column 4 move to row
4, column 2). An example of this behaviour is in the binary coefficients matrix for the Chien Null
activity model.
l Right Wrap. Use this option in conjunction with the Wrap cell. When data in the last cell of the
rightmost column has been input, the focus moves to the next line in the leftmost column. This is used
in the view for molecular weight/density/viscosity assay data input.
l Right if Empty. If the value in the cell was <Empty> before input, then move to the right; if it held a
value and the user is simply editing, then stay in that cell.
l Down if Empty. If the value in the cell was <Empty> before input, then move down one cell; if it held
a value and the user is simply editing, then stay in that cell.
l Complement if Empty. If the value in the cell was <Empty> before input, then move to the
complementary matrix cell; if it held a value and the user is simply editing, then stay in that cell.

Grids Specify whether you want the matrix grid shown for each Column, each Row, Both rows and columns or
None at all.

Target By making a selection from this drop-down list, you are instructing the matrix widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.
For an example, see the Target Widget property for the Text Entry widget.

DataSet Properties

All data set types have the following common properties:

Figure 4.39

Object Description

Name Retain the default name or input a more descriptive name for the data set, which appears in the Data Sets
list on the Matrix Properties view.

Fly By Place text in this cell to have a message appear in the UniSim Design status bar and/or as a tool tip when
the mouse is placed over the data set. This overrides any Fly By that has been input for the matrix widget.
The ‘\n’ (newline sequence) is used to differentiate status bar output and tool tips.

For example, with the Fly By input of “Performs an action.\nThe sky is blue”, the message to the left of the
newline sequence, “Performs an action”, would appear in the status bar and the message to the right of the
newline sequence, “The sky is blue” would appear as a tool tip. If the newline sequence is not used, the
whole message appears in the status bar.

Moniker This is the variable to which you put your data and/or from which you get your data. It is the variable that is
associated with the data set. Clicking the Ellipsis icon gives a list of available options, including any
appropriate variables that you have created in the Object Manager.

- 157 -
Chapter 4 - Extension View Editor

Object Description
Message This is the command(s) that will be executed/fired when the ENTER key is pressed.

Label Select either the Fixed or Moniker radio button and then either specify a static label or associate a moniker
with the data set label.

Cell Width Enter a width for the data set cell that overrides the value in the Width cell of the Cells group on the Matrix
Override Properties view.

View Only Check this checkbox to make the data set read-only.

Specific data set type properties include:

Attachment

Figure 4.40

Object Description

Drop List Assign a type of sorting for the list of attachments that appears in the drop-down list: Ascending
Sorting (alphabetical), Descending (reverse alphabetical) or None.

Expand This is the recommended way, by controlling through the widget instead of through code, to control how the
Style matrix expands.

There are three selections in this drop-down list:

l Always. Adds another field to the matrix when the current boundary is exceeded. The default setting
for Empty Text is <Empty>.
An example of this behaviour is found for unit operations that can handle multiple feeds or products. You
are first presented with something like <New Feed>. As you add feeds, the matrix is expanded and
<New Feed> is added to the bottom of the list. When the physical size of the matrix is exceeded, scroll
bars appear and another field is added to the bottom of the list. In this case, [Link] file has been
modified through a text editor to change the Empty Text from <Empty> to <New Feed>.
l Never. The matrix is limited to the physical size of the widget.
l Limit. Supply a limit for the maximum size that is allowed for the data set.

Allow Check this checkbox if you want the user to be able to type in a name and have a new object (of the
Creation particular type) be created and added to the list if the name does not already exist.

Show Tag If this checkbox is checked, you will see the flowsheet name attached to the object name if you are currently
Names not in the flowsheet where the object resides (i.e., from the column environment, you might see
Feed@Main if the stream Feed was created in the main environment).

Boolean

Figure 4.41

- 158 -
Chapter 4 - Extension View Editor

Object Description

True Icon Double-click on this cell to select an icon that represents the true value of the Boolean, which is the value 1.

False Icon Double-click on this cell to select an icon that represents the false value of the Boolean, which is the value
0.

Third State Double-click on this cell to select an icon that represents the (often misunderstood) other state of the
Icon Boolean, which is any value other that 0 or 1.

Enumeration

Figure 4.42

Object Description

Specify EMPTY on Check this checkbox if you want -32767 to be set in the variable when the user presses
Delete DELETE.

Numeric

Figure 4.43

Object Description

Format Specify the format for the value in the data set. Clicking the Ellipsis icon brings up the Real Format Editor
view.

Empty If the value held in the matrix cell becomes -32767, whatever is input in the Empty Text field is shown.
Text

Hidden If the value held in the matrix cell becomes -32768, whatever is input in the Hidden Text field is shown.
Text

Variable This is for historical purposes only and is no longer relevant (the method GetEDVarType is now used
type internally).
override
moniker

Auto Assigns the appropriate unit according to the specified Moniker and the chosen Unit Set in the Session
Preferences.

Moniker This choice allows you to override the selection in the Session Preferences, but also gives the opportunity
for the user to make the unit selection at run time. You must specify a moniker to be used when this radio
button is selected. This is usually used in conjunction with a Unit data set, which specifies the unit moniker.
The same moniker is then used in this unit moniker cell, forming a link between the two cells.
A good example is on the Integrator view, where the user can select a time unit for the integrator step size.
The step size, minimum and maximum are then shown in that selected time unit regardless of the choice in
the Session Preferences.

- 159 -
Chapter 4 - Extension View Editor

Object Description

Fixed Allows you to hard code a particular unit type which overrides the selection in the Session Preferences; for a
temperature moniker, you could enter ‘C’ and have the value always in Celsius; for the format of entries in
this field, refer to the unit representations as shown in the Display Units group on the Units page of the
Session Preferences view.

Show Unit Check this checkbox if you want to show the unit associated with the data set Moniker along with the value
in Cell in the cell.

Hide Check this checkbox if you want to hide the unit in the data set label.
Units in
Label

Spreadsheet

Figure 4.44

Object Description

Unit System Optional setting. When set it allows the unit set used for the held data to differ from the default “Unit Set”
Moniker configured in preferences.

Variable Type This is for historical purposes only and is no longer relevant.
Moniker

Is Formula? Opens the Select Number Variable view. This allows you to set whether the moniker will be used to
Moniker get or set either: text (a formula) or numbers (non-formula).

Formula Error Must return an error code form that indicates what type of mathematical error has occurred or when all
Moniker is well.

Unit

Figure 4.45

Object Description

Variable Type Moniker This is for historical purposes only and is no longer relevant.

Worksheet Attach

Figure 4.46

- 160 -
Chapter 4 - Extension View Editor

Object Description

Expand There are three options for this drop-down list:


Style
l Always. The default setting. It allows you to automatically expand the worksheet data set to include
new entries.
l Never. This option does not allow you to expand the number of variable entries.
l Limit. This option allows you to explicitly set the number of entries you can expand to.

Numerical Format

Figure 4.47

Object Description

Default This is the variable that represents the default format for the widget. It is called when the user presses either
Format the DELETE key in the widget or the Use Default button on the Real Format Editor view.

4.3.11 Check Box Widget


Use this widget for boolean (true/false or yes/no) situations.

Figure 4.48

[Link] Checkbox Properties

The properties available for a Checkbox widget are described in the table below:

Object Description

Label Whatever is entered here is shown as the text next to the checkbox. Place an ampersand (&) before the
character that gets the hot key (underscore) designation.

Label Select a radio button to place the label text to the left or to the right of the checkbox.
Placement

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,

including any variables of type Real or Enum that you have created in the Object Manager.

- 161 -
Chapter 4 - Extension View Editor

Object Description
Target By making a selection from this drop-down list, you are instructing the checkbox widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.

For an example, see the Target Widget property for the Text Entry widget.

4.3.12 Radio Buttons Widget


Use this widget when you want the user to make a single specific choice from a list of mutually exclusive choices (normally a
maximum of 3; if more than 3, use an enumeration widget or other appropriate widget).

Figure 4.49

[Link] Radio Button Properties

The properties available for a Radio Button widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Real or Enum that you have created in the Object Manager.

Target By making a selection from this drop-down list, you are instructing the radio buttons widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must correspond
to a variable associated with the target widget.
For an example, see the Target Widget property for the text entry widget.

Insert Adds another entry in to the radio button details matrix wherever the focus happens to be, but the entry will
not be named and will have no assigned value. The symbol +++ is shown in the label cell.

Delete Deletes the entry from the radio button details matrix wherever the focus happens to be.

Use This is not functional.


Template

Radio There are six columns in the matrix in which you can specify details for the radio button widget:
Button

- 162 -
Chapter 4 - Extension View Editor

Object Description
Details l Label. Whatever is entered here will be shown as the text next to the radio button. Place an
Matrix ampersand (&) before the character that will get the hot key (underscore) designation.
l Value. Each radio button must have a unique value, such that it can be used in code, if need be. The
value can be integer or real, it simply needs to be unique within the scope of the particular widget.
l X. X coordinate of the particular radio button on the DefaultView form. For information concerning the
units used, refer to the Position section under Common Widget Properties.
l Y. Y coordinate of the particular radio button on the DefaultView form. For information concerning the
units used, refer to the Position section under Common Widget Properties.
l Width. Width of the widget. If you input different values for each radio button, the largest value will be
honoured. For information concerning the units used, refer to the Position section under Common
Widget Properties.
l Placement. Choice for where you want to place the label, in reference to the radio button. Either On
Left or On Right.

4.3.13 Graphic Button Widget


Use this widget to send specific instructions to its base object when it is clicked by the user. More functionality is offered with
this widget than with the regular button widget. For instance, you can have a picture appear on the button face and have the
button stick in its pressed state.

Figure 4.50

[Link] Graphic Button Properties

The properties available for a Graphic Button widget are described in the table below:

- 163 -
Chapter 4 - Extension View Editor

Object Description

Main Icon Double-click on this cell to make a choice for the icon that will appear on the button.

Focus Icon Double-click on this cell to make a choice for the icon that will appear with the Main Icon on the button when
the button has focus. The default for Focus Icon is the regular dotted outline that appears with most
Windows programs.

Message This is the command(s) that will be executed/fired when the button is pressed. For the button shown above,
the property view of the upstream unit operation will be shown. You can click the Ellipsis icon to access the
Edit Messages view, which provides a list of the current messages that are being used for the particular
button. From this view, you can add new messages, delete existing ones, edit the list or re-arrange the
order in which the messages are fired. If you have created variables of type Message in the Objects
Manager, these will be available for addition to the Edit Messages view.

Source Allows you to choose a widget that will provide required information when the button is fired. It is used to
Widget ‘populate’ the arguments for the Message. For example, the index value of an object in a list could be
provided to the button so the button can perform some action on the particular object. You can use
placement holder type syntax (i.e.,%d for an integer).

Target Allows you to choose a widget which holds a collection of objects. The selected object or multiple selected
Widget objects will be affected by the firing of the button. For an example, refer to the Target Widget section for the
Button widget.

Value Allows you to choose what type of data is held or passed when the button is pressed. You can choose one
Type of the following:

l None. The button’s only purpose is to fire its message when it is pressed. The View Next
Downstream Operation button is an example of the use of this option.
l Number. A numeric value is held when the button has been pressed. The Colour Scheme button on
the PFD is an example of the use of this option.
l Object Type. An object type string is held when the button is pressed. All unit operation and stream
buttons on the Object Palette use this option.

Repeat In these two fields, Initial and Fast, you can enter values that respectively represent the time that elapses
Delays before the first message is sent and the time interval that will pass before the sending of each subsequent
message if the button is held down. The units used for the time entries are milliseconds.
This is used for the rotation of plots, where the user presses and holds a button down to continually rotate
the plot until the desired view is attained.

Sticky These options allow you to set whether or not the button will remain in its pressed state (Stuck) when it is
Options pressed and also if it is in its pressed state, whether or not pressing the button again will remove it from its
pressed state (Released).

You can assign a variable (normally of type Boolean) in the Variable cell to the option, which will allow you
to monitor the state of the button (Stuck or Released).

By providing values in the Stuck and Released cells, you can assign one of two behaviours for the button:

l Pressing a Stuck button releases the button - provide a unique value in each cell (i.e. 50 and 65)
l A Stuck button is released by another object - provide the same value in each cell. This behaviour is
exhibited by the unit operation and stream buttons on the Objects Palette. For instance, pressing a
Cooler operation button will make it stuck. You cannot release the button by pressing it again. You must
click the Cancel button (the red X), click the Add button (the green +), click another unit operation or
stream button in the palette or click on the PFD to add the operation.

Requires Activating this checkbox limits selection in the source widget to a single item. Continuing the example cited
Single in the Source Widget discussion, activating this checkbox will allow the user to select only a single fluid

- 164 -
Chapter 4 - Extension View Editor

Object Description

Source package in the list.

Requires Activating this checkbox limits selection in the target widget to a single item. If the button deletes items from
Single a list, you may want to limit the user to only a single deletion per button click.
Target

Accepts Check this checkbox if you want the button to take away the focus when it is pressed or to have the ability to
Focus accept the focus when its tab order number is selected by pressing the TAB key.

For instance, none of the buttons in the PFD toolbar have this checkbox checked, and as such, do not
accept the focus when they are pressed. Focus remains with whatever was selected in the PFD. Also, you
cannot access the buttons by pressing the TAB key.

Support Check this checkbox if the button widget will be drag and drop compliant. All unit operation and stream
Drag buttons in the Object Palette have this checkbox checked, and thus, when a button is selected with the
secondary mouse button and dragged, the value can be dropped onto another widget (i.e. the PFD).

4.3.14 Group Widget


Use this widget to organize related information within a titled border on the application’s view.

Figure 4.51

[Link] Group Properties

The properties available for a Group widget are described in the table below:

Object Description

Title Enter a title for the group. Use the ampersand (&) before the character that is the accelerator key or hot key.

4.3.15 Page Tabs Widget


Use this widget to increase the amount of information that can appear on the application’s view. The widget can then be used
in conjunction with the Visibility Manager to organize the information on particular tabs.

- 165 -
Chapter 4 - Extension View Editor

Figure 4.52

[Link] Page Tab Properties

The properties available for a Tab widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Real or Enum that you have created in the Object Manager.

Static Tabs In this group, supply a Label and a unique Value for each tab that will appear in this widget.

The unique Value that is supplied for each tab should match the High/Low values that you provide in the
Visibility Controller Properties view. Refer to the Visibility Manager for more information.

Draw Check this checkbox if would like a rectangular area around the tabs to have a three-dimensional sunken
Border effect. The tabs in UniSim Design do not have this option enabled.

Dynamic There are three areas in this group, each of which deals with the changing of the tabs at run-time:
Tabs
l Label Moniker. Supply a variable in this cell if you have to adapt the view according to user input at
run-time. For instance, the results view for the case study tool in UniSim Design has a Label moniker
(variable) since the user can create as many case studies as required in the simulation. The view must
show one tab per case study created.
l First Value. Provide a unique value in this cell such that the first tab added at run-time does not
conflict with any of the values for the static tabs. This value should be greater than the largest unique
value that you are using in the Static Tabs group.
l Move Tab Message. Allows you to input a custom message, which will be defined in your code, to
enable the movement/re- ordering of the tabs at run-time by the user. This functionality is found in the
Workbook, where you can select a tab, drag down below the tab and then drag to the side where you
would like to move the tab. All tab contents are moved with the tab.

Controlled The widget selected in this drop-down list will receive the focus when a tab is selected. This functionality
Widget provides visual appeal in that the tab seems to be part of the controlled widget. The user does not have to

- 166 -
Chapter 4 - Extension View Editor

Object Description

click within the controlled widget after selecting a tab. Normal use of this option occurs when the selected
widget is the only other widget on the DefaultView form or when there is a clearly dominant widget that
will be the main focus of the user.
This functionality is used in the Workbook and in the PFD, in which you can select a particular tab and the
focus is automatically placed within the particular Workbook sheet or PFD pane.

Target By making a selection from this drop-down list, you are instructing the tabs widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.
For an example, see the Target Widget property for the text entry widget.

4.3.16 Ply Picker Widget


This widget, used in conjunction with the tabs widget, provides a way to further organize information while retaining a clean
look for the application’s view. With an enormous amount of information, using this widget avoids the creation of tabs in the
double digits on a single view.

Figure 4.53

[Link] Ply Picker Properties

The properties available for a Page Picker widget are described in the table below:

Object Description

Title In this group you can provide a title for the ply picker widget. Refer to the example widget shown previously,
Options which has the title Design, to see where the title is placed.

You see a different input cell in this group depending on the radio button selection. The radio button
selections are:

l Fixed. Choose this option if you want to supply a static title, and then supply the text in the Title input
cell.
l Dynamic. If you would like the title to be dynamic (i.e. ability to change at run-time), select this option
and then associate the title with a variable in the Title Moniker cell. Any variables of type Text that you
have created in the Object Manager will be shown when you click the Ellipsis icon.
l Other Widget. Select this option if you want to choose a widget that will supply the ply picker title with
information. You can then select a widget from the Source Widget drop-down list. For example, you
could select the tabs widget and have the tab label appear as the ply picker title widget. This is how the

- 167 -
Chapter 4 - Extension View Editor

Object Description

ply picker widget on the UniSim Design unit operation property views are configured.

Enum Allows you to associate an enumeration variable to the widget so that the name of each individual ‘ply’ can
Moniker appear on the widget. For example, the widget shown previously, the enumeration contains the names
Connections, Parameters, User Variables and Notes.

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Real or Enum that you have created in the Object Manager.

Target By making a selection from this drop-down list, you are instructing the ply picker widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must correspond
to a variable associated with the target widget.

s For an example, see the Target Widget property for the Text Entry widget.

4.3.17 Attachment Name Widget


Use this widget to display variables of type Attachment in a drop- down list format.

Figure 4.54

[Link] Attachment Name Properties

The properties available for a Attachment Name widget are described in the table below:

Object Description

Number of In this cell, you specify the size of the list that is shown when the drop-down list is accessed. If more
Entries objects exist than the value specified, a scroll bar is automatically added to the drop- down list.

Target Moniker This is the variable to which you put your widget data and/or from which you get your widget data. It is
the variable that is associated with the [Link] the Ellipsis icon gives a list of available
options, including any variables of type Attachment that you have created in the Object Manager.

Target Widget By making a selection from this drop-down list, you are instructing the attachment name widget to
receive its information from the Target Widget. When a target widget is selected, the target moniker
must correspond to a variable associated with the target widget.

For an example, see the Target Widget property for the Text Entry widget.

- 168 -
Chapter 4 - Extension View Editor

Object Description
Attach Allows you to specify a command(s) that will be executed/fired when a choice is made in the
Message attachment name widget. All variables of type Message that you created in the Objects Manager will
be available if you click the Ellipsis and then click the Insert button on the Edit Messages view.

Allow creation Check this checkbox if you want the user to be able to type directly in the attachment name widget and
have the application create a new object of type Attachment with the user input name.

Most unit operation views that have attachment name widgets will allow the creation of a new
attached stream when the user types a name directly in the widget.

Use drop list Check this checkbox if you want the widget to show its drop- down list when checked. If this checkbox
is unchecked, the widget appears as though it is a text entry widget.

Match using Check this checkbox if you want the focus in the drop-down list to move to the first occurrence of the
abbreviations letter or letter combination that the user types.

This checkbox is available only when the Use drop list checkbox is checked.

Drop List Select one of the radio buttons to instruct the widget on how you would like the items in the drop-down
Sorting list shown:

l Ascending. Items are shown alphabetically.


l Descending. Items are shown in reverse alphabetical order.
l None. Items are shown in the order in which they are added to the application.

4.3.18 Enumeration Widget


Use this widget to display a list of names in a drop-down list format.

Figure 4.55

[Link] Enumeration Properties

The properties available for a Enumeration widget are described in the table below:

Object Description

Number of In this cell, you specify the size of the list that is shown when the drop-down list is accessed. If more
Entries objects exist than the value specified, a scroll bar is automatically added to the drop- down list.

Target Moniker This is the variable to which you put your widget data and/or from which you get your widget data. It is
the variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available

- 169 -
Chapter 4 - Extension View Editor

Object Description
options, including any variables of type Enumeration that you have created in the Object Manager.

Target Widget By making a selection from this drop-down list, you are instructing the enumeration widget to receive
its information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.

For an example, see the Target Widget property for the Text Entry widget.

Match using Check this checkbox if you want the focus in the drop-down list to move to the first occurrence of the
abbreviations letter or letter combination that the user types.

Drop List Select one of the radio buttons to instruct the widget on how you would like the items in the drop-down
Sorting list shown:

l Ascending. Items are shown alphabetically.


l Descending. Items are shown in reverse alphabetical order.
l None. Items are shown in the order in which they are added to the application.

4.3.19 Unit Enumeration Widget


Use this widget to display a list of units in a drop-down list format.

Figure 4.56

[Link] Unit Enumeration Properties

The properties available for a Unit Enumeration widget are described in the table below:

Object Description

Number of In this cell, you specify the size of the list that is shown when the drop-down list is accessed. If more
Entries objects exist than the value specified, a scroll bar is automatically added to the drop- down list.

Target Moniker This is the variable to which you put your widget data and/or from which you get your widget data. It is
the variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available
options, including any variables of type Text that you have created in the Object Manager.

Target Widget By making a selection from this drop-down list, you are instructing the unit enumeration widget to
receive its information from the Target Widget. When a target widget is selected, the target moniker
must correspond to a variable associated with the target widget.

- 170 -
Chapter 4 - Extension View Editor

Object Description

For an example, see the Target Widget property for the text entry widget.

Unit Type/ Unit This cell along with its corresponding radio buttons (Fixed and Source) are for historical purposes
Type Moniker only.

Match using Check this checkbox if you want the focus in the drop-down list to move to the first occurrence of the
abbreviations letter or letter combination that the user types.

Drop List Select one of the radio buttons to instruct the widget on how you would like the items in the drop-down
Sorting list shown:

l Ascending. Items are shown alphabetically.


l Descending. Items are shown in reverse alphabetical order.
l None. Items are shown in the order in which they are added to the application.

4.3.20 Text List Widget


Use this widget to display a list of object related information in text format, from which the object can usually be accessed.

Figure 4.57

[Link] Text List Properties

The properties available for a Text List widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,

including any variables of type Text that you created in the Objects Manager. Any variables of type Text
that you create must have Vector selected in the N Dimensions drop-down list.

Message This is the message that is executed/sent when the user presses ENTER or double-clicks on the
selection in the widget. Normal use would have the object’s property view open.

Delete This is the message that will be executed/fired when the user presses DELETE on the selection in the

- 171 -
Chapter 4 - Extension View Editor

Object Description

Message widget. Normal use would have the object being deleted.

Insert This is the message that will be executed/fired when the user presses INSERT while the focus is within
Message the widget.

Track Supply a variable in this cell which will allow you to keep a record of the selected object in the list or set the
Moniker selected object in the list, depending on how it is used in your code. When there is multiple selection in the
list, the first (topmost) object in the selection will be accessed through the track moniker. The track
moniker will not correspond to the object that has focus when multiple selection is made from the top
down, as the bottom most object will have the dotted outline or focus.

Sorting Select one of the options in the drop-down list to instruct the widget on how you would like the items in the
widget to be shown:

l Ascending. Items are shown alphabetically.


l Descending. Items are shown in reverse alphabetical order.
l None. Items are shown in the order in which they are added to the application.

Multi- Check this checkbox if you want to allow more than a single selection in the widget.
Selectable

Sticky Last If this checkbox is checked, placing the focus on the last entry will keep the focus on the last entry in the
Entry widget even when additions are being made to the widget. Refer to this option in the Matrix widget for an
example.

Append Check this checkbox if you want a blank row to always be present at the end of the list. This is useful
Extra Blank when the user is able to select the position of new entrants to the list. By placing the focus on the blank
row at the end, the new list entrant will added to the end of the list. Placing the focus on an existing list
entry will have the new list entrant added above this selection. This behaviour is exhibited in the Current
Component List on the Components tab of the Fluid Package view.

Initially Check this checkbox if you want to have an item selected in the widget when the view is re-opened. This
Selected option retrieves the list item identified in the track moniker and tries to match this information to an item
that you may have coded (i.e. by name). If no match is found, the first item in the list becomes the selected
item and this information is sent to the track moniker. A selected item does not necessarily have the focus.

Source Allows you to choose a widget that will provide required information when any message is fired. It is used
Widget to ‘populate’ the arguments for a message.

Target By making a selection from this drop-down list, you are instructing the text list widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.

For an example, see the Target Widget property for the text entry widget.

Abbrev Check this checkbox if you want the focus in the list to move to the first occurrence of the letter or letter
Keys combination that the user types.

Draw Border Check this checkbox if you would like a rectangular area around the text list to have a three-dimensional
sunken effect.

Tab Stops Add values here which correspond to the use of ‘\t’, the tab character, in the text strings that will populate
the text list widget.

If there are two occurrences of the tab character in the text strings that will fill the widget, there should be
two tab stops, indicating the position to start the string after the tab. With 2 tab stops, it will seem as
though there are three columns of information in the text list widget.

- 172 -
Chapter 4 - Extension View Editor

Object Description
Column If you provide a value (the width of each column) in this cell, list entries will wrap to the right in to a new
Width column when the current widget size has been reached. If no value is provided, the list will keep
expanding in a single column with the appearance of scroll bars when the widget height has been
reached.

4.3.21 Enumeration List Widget


Use this widget to display a list of the labels in an enumeration.

Figure 4.58

[Link] Enumeration List Properties

The properties available for a Enumeration List widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the [Link] the Ellipsis icon gives a list of available options,
including any variables of type Enumeration that you created in the Objects Manager.

Message This is the message that is executed/sent when the user presses ENTER or double-clicks on the
selection in the widget. Normal use would have the object’s property view open.

Delete This is the message that will be executed/fired when the user presses DELETE on the selection in the
Message widget. Normal use would have the object being deleted.

Insert This is the message that will be executed/fired when the user presses INSERT while the focus is within
Message the widget.

Track Supply a variable in this cell which will allow you to keep a record of the selected object in the list or set the
Moniker selected object in the list, depending on how it is used in your code. When there is multiple selection in the
list, the first (top most) object in the selection will be accessed through the track moniker. The track
moniker will not correspond to the object that has focus when multiple selection is made from the top
down, as the bottommost object will have the dotted outline or focus.

Sorting Select one of the options in the drop-down list to instruct the widget on how you would like the items in the
widget to be shown:

- 173 -
Chapter 4 - Extension View Editor

Object Description
l Ascending. Items are shown alphabetically.
l Descending. Items are shown in reverse alphabetical order.
l None. Items are shown in the order in which they are added to the application.

Multi- Check this checkbox if you want to allow more than a single selection in the widget.
Selectable

Sticky Last If this checkbox is checked, placing the focus on the last entry will keep the focus on the last entry in the
Entry widget even when additions are being made to the widget. Refer to this option in the Matrix widget for an
example.

Append Check this checkbox if you want a blank row to always be present at the end of the list. This is useful
Extra Blank when the user is able to select the position of new entrants to the list. By placing the focus on the blank
row at the end, the new list entrant will be added to the end of the list. Placing the focus on an existing list
entry will have the new list entrant added above this selection. This behaviour is exhibited in the Current
Component List on the Components tab of the Fluid Package view.

Initially Check this checkbox if you want to have an item selected in the widget when the view is re-opened. This
Selected option retrieves the list item identified in the track moniker and tries to match this information to an item
that you may have coded (i.e. by name). If no match is found, the first item in the list becomes the selected
item and this information is sent to the track moniker. A selected item does not necessarily have the focus.

Source Allows you to choose a widget that will provide required information when any message is fired. It is used
Widget to ‘populate’ the arguments for a message.

Target By making a selection from this drop-down list, you are instructing the enumeration list widget to receive
Widget its information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.
For an example, see the Target Widget property for the text entry widget.

Abbrev Check this checkbox if you want the focus in the list to move to the first occurrence of the letter or letter
Keys combination that the user types.

Draw Border Check this checkbox if you would like a rectangular area around the enumeration list to have a three-
dimensional sunken effect.

Tab Stops Add values here which correspond to the use of ‘\t’, the tab character, in the enumeration labels that will
populate the enumeration list widget.

If there are two occurrences of the tab character in the enumeration labels that will fill the widget, there
should be two tab stops, indicating the position to start the label after the tab. With 2 tab stops, it will seem
as though there are three columns of information in the enumeration list widget.

Column If you provide a value (the width of each column) in this cell, list entries will wrap to the right in to a new
Width column when the current widget size has been reached. If no value is provided, the list will keep
expanding in a single column with the appearance of scroll bars when the widget height has been
reached.

4.3.22 Attachment List Widget


Use this widget to display a list of related objects.

- 174 -
Chapter 4 - Extension View Editor

Figure 4.59

[Link] Attachment List Properties

The properties available for a Attachment List widget are described in the table below:

Object Description

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Attachment that you created in the Objects Manager. Any variables of type
Attachment that you create must have Vector selected in the N Dimensions drop-down list.

Message This is the message that is executed/sent when the user presses ENTER or double-clicks on the
selection in the widget. Normal use would have the object’s property view open.

Delete This is the message that will be executed/fired when the user presses DELETE on the selection in the
Message widget. Normal use would have the object being deleted.

Insert This is the message that will be executed/fired when the user presses INSERT while the focus is within
Message the widget.

Track Supply a variable in this cell which will allow you to keep a record of the selected object in the list or set the
Moniker selected object in the list, depending on how it is used in your code. When there is multiple selection in the
list, the first (topmost) object in the selection will be accessed through the track moniker. The track
moniker will not correspond to the object that has focus when multiple selection is made from the top
down, as the bottommost object will have the dotted outline or focus.

Sorting Select one of the options in the drop-down list to instruct the widget on how you would like the items in the
widget to be shown:

l Ascending. Items are shown alphabetically.


l Descending. Items are shown in reverse alphabetical order.
l None. Items are shown in the order in which they are added to the application.

Multi- Check this checkbox if you want to allow more than a single selection in the widget.
Selectable

Sticky Last If this checkbox is checked, placing the focus on the last entry will keep the focus on the last entry in the

- 175 -
Chapter 4 - Extension View Editor

Object Description
Entry widget even when additions are being made to the widget. Refer to this option in the Matrix widget for an
example.

Append Check this checkbox if you want a blank row to always be present at the end of the list. This is useful
Extra Blank when the user is able to select the position of new entrants to the list. By placing the focus on the blank
row at the end, the new list entrant will be added to the end of the list. Placing the focus on an existing list
entry will have the new list entrant added above this selection. This behaviour is exhibited in the Current
Component List on the Components tab of the Fluid Package view.

Initially Check this checkbox if you want to have an item selected in the widget when the view is re-opened. This
Selected option retrieves the list item identified in the track moniker and tries to match this information to an item
that you may have coded (i.e. by name). If no match is found, the first item in the list becomes the selected
item and this information is sent to the track moniker. A selected item does not necessarily have the focus.

Source Allows you to choose a widget that will provide required information when any message is fired. It is used
Widget to ‘populate’ the arguments for a message.

Target By making a selection from this drop-down list, you are instructing the attachment list widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.

For an example, see the Target Widget property for the text entry widget.

Abbrev Check this checkbox if you want the focus in the list to move to the first occurrence of the letter or letter
Keys combination that the user types.

Hide Tags Check this checkbox if you do not want to show name of the flowsheet with the name of the object in the
list. The flowsheet name will only appear when the object is being shown outside its home flowsheet.
For instance, in a list of material streams, a stream representing the reflux to a column, which is internal
to the column environment, may appear in a list in the main flowsheet as Reflux@COL1 if the Hide Tags
checkbox is unchecked. With this checkbox checked, the user would only see Reflux.

Draw Border Check this checkbox if you would like a rectangular area around the attachment list to have a three-
dimensional sunken effect.

Allow Check this checkbox if you want the object pointer to be replaced by NULL when the attachment is
Detach deleted. If this option is used, the code must account for this scenario. The Allow Detach option is only
valid when the Delete Message is not being used.

Column If you provide a value (the width of each column) in this cell, list entries will wrap to the right in to a new
Width column when the current widget size has been reached. If no value is provided, the list will keep
expanding in a single column with the appearance of scroll bars when the widget height has been
reached.

4.3.23 Level Widget


Use this widget to display a numerical value along with a graphical representation of the value as a percentage of its full
range.

- 176 -
Chapter 4 - Extension View Editor

Figure 4.60

[Link] Level Properties

The properties available for a Level widget are described in the table below:

Object Description

Format Specify the format for the value in the widget. Clicking the Ellipsis icon brings up the Real Format
Editor view.

Fixed Units Enter a unit here if you want to force the value in the widget to remain as this unit type regardless of the
unit set selection in the Session Preferences. For a temperature moniker, you could enter ‘C’ and have
the value always in Celsius.
For information concerning the format of entries in this field, refer to Section 12.3.1 - Units Page from
the UniSim Design User Guide.

Variable This is for historical purposes only and is no longer relevant (the method GetEDVarType is used
Type internally).
Moniker

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is the
Moniker variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available options,
including any variables of type Real Number or Enumeration that you have created in the Object
Manager.

Orientation The radio button selection in this group provides instructions on how to draw the graphical portion of the
widget. The choices are:

l Horizontal. The line representing the current value in the range will be vertical. The use of
Horizontal stems from the fact that the ‘used’ portion and ‘unused’ portion of the range are seen one
beside the other.
l Vertical. The line representing the current value in the range will be horizontal. The use of Vertical
stems from the fact that the ‘used’ portion and ‘unused’ portion of the range are seen one above the
other.

Increment Enter a value here which is used as the incremental step size when the current value pointer is dragged
in the level widget. For the OP cell in a face plate, you can click on the current value (when the controller

- 177 -
Chapter 4 - Extension View Editor

Object Description
is in Manual) with the mouse and drag the line to a new output value. The increment value for the OP cell
is 0.01.

Minimum The Minimum cell as shown has no relevance. Both the Minimum and Maximum values in the target
moniker range should be determined through monikers or through the code.

Maximum The Maximum cell as shown has no relevance. Both the Minimum and Maximum values in the target
moniker range should be determined through monikers or through the code.

Show Unit Check this checkbox if you want to show the unit associated with the moniker with the value in the
widget.

View Only Check this checkbox to make the widget read-only.

Target By making a selection from this drop-down list, you are instructing the level widget to receive its
Widget information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.
For an example, see the Target Widget property for the Text Entry widget.

Display The display mode represents the graphical portion of the widget. Select either radio button:
Mode
l Percent. The graphical bar representing the current value in the level widget will be shown at the
percentage value in the range. If you are monitoring a temperature between 0 and 200°C, and the
current value is 20°C, the bar shows up at the 10% point in the range.
l Actual. The graphical bar representing the current value in the level widget will be shown at the
current value in the range. If you are monitoring a temperature between 0 and 200°C, and the
current value is 20°C, the bar shows up at the 20°C point in the range.
It is recommended that you select the same radio button choice in both the Display Mode and the Value
groups.

Value The value represents the numeric value shown in the widget. Select either radio button:

l Percent. The numeric value in the level widget is shown as the percentage value in the range. If you
are monitoring a temperature between 0 and 200°C, and the current value is 20°C, you see 10 in the
widget representing 10% of the range.
l Actual. The numeric value in the level widget is shown as the actual value in the range. If you are
monitoring a temperature between 0 and 200°C, and the current value is 20°C, you see 20°C in the
widget.
It is recommended that you select the same radio button choice in both the Display Mode and the Value
groups.

4.3.24 Plot Widget


Use this widget to show a two-dimensional or three-dimensional graph. The appropriate plot is shown according to the
values sent through code.

- 178 -
Chapter 4 - Extension View Editor

Figure 4.61

[Link] Plot Properties

The properties available for a Plot widget are described in the table below:

Object Description

Draw Border Check this checkbox if you would like a rectangular area around the plot to have a three-dimensional
sunken effect.

Plot Enter a description (with no spaces in the name) here such that you can access the widget through
Description code.

Target This is the variable to which you put your widget data and/or from which you get your widget data. It is
Moniker the variable that is associated with the widget. Clicking the Ellipsis icon gives a list of available
options, including any variables of type Real Number or Enumeration that you have created in the Object
Manager.

4.3.25 Worksheet Matrix Widget


Use this widget to display related information in an organized fashion. The Worksheet Matrix provides all the functionality of
the Matrix widget in addition to the built-in run-time wrapping capabilities.

TIP
When a Worksheet Matrix (i.e., the Workbook matrix) is resized by the user, the number of columns dynamically
change according to the current size of the view.

- 179 -
Chapter 4 - Extension View Editor

Figure 4.62

[Link] Worksheet Matrix Properties

The properties available for a Worksheet Matrix widget are described in the table below:

Object Description

Data Sets In this list, you can Edit or Delete a selected data set or Insert a new data set by clicking the appropriate
button. The View Editor requires a minimum of one data set at all times for the worksheet matrix widget.

When the Insert button is clicked, you must choose the type of data set from the Select a Data Type view.
Each type has its own set of properties. Only the most frequently used data set types are described:

l Attachment. For objects such as streams, pump curves, etc.


l Boolean. Shows a checkbox (or other designated symbol) for true/false type situations.
l Enumeration. Shows the enumeration label for the given enumeration value.
l Numeric. For any numeric value, real or integer.
l Text. For text values or labels.
l Unit. Used to show and specify the unit being used (i.e., for time units, choose between seconds,
minutes, hours, etc.) for other data in the matrix; provides a link for overriding the Session
Preferences unit set for other matrix data.

TIP
For more information on the data set type properties see DataSet Properties found in Matrix
Widget.

- 180 -
Chapter 4 - Extension View Editor

Object Description
Vertical If this checkbox is checked, data sets are added one below the next (vertical direction).
Direction

Multi- If this checkbox is checked, you are able to select multiple cells in the matrix, horizontally, vertically and
Selectable diagonally.

Sticky Last If this checkbox is checked, placing the focus on the last entry will keep the focus on the last entry in the
Entry matrix even when additions are being made to the matrix. For instance, while the solver is performing
iterations, run time data can enter a matrix. If you always wanted to see the last entry in the list, you would
check the Sticky Last Entry checkbox and place the focus on the last entry in the matrix. Placing the focus
anywhere but on the last entry will keep the focus on that particular entry, which is also the behaviour
which will be exhibited if the checkbox is unchecked.

Position Allows you to assign different monikers to the x and y locations in the matrix so you can keep track of the
Track exact location of the focus. An example of this functionality is in the Workbook. The Show Name Only
Monikers button compresses all the stream information to show only the names of the streams. The current focus
can be on any of the stream properties (i.e. name, temperature, molar flow) when uncompressed
information is shown. When the Show Name Only button is clicked the focus moves to the name of the
stream that held the focus, which would be a different row number.

Labels The Labels group has two drop-down lists, a numerical entry cell and a cell for a label moniker:

l Unnamed. The first option is unnamed, but allows you to choose where you would like labels shown
in the matrix. Your options are None, Row (place the labels in the left column of each row), Column
(place the labels along the top row on each column) and Both.
l Show Units. A drop-down list which you can choose to display units along with label on the Row, in
the Column or on Both or choose None. This will likely coincide with your choice of whether or not to
display units.

Cells In this group, you can set global Width, Height and Wrap values for the worksheet matrix widget. The cell
width can be overridden in the individual data set properties. The cell height of 9 is the standard that is
used in all UniSim Design views. The value for Wrap allows you to force a particular number of columns
of data to be displayed in the matrix. After this value is reached the next column of data will start at the far
left. An example of this behaviour is on the Worksheet tab of the Column unit operation (its value is set to
5).

Enter Select a direction for the focus movement when the ENTER key has been pressed in the matrix. The
Motion options include:

l None. Stay in the same cell.


l Right. Move to the cell to the right.
l Down. Move to the cell directly below.
l Complement. Move to the complementary matrix cell (i.e. if focus is in row 2, column 4 move to row
4, column 2). An example of this behaviour is in the binary coefficients matrix for the Chien Null
activity model.
l Right Wrap. Use this option in conjunction with the Wrap cell. When data in the last cell of the
rightmost column has been input, the focus moves to the next line in the leftmost column. This is used
in the view for molecular weight/density/viscosity assay data input.
l Right if Empty. If the value in the cell was <empty> before input, then move to the right; if it held a
value and the user is simply editing, then stay in that cell.
l Down if Empty. If the value in the cell was <empty> before input, then move down one cell; if it held
a value and the user is simply editing, then stay in that cell.
l Complement if Empty. If the value in the cell was <empty> before input, then move to the

- 181 -
Chapter 4 - Extension View Editor

Object Description
complementary matrix cell; if it held a value and the user is simply editing, then stay in that cell.

Grids Specify whether you want the matrix grid shown for each Column, each Row, Both rows and columns or
None at all.

Target By making a selection from this drop-down list, you are instructing the worksheet matrix widget to receive
Widget its information from the Target Widget. When a target widget is selected, the target moniker must
correspond to a variable associated with the target widget.
For an example, see the Target Widget property for the Text Entry widget.

4.3.26 ACTIVEX Container Widget


This widget allows you to incorporate ActiveX objects in to your DefaultView form.

Figure 4.63

[Link] ActiveX Container Properties

The properties available for a ActiveX Container widget are described in the table below:

Object Description

Control CLSID Clicking the Ellipsis icon opens the Select an ActiveX Control view which displays a list of ActiveX

Controls. Selecting a control inserts the Class Identity currently available on your computer.

Custom Clicking this button displays the custom properties associated with the ActiveX Control.
Properties The Control CLSID field must first be selected before this button can be used.

Associations Opens the Set Associations with ActiveX Properties and Events that allows you to tie the control to an
event or the custom properties to a variable.
The Control CLSID field must first be selected before this button can be used.

Unique Tag This the internal designation of the control.

Caption Text The text associated with the control.

Menu Title The text label that appears in the menu bar when the control has focus.

Draw Border Draws a border around the ActiveX Control.

Container can This checkbox is for internal use only and should not go unchecked.
alter extent

- 182 -
CHAPTER

5 USER VARIABLES

5.1 Introduction
User Variables help you to increase the internal functionality of UniSim Design objects, such as streams and unit operations,
by dynamically attaching variables and code to those objects from within UniSim Design itself. User Variables are
indistinguishable from the variables built into UniSim Design objects and, as such, can be added to spreadsheets, targeted
by logic controllers, have their values specified by your input, etc.

TIP
For example, you could attach a User Variable to a stream to ensure that the flow rate is specified lower than a certain
value. Or, you could have a view appear when a vessel temperature exceeds a certain value.

User Variables let you attach code written in a Visual Basic© compatible macro language to simulation objects and specify
when that code is to execute. In doing so, you have a simple means of adding extra functionality to any UniSim Design
simulation.

5.2 Adding a User Variable


You can add User Variables on three levels within your case:

l Flowsheet Object. User Variables can be added to most UniSim Design flowsheet objects in the User Variables
matrix located on the User Variables page or the User Variables tab, of the object's property view.

Figure 5.1

- 183 -
Chapter 5 - User Variables

TIP
Regardless of where the User Variables matrix is located, the matrix is the same as the one shown in the figure
on the right except for streams. For, the 'General' tab will look the same, but with additional tabs for each non-
scalar variable that show their values. For energy streams, the view is the same with a button that opens a
detailed view (like the one in material streams).

l The extended user variable view is only applicable for material and energy streams.

Figure 5.2

l Flowsheet. If you want to attach a User Variable to the flowsheet on which you are working, open the Flowsheet
menu in the menu bar and select Flowsheet User Variables command.

Figure 5.3

l Simulation. If you want to add a User Variable to your simulation, open the Simulation menu in the menu bar and
select Simulation User Variables command.

- 184 -
Chapter 5 - User Variables

Figure 5.4

The User Variables view contains all the User Variables currently attached to the object. There is a drop-down list that
serves as a filter to sort the displayed User Variables by Data Type.

NOTE
There is no User Variables page or tab attached directly to the Column view. User Variables can be attached to the
individual components of the Column (tray section, reboiler etc.) only when you are in the column sub-flowsheet
environment.

The User Variables matrix lists the User Variables of the object owning the view. The name of the variable appears in the left
column, and the value appears in the right. Un-initialized values of type Real displays <empty> in the right column. Un-
initialized non-scalar values displays <Multidimensional>.

The User Variables are listed in their execution order. You can change the execution order using the icons in the toolbar.

The toolbar above the matrix lets you create, edit, and delete variables as well as filtering and ordering the list. Until one or
more User Variables are added to an object, some of the icons at the top of the view are disabled. The drop-down list, on the
left side of the icons, filters the matrix by data type and customer user type.

TIP
Before you add the first User Variable to an object, only the Create a New User Variable and the Sort Alphabetically
and Sort by Execution Order buttons are active.

The following table outlines User Variables view icon functionality:

Name Icon Function

Create a New User When this icon is clicked, the Create a New User Variable view opens.
Variable

Edit the Selected Select an existing User Variable and click this icon to open the view of the existing
User Variable User Variable for editing.

TIP
You can also open the edit view of a User Variable by doubleclicking on its name
in the matrix.

Delete the Selected Select the User Variable you want to delete and click this icon.
User Variable

- 185 -
Chapter 5 - User Variables

Name Icon Function

UniSim Design requires confirmation before proceeding with the deletion. If a


password has been assigned to the User Variable, the password is requested before
proceeding with the deletion.

Sort Alphabetically Click this icon to sort the User Variable list alphabetically.

Sort by Execution Click this icon to sort the User Variable list according to the order by which they are
Order executed by UniSim Design.

TIP
Sorting by execution order is important if your User Variables have order
dependencies in their macro code. Normally, you should try and avoid these
types of dependencies.

Move Selected Click this icon to move the selected User Variable up in execution order.
Variable Up In
Execution Order

Move Selected Click this icon to move the selected User Variable down in the execution order.
Variable Down In
Execution Order

Show/Hide Shows or hides the Variable Enabling checkboxes associated with each User
Variable Variable. By default, the checkboxes are not displayed.
EnablingCheckbox

To add a User Variable:

1. Access the User Variables matrix in the object where you want to associate the User Variables.
2. In the User Variables view, click the Create a New User Variable icon. The Create New User Variable view
appears.
3. Fill in the parameters for your new User Variable in the Create New User Variables view. Refer to the figure below

- 186 -
Chapter 5 - User Variables

for information on how to fill in the User Variable parameters.

Figure 5.5

TIP
You can define your own filters on the Filters tab of the User Variable editing view.

5.3 Importing/Exporting User Variables


You may import and export User Variables between cases via the Import Export User Variables view.

Figure 5.6

5.3.1 Exporting a User Variable


The following general procedure can be used to export User Variables:

- 187 -
Chapter 5 - User Variables

1. Select Import and Export User Variables command from the Simulation menu. This opens the Import and
Export User Variables view.

Figure 5.7

A list of User Variables currently attached to the case appears in the User Variables In Case group. The list on the
right displays a list of variables attached to the object selected in the list on the left.
2. In the User Variables In Case group, select the object containing the User Variable you want to export from the left
list, then select the User Variable you want to export from the right list.
3. Click the Export button. This opens the User Import/Export Variable File view.

Figure 5.8

4. Select the path you want to save the file in.


5. In the File name field type the name of the file you want to save the User Variables to and click the Save button.
The file is saved with *.huv file extension.

- 188 -
Chapter 5 - User Variables

5.3.2 Importing a User Variable


The following general procedure should be used for importing User Variables to a case.

1. Select Import and Export User Variables command from the Simulation menu. This opens the Import and
Export User Variables view.
2. Click the Select File button. This opens the User Variable Import/ Export File view.
3. Find the *.huv file that contains the User Variables you want to import and click the Save button.
The file name you selected should now appear in the User Variables In Export File group under the Current Export
File: text. A list of user variables in the file should appear in the list in this group.
4. Select the variable you want to import and click the Import button.

5.4 User Variable View


When you add a User Variable to an operation, the Create a New User Variable view, shown in the figure below, appears.

Figure 5.9

The only entry fields common to all user variable data types are the Name and Tag fields. The Name specified is the visible
name of the variable used throughout UniSim Design. The Tag is the unique identifier used to access this user variable
programmatically. These two strings are often identical and the variable tag automatically defaults to be the same as the
variable Name, if not specified. You are prompted to provide an alternate Name or Tag if they are not unique among all User
Variables attached to the object. You are also prompted to provide a cryptic tag if the User Variable uses a security
password.

- 189 -
Chapter 5 - User Variables

TIP
For more information on using security passwords, see Security Tab.

Finally, the Show or Hide Variable Details icon, in the upper-right corner of the editing view, expands or shrinks the
Code Editor. This icon either hides or reveals most of the attribute fields of the User Variable.

Normally, once a User Variable has been defined, its attributes remain fairly static and most effort is directed toward editing
and debugging its macro code. For this reason, the code field is presented in its expanded position when debugging or
editing the User Variable, and in its reduced position when creating the variable.

5.5 Data Types


5.5.1 Type Drop-down List
Five data types are available from the Type drop-down list:

Figure 5.10

l Real (double precision floating point number)


l Enumeration
l Text
l Code Only
l Message

The drop-down list at the top of the User Variables view can change, depending on the additional requirements for the
specified data type.

5.5.2 Dimensions Drop-down List


When a Real, Enumeration or Text data type is specified, the Dimensions drop-down list is available on the User Variables
view. Data dimensions available from the drop-down list include:

l Scalar
l Vector (array)
l Matrix
l Cube (3 dimensions)

5.5.3 Real Data Type


[Link] Units Drop-down List

The Units drop-down list is available only when Real is selected as the Data Type.

- 190 -
Chapter 5 - User Variables

Figure 5.11

From this drop-down list you can select one of the existing variable types built into UniSim Design in order to determine units
and valid numeric range for the new variable. For example, selecting Temperature results in a User Variable displaying units
of temperature that accepts input in Celsius, Kelvin, Rankin or Fahrenheit. That same variable would also automatically
disallow out of range input such as a negative Kelvin value or a Celsius value less than -273.15.

This drop-down list defaults to variable type Index, which is a unitless, generic type. The Variable Changing macro can be
used to provide custom filtering of input values for a user variable if desired. See the Macros Tab for more details.

5.5.4 Enumeration Data Type


When you select Enumeration as the User Variable type, the Enumeration Values button appears directly below the
Dimensions drop-down list:

Figure 5.12

Click this button and the Enumeration Values view, containing a two-column matrix appears:

Figure 5.13

Entering text labels in the left column and corresponding numeric values in the right column to define the enumeration. The
resulting Enumeration Variable appears in UniSim Design views as a drop-down list containing these text labels. Selecting
one of these labels assigns the corresponding value to the User Variable.

- 191 -
Chapter 5 - User Variables

5.5.5 Message Data Type


Type Message variables have a single purpose: to execute their Fire macro when the user variable is invoked
programmatically, usually in response to you clicking a button. Message User Variables are currently applicable mainly to
UniSim Design Extensions.

5.5.6 Code Only Data Type


A user variable of type Code Only allocates no storage space for itself but still serves as a host for attaching macro code. If
you want to write macro code that does not preserve any results or state information, then a Code Only User Variable is the
most efficient choice.

5.6 User Variables Tabs


Additional settings appear in the central pane of the User Variable editing view and are grouped under five tabs:

l Macros
l Attributes
l Filters
l Security
l Defaults

5.6.1 Macros Tab


The Macros tab lists the macros that can be enabled for the variable currently being edited. The macros listed on the left side
of the tab vary depending on the level within your simulation that the User Variable was created. These macros are
described in the following table:

Object Macros

Flowsheet PreExecuted. Invoked when the Steady State solver is about to execute the flowsheet object that
Object owns this variable.
PostExecuted. Invoked immediately after the Steady State solver executes the flowsheet object that
owns this variable.

Flowsheets PreSolve. Invoked before the Steady State solver begins solving the flowsheet.
PostSolve. Invoked after the Steady State solver completes the flowsheet solution.

Simulation Run. Explicitly invoked when the Run button on the Simulation Case User Variables view is clicked.
Case

Enable the macro by activating the checkbox to the right of the macro name, as shown in the figure below. This User
Variable is attached to a flowsheet object and, as such, has a Pre-Execute and Post-Execution macro. Once checked, the
empty sub-routine code for the macro is initialized in the Code Editor.

- 192 -
Chapter 5 - User Variables

Figure 5.14

The checkboxes in the Variable group on the right of the Macros tab enables macros that are invoked when the value of the
User Variable is modified or accessed.

The sub-routines that are added to the User Variable when the checkboxes, in the Variable group, are checked include:

Sub-routine Initialization

Variable Called when an attempt is made to specify a new value for the User Variable from any source other than
Changing the variable’s own macro [Link] new value is available for inspection using the ActiveVariableWrapper
macro keyword. If the Variable Changing code chooses to disallow the change, it must set the
AllowThisChange property to false.

Variable Invoked immediately after a new value has been assigned to the variable.
Changed

Variable Invoked whenever the value for a User Variable is about to be read.
Query

The following code example demonstrates simple bounds checking for a numeric User Variable using a Variable Changing
sub-routine:

Sub VariableChanging()
If [Link] > 100 Or
[Link] < 1 Then
AllowThisChange = False
MsgBox "Valid values are in the range 1-100", vbOkOnly, "User Variable"
End If
End Sub

The presence of code for a particular macro sub-routine is not sufficient to have that code invoked - the macro's checkbox
must also be enabled. If you disable a macro, UniSim Design requires confirmation before it proceeds with this action.
Pasting or typing macro sub-routine code in to the Code Editor causes the specific macro to be automatically enabled.

- 193 -
Chapter 5 - User Variables

NOTE
If you disable a macro with its code still present and then type or paste in the Code Editor, the macro is automatically re-
enabled.

5.6.2 Attributes Tab


The Attributes tab has two associated groups:

l Activation
l Solver

[Link] Activation Group

The Activation group refers to the scope of the variable. A User Variable is defined for an entire class of objects but can be
optionally enabled only in specific instances of these objects or made to appear automatically in all instances. Specify the
activation by choosing from either the Automatic or User Enabled radio button.

Figure 5.15

Automatic User Variables appear in all instances of the object type for which it is defined within a simulation. Most objects
have a discrete type such as pumps or mixers. However, some types can manifest themselves in different forms. For
example, streams can be either material or energy streams and share their User Variables. That is, variables created in
material streams are also available to energy streams, and vice versa. If you do not want a User Variable to be available
universally across an object type, you can specify it to be User Enabled setting by selecting the User Enabled radio button.

With the User Enabled radio button selected, specific variables appear only in certain instances of an object type. The
variable can be turned on or off for specific instances of objects of that type. To do this, use the enabling column of the User
Variables matrix in the objects' property views.

- 194 -
Chapter 5 - User Variables

Figure 5.16

The Enable In <Object Name> checkbox of the Activation group is a short-cut for checking the enable switch of the variable
in the current object.

The Automatic setting overrides any previous User Enable settings. UniSim Design, however, preserves the user setting
and if the variable is switched back to User Enabled, the previously specified setting is restored. This means that you can
easily switch specific variables on and off across an entire object type simply by editing the variable from any object instance
and changing it between Automatic and User Enabled.

Even if no instances of a particular object type exist in a simulation case, any User Variables previously defined for that object
type are preserved. If new instances of the type are ever added to the case, they automatically inherit the previously defined
User Variables.

[Link] Solver Group

The Solver group of the Attributes tab contains a single checkbox labelled Trigger Solve. This checkbox is only available for
Real and Enumeration data types. When enabled, the User Variable causes the object instance that owns it to recalculate
whenever the value of the variable is changed. This is analogous to the UniSim Design Process Variable.

Figure 5.17

5.6.3 Filters Tab


The Filters tab provides a mechanism for creating and assigning custom variable types that can be used to filter User
Variables lists.

- 195 -
Chapter 5 - User Variables

Figure 5.18

To add a new filter type, click the Edit button. The Filter Names view opens:

Figure 5.19

From this view you can create new filter names. Once the new filter names have been specified, click the OK button to return
to the User Variable view. If you do not want to keep the filter names you specified, click the Cancel button. New filter names
appear in the list on the right of the Filters tab.

The native data type (Real, Text, etc.) is always included in the list of active filters. It cannot be deleted. To include a newly
created filter name with the active filters, highlight the filter name on the right and click the Add button. To remove a filter from
the active list, click the Remove button.

NOTE
Filtering can only be applied using the drop-down list of the User Variable page of Unit Operation views.

5.6.4 Security Tab


There are two levels of User Variable protection available on the Security tab. The two levels are split into two groups on the
tab:

l Password to Edit/Delete
l Variable

Figure 5.20

- 196 -
Chapter 5 - User Variables

Password to Edit/Delete Group

When you have assigned a password, you are required to enter that password before the variable can be edited or deleted.
As a convenience, if the password is entered correctly when requested it is not requested again until the next time the case is
opened. However, you are always required to enter the password if you are attempting to delete a User Variable. Combining
a password with the Automatic attribute would guarantee that a User Variable is always present in any instance of its owning
object.

NOTE
A suitably cryptic variable Tag is highly recommended when using a password in order to protect against programmatic
access to the variable.

Variable

The second level of security is the Calculate Only setting. Check this checkbox to ensure that only the User Variable’s macro
code can change its value.

5.6.5 Defaults Tab


The Defaults tab lets you assign a default value to the User Variable. Default value may only be assigned to scalar variables
of type Real, Enumeration, and Text. Without an explicit default value, scalar variables of these types are initially created with
empty values.

Figure 5.21

5.7 Code Editor


The Code Editor is where you write, using the Visual Basic® compatible macro language, and debug the macro code that
you are attaching to a simulation object. You can add break points to the code by simply clicking in the bar that borders the
left side of the Code Editor. If there are no break points in your code, the macros execute seamlessly as part of your UniSim
Design case. The Code Editor is shown below:

- 197 -
Chapter 5 - User Variables

Figure 5.22

TIP
Once changes are made to your code in the Code Editor, click the Start Solver icon to continue with the UniSim Design
calculations.

5.7.1 Tool Tip Text


A single quote (') preceding text in the Code Editor indicates a Visual Basic® user comment. For UniSim Design User
Variables, any user comments written in the first three lines of the Code Editor appears as a tool tip when the cursor is placed
over the User Variable name in the matrix on the User Variable page or tab. See Figure: 5.29 .

5.8 User Variable Examples


5.8.1 Dew Point Temperature Variable
The following User Variable example can be applied to any UniSim Design simulation. In it, you create a new User Variable
that calculates and displays, in the User Variable Matrix, the Dew Point Temperature for a material stream.

- 198 -
Chapter 5 - User Variables

1. Open any material stream in your simulation to the User Variables page:

Figure 5.23

2. Click the New User Variable icon at the top of the user variable matrix. The Create New User Variable view
opens.
3. In the Create New User Variable view, enter the following information in the indicated fields:

Field Input

Name DewPt Temp

Type Real

Units Temperature

TIP
When you specify a Name, it is automatically copied to the Tag field.

4. On the Attributes tab, select the User Enabled radio button in the Activation group. You are then required to
manually enable the variable in any of the material streams that requires this variable.

- 199 -
Chapter 5 - User Variables

Figure 5.24

5. On the Security tab, check the Calculate Only checkbox. This ensures that no one attempts to specify a value for
this User Variable other than its macro.

TIP
This step is a convenience and not a requirement for macro execution.

Figure 5.25

6. On the Macros tab, check the PostExecute() checkbox. An empty sub-routine automatically appears in the Code
Editor. Enter the PostExecute macro as follows:

Sub PostExecute()
On Error GoTo ErrorHandler
Dim myFluid As Object
[Link]
Set myFluid = [Link]
FS = 0

- 200 -
Chapter 5 - User Variables

FS = [Link]([Link],1.0)
If FS = 0 Then ' fsFlashOK
[Link]([Link].
GetValue)
End If
ErrorHandler:
Exit Sub
End Sub

The error checking is in place to so that the macro can handle <empty> values. If the value is <empty> the macro
exits the sub-routine and continue on to the next one.

A new User Variable of type Temperature, named DewPt Temp, now exists in all current and future instances of streams in
this case. The DewPt Temperature automatically calculates its value during a steady state solve pass immediately after its
owning stream executes.

NOTE
The user variable exists in both Material and Energy streams, but the dew point calculation only applies to Material
streams. The variable fails to calculate a value in energy streams; this is harmless, but the macro could be modified to
test for the stream type before performing its calculations.

Re-calculate the stream and the dew point temperature value appears in the User Variables page for all the streams in your
simulation.

The figure below shows two streams views with the calculated values:

Figure 5.26

- 201 -
Chapter 5 - User Variables

5.8.2 Automatic Pump Energy Stream


The User Variable created in this example automatically adds an energy stream to a pump operation whenever both Feed
and Product streams are connected. This is accomplished through an Enumeration type User Variable. The code is such
that the work of creating and connecting the Energy stream to a pump is performed only once, unless otherwise specified.
The energy streams added is named using the operation name, followed by “_W.” For instance, the energy stream for pump
P- 100 is named P-100_W.

1. Install a pump into the PFD, if the simulation case does not already have a pump. Open the pump property view.
2. Go to the User Variables page on the Design tab.

3. Click the New User Variable icon from the top of the matrix.

Figure 5.27

4. Enter the following information for the fields in the resulting Create New User Variable view, as specified in the
following table.

Field Input

Name QStream

Type Enumeration

5. Edit the enumeration values by clicking the Enumeration Values button. Create two labels in the left column of this
view named Not Yet Run and Has Run; assign the values 0 and 1 to them, respectively.

Figure 5.28

- 202 -
Chapter 5 - User Variables

6. When completed as shown in the figure above, click the OK button.

NOTE
The Label names are not important, but the numeric values of the two must match the NotYetRun and HasRun
constants used in the associated code.

7. On the Attributes tab, select the Automatic radio button in the Activation group. This creates the variable in all
current and future instances of pumps in your simulation case.
8. Check the PostExecute() checkbox found on the Macro tab. Enter the following PostExecute macro in the Code
Editor.

' Automatically add and connect an energy


stream once feed and product
' streams are connected.
' The process will not repeat unless this variable
is reset to NotYetRun.
' Global constants matching the enumeration values
of this user variable.
' Note that only constant values are useful here.
Non-constant global
' variables will lose their values
' between invocations of this macro code. Create
user variables when
' storing persistent 'information.
Const NotYetRun = 0
Const HasRun = 1
' The use of both late and early binding are
demonstrated here.
' Late binding should be used during development
and testing since it is
' more robust and produces more useful error messages.
' Early binding should be used where performance
is an issue as it is
' slightly faster. Or when an explicit 'cast'
to a certain interface of
' an object is required.
Sub PostExecute()
' Error handling minimized for clarity.
On Error GoTo UnknownError
'Early binding of PumpOp object.
Dim pump As PumpOp
'ActiveObject is the object that owns this
user variable.
Set pump = ActiveObject
' Early binding of RealVariable object.
Dim thisvar As RealVariable
' ActiveVariableWrapper is the
InternalVariableWrapper containing this
' user variable.
Set thisvar = [Link]
' Only run once. If the user wants
me to run again,
' change my value to "Not Yet Run'
If [Link] = HasRun Then GoTo AlreadyAdded
If [Link] = False Then
Exit Sub
ElseIf [Link] = False Then
Exit Sub
ElseIf [Link] = False Then
'Late binding of Streams collection and
Stream object. Dim strs As Object
Dim newstr As Object
Set strs = [Link]
Dim strName As String

- 203 -
Chapter 5 - User Variables

strName = [Link] + "_W"


Set newstr = [Link](strName)
[Link] = True
[Link] = newstr
[Link] = HasRun
Else
[Link] = HasRun
End If
Exit Sub
AlreadyAdded:
Exit Sub
UnknownError:
End Sub

Now, whenever both inlet and outlet streams are connected to any pump in the case, and no energy stream is currently
connected to that pump, a new energy stream is automatically created and connected to that pump.

For the pump and streams shown on the left of the figure below, once the inlet and outlet streams are connected, the stream
PUMP_W is automatically created, as shown to the right:

Figure 5.29

The first three lines of comment in your code appear as tool tip fly by when the cursor hovers over the variable in on the User
Variables page:

- 204 -
Chapter 5 - User Variables

Figure 5.30

This process changes the value of the Enumeration User Variable containing the code to Has Run, as shown above. This
ensures that the work of creating and connecting the energy stream is not repeated for that pump.

The User Variable enumeration can be explicitly toggled for any pump instance by changing its value in the User Variable
Matrix on the User Variables page. Select the value in the right column of the matrix and then access the drop-down list (see
the figure below). You can select Not Yet Run from the list.

Figure 5.31

TIP
Toggling the setting back to Not Run Yet would allow the macro to once again add and connect a new Energy stream
during a steady state execution of the pump when inlet and outlet streams are connected.

- 205 -
CHAPTER

6 USER UNIT OPERATION

6.1 Introduction
The User Unit Operation is a UniSim Design unit operation much like any other, except that its behaviour is defined entirely
with Visual Basic® compatible code that you provide. It allows you to create additional unit operation types without the
complexity involved in creating an Extension Unit Operation.

With properly designed code, a user-defined unit operation type can be seamlessly integrated in to UniSim Design cases and
for use by third parties. However, this level of sophistication and user-friendliness is not necessary for all user ops - you may
want to quickly create a type that is specialized for use in specific situations or at a specific location in a case.

6.2 Adding a User Unit Operation


Adding a User Unit Operation to a case requires you to follow a slightly different procedure than is normally followed when
adding the standard UniSim Design unit operations. Before you can add the initial User Unit Operation to a case, you must
first create an operation Type. The Type is simply a classification for the User Unit Operation, much like Pumps or Heaters
are types for unit operations that currently exist in UniSim Design.

To add a User Unit Operation:

1. Do one of the following:

l Open the Object Palette (press F4) and double-click the User Ops icon from the Object Palette.
l Select Add Operation command from the Flowsheet menu, or press F12. The UnitOps view appears.
Select User Unit Ops from the Available Unit Operations group on the UnitOps view.

NOTE
If you use the User Ops filter on the UnitOps view, the left side of the view changes to include the same buttons
that appear in the view on the figure below.

2. When the User Unit Operation has been added, the following view appears:

- 206 -
Chapter 6 - User Unit Operation

Figure 6.1

The view shown above lists the available User Unit Operation types, lets you add new operations of existing types,
and lets you create or delete operation types.
3. Click the Create Type button to add a new type to the list. The following view opens:

Figure 6.2

4. Enter a descriptive name for the operation type you want to create and click the OK button. This type is added to the
Available User Unit Operation Types group in the Add a User Unit Operations view.
5. To add an operation of that type, highlight the type you created and click the Add button. The User Unit Op view
appears:

- 207 -
Chapter 6 - User Unit Operation

Figure 6.3

TIP
By default, the second feed and product nozzles, as well as the energy nozzles are checked.

6.2.1 Importing and Exporting a User Unit Op


The Add a User Unit Operation view contains two buttons: Import and Export that allow you to transfer User Unit Operations
between cases.

[Link] Exporting a User Unit Op

1. To export a User Unit Op, simply select the User Unit Op type you want to export and click the Export button.
2. The Export User Unit Op view appears. Type the name of the file you want to save under in the File name field.
3. Choose the path you want to save the file to.
4. Click the Save button.
5. The file is saved with *.huo file extension.

[Link] Importing a User Unit Op

1. Click the Import button on the Add a User Unit Op view.


2. From the Import User Unit Op view, select the *.huo file that contains the User Unit Op type you want to import.
3. Click the Open button. This should add the User Unit Op to the list of Available User Unit Operation Types.

6.3 User Unit Op Property View


Unlike most other UniSim Design unit operations, the User Unit Op view consists of only two tabs: Design and Worksheet.

- 208 -
Chapter 6 - User Unit Operation

Figure 6.4

TIP
By default, the second feed and product nozzles, as well as the energy nozzles are checked.

6.3.1 Design Tab


There are five pages associated with the Design tab:

l Connections
l Code
l Variables
l Notes
l Export

[Link] Connections Page

On the Connections page you can specify the Name of the operation, and attach Feed, Product, and Energy streams.

- 209 -
Chapter 6 - User Unit Operation

Figure 6.5

You can add as many Feed and Product streams as your operation requires. Each User Unit Operation has two material
feed nozzles, two material product nozzles, one energy feed nozzle, and one energy product nozzle available. Each of these
nozzles can accept multiple stream attachments. UniSim Design provides default nozzle names - Feed1, Product1, etc.
These names can be changed to better describe the functioning of your operation.

The first feed and first product nozzles are always active, but the other four nozzles can be activated or deactivated
depending on the type of requirements of your User Unit Operation. Attach streams to the nozzles in the matrices directly
below the nozzle names. Highlight the <empty> cell and select an available stream name from the drop-down list, or enter
the stream name directly. To change the name of the nozzle, simply click on the appropriate field and begin typing.

If you want a second nozzle for feed or product streams, check the checkbox directly to the right of the second stream nozzle
field (Feed2 or Product2). The Connections page changes and activates another matrix. This matrix allows you to attach the
streams to a second stream nozzle.

If your User Unit Operation requires Energy streams, check the checkboxes to the right of the Energy In or Energy Out fields
and once again, a stream matrix becomes visible.

Nozzles can also be configured programmatically. This is the preferred mechanism when designing a User Unit Operation
that may be added multiple times to a flowsheet or different cases. See the code in Dehumidifier Example for an example
of automatically configuring nozzles in the Initialize sub-routine.

[Link] Code Page

On the Code page, you add the Visual Basic® compatible code that defines the behaviour of your User Unit Operation.

- 210 -
Chapter 6 - User Unit Operation

Figure 6.6

The code environment in the User Unit Operation is very similar to that described for the User Variables, see User
Variablesfor more information.

Code can be added by clicking the Edit button. This opens the Edit Existing Code view. The view in the figure below shows
the three empty sub-routines that appear before you begin adding code in the view.

Figure 6.7

The three User Unit Operation sub-routines are described in the following table:

- 211 -
Chapter 6 - User Unit Operation

Sub-routine Action

Initialize() Called immediately before the first time Execute is called. This sub-routine should be used to set up
the unit operation. Decide which nozzles are valid and name them; create any variables that will be
needed and give them initial values, etc.

Execute() Called whenever a trigger solve variable of the unit operation is changed, and whenever any of its
attached streams re- calculates. This sub-routine should perform all of the unit operation’s calculations.
In this sub-routine only, it is permissible (and recommended) to use the Calculate method to write
data to variables of the operations attached streams. These variables are then displayed in black in
UniSim Design, and cause an inconsistency error if any other object attempts to calculate their values.

StatusQuery() Called whenever UniSim Design wants to update the status information for its objects. This sub-routine
should be used to provide warning and error messages for any missing connections, missing variable
values, etc. These messages will be displayed in the UniSim Design status bar, as well as at the bottom
of the User Unit Operation’s view.

Empty versions of these three sub-routines are automatically generated for each new User Unit Operation Type.

NOTE
It is recommended that any sub-routine that you do not want to be implemented be deleted or turned in to comments by
preceding each line with the single-quote comment character. This ensures that UniSim Design does not waste time
calling an empty sub-routine. The sub-routine can be implemented or un-commented at any time.

The left border of the Code page is a development tool for you to use as you add code to your operation. You may add break
points in this border thereby allowing you to step through your code. Simply click the primary mouse button in the margin on
the left side of the code pane next to the line you want to insert the break for.

The standard debugging view is shown as follows:

- 212 -
Chapter 6 - User Unit Operation

Figure 6.8

[Link] Variables Page

You can attach User Variables to the User Unit Operation, as you can to any flowsheet object, to further customize your
simulation case.

TIP
User Variables do not have the PreExecute and PostExecute macro options.

User Unit Operation User Variables can be used to store calculation results, persistent state information, etc. These
variables can be created manually from the Variables page, or programmatically using the CreateUserVariable method of
the Active Object interface.

TIP
The Execute macro of the User Unit Operation itself is intended to perform all calculations required to implement the
operation and its variable values.

For more information on adding code and implementing this option, see User Variables.

[Link] Notes Page

The Notes page provides a text editor where you can record any comments or information regarding the User Unit
Operation, or pertaining to your simulation in general.

- 213 -
Chapter 6 - User Unit Operation

[Link] Export Page

The Export page allows you to export the User Unit Operation, by clicking the Export button and entering the file name and
file path for the User Unit Operation. The file is saved with *.huo file extension.

You can also add a description about the User Unit Operation in the Type Description group.

6.3.2 Worksheet Tab


The Worksheet tab provides the same information as the default Material Streams page of the Workbook. However, this
page only displays the streams that are currently attached to the User Unit Operation.

6.4 Dehumidifier Example


The following example shows how to create a new User Unit Operation. This operation will function as a dehumidifier. From
a single feed stream containing water, the operation copies the conditions and composition of its feed stream in to two
product streams. The first product consists of the stream composition minus any water; the second is a pure water stream.

1. Begin by creating a new case. Click the New Case icon .


2. Create the following fluid package and then enter the Main Simulation Environment:

Property Package Components

PRSV Methane, Ethane, Propane, i-Butane, n-Butane, i- Pentane, H2O

3. Specify a material stream Feed, with the following properties:

Stream Properties Value

Temperature [C] 23.0000

Pressure [kPa] 303.9750

Molar Flow [kgmole/h] 100.0000

Comp Mole Frac [Methane] 0.40

Comp Mole Frac [Ethane] 0.20

Comp Mole Frac [Propane] 0.15

Comp Mole Frac [i-Butane] 0.10

Comp Mole Frac [n-Butane] 0.05

Comp Mole Frac [i-Pentane] 0.05

Comp Mole Frac [H2O] 0.05

4. Add two more material streams: Dry Product and Wet Product.

5. Add a new User Unit Operation to your case. Double-click the User Ops icon from the Object Palette. The Add
a User Unit Operation view appears.
6. Click the Create Type button on the Add a User Unit Operation view. Enter Dehumidifier as the New User
Operation Type name field and click the OK button.

- 214 -
Chapter 6 - User Unit Operation

Figure 6.9

The Dehumidifier operation type is added to the list of User Ops types for the current case.
7. After you click the OK button, both New User Operation Type Name and Add a User Unit Operation views close,
and User Unit Op view for the dehumidifier appears as shown in the figure below.

Figure 6.10

This operation requires that a single feed nozzle and both product nozzles are active. As no energy stream is
required for the operation, the energy nozzles can be left unchecked.
At this point, the op-100 is unable to perform any calculations on any attached streams.
8. To add code, switch to the Code page and click the Edit button. This opens the Edit Existing Code view where you
can enter the following code:

Sub Initialize()
' Of the four optional nozzles, we only
want the second products:
ActiveObject.Feeds1Name = "Feed"
ActiveObject.Products1Name = "Dry Product"
ActiveObject.Feeds2Name = "Inactive Feed"
ActiveObject.Feeds2Active = False
ActiveObject.Products2Name = "Water Product"
ActiveObject.Products2Active = True
[Link] = "Inactive
Energy In"
[Link] = False

- 215 -
Chapter 6 - User Unit Operation

[Link] = "Inactive
Energy Out"
[Link] = False
End Sub
Sub Execute()
On Error GoTo EarlyExit
' get the feed stream
Dim feed As Object
Set feed = [Link](0)
If feed Is Nothing Then GoTo EarlyExit
' get the dry product stream
Dim prod As Object
Set prod = [Link](0)
If prod Is Nothing Then GoTo EarlyExit
' get the water product stream
Dim wtr As Object
Set wtr = [Link](0)
If wtr Is Nothing Then GoTo EarlyExit
' find the position of water in the current
Fluid Package's component
list
Dim theComps As Object
Set theComps = [Link].
[Link]
waterPosn = [Link]("H2O")
' get the array of component molar
flows from the feed stream
Dim CMFs As Variant
CMFs = [Link]
e WaterFlow = CMFs(waterPosn)
DryFlow = [Link] - WaterFlow
' calculate the Temperature,
Pressure, and Flow of the water product
stream
[Link]([Link])
[Link]([Link])
[Link](WaterFlow)
' remove the water from the CMF array
CMFs(waterPosn) = 0.0
' calculate Temperature, Pressure,
and ComponentMolarFlows of the dry
stream
[Link]([Link])
[Link]([Link])
[Link](DryFlow)
' calculate the composition of the dry stream
For i = 0 To [Link] - 1
CMFs(i) = CMFS(i) / DryFlow
Next i
[Link](CMFs)
' calculate the composition of the water
stream (pure water)
For i = 0 To [Link] - 1
CMFs(i) = 0.0
Next i
CMFs(waterPosn) = 1.0
[Link](CMFs)
' tell the Solver we're done
' (this will remove the "Not Solved"
status message)
[Link]
Exit Sub
EarlyExit:
' not enough info to calculate
End Sub
Sub StatusQuery()
On Error GoTo ThatsAll
Dim GotOne As Boolean

- 216 -
Chapter 6 - User Unit Operation

GotOne = False
If [Link] = 0 Then
GotOne = True
[Link]
(slMissingRequiredInformation, 1,
"Feed Stream Required")
End If
If [Link] = 0 Then
GotOne = True
[Link]
(slMissingRequiredInformation, 2, "Dry
Product Stream Required")
End If
If [Link] = 0 Then
GotOne = True
[Link]
(slMissingRequiredInformation, 3,
"Water Product Stream Required")
End If
' If we're missing an attachment,
don't bother checking for
any other problems
If GotOne = True Then GoTo ThatsAll
On Error GoTo NoWater
waterPosn = [Link]
.[Link]("H2O")
GoTo AfterWaterCheck
NoWater:
GotOne = True
[Link](slError,
11, "No Water in Current Fluid Package")
AfterWaterCheck:
On Error GoTo ThatsAll
Dim feed As Object
Set feed = [Link](0)
If Not [Link]
[Link]
(slMissingOptionalInformation, 12,
"Feed Temperature Unknown")
GotOne = True
End If
If Not [Link]
[Link]
(slMissingOptionalInformation, 13,
"Feed Pressure Unknown")
GotOne = True
End If
If Not [Link] Then
[Link]
(slMissingOptionalInformation, 14,
"Feed Flow Unknown")
GotOne = True
End If
' The composition's IsKnown will return a
Variant containing an array of Booleans.
' We must make a variable containing the array
before we attempt to access a data
' member.
' (i.e., "[Link].
IsKnown(0)" will probably not work)
CMFsKnown = [Link]
If Not CMFsKnown(0) Then
[Link]
(slMissingOptionalInformation, 15,
"Feed Composition Unknown")
GotOne = True
End If
If GotOne = True Then GoTo ThatsAll

- 217 -
Chapter 6 - User Unit Operation

If [Link] > 1 Then


GotOne = True
[Link](slWarning,
20, "Additional Feed Stream(s) Ignored")
End If
If [Link] > 1 Then
GotOne = True
[Link](slWarning,
20, "Additional Feed Stream(s) Ignored")
End If
If [Link] > 1 Then
GotOne = True
[Link](slWarning,
21, "Additional Dry Product Stream(s) Ignored")
End If
If [Link] > 1 Then
GotOne = True
[Link](slWarning,
22, "Additional Water Product Stream(s) Ignored")
End If
Dim BogusCnxn As Boolean
BogusCnxn = False
If [Link] > 0 Then
BogusCnxn = True
ElseIf [Link] > 0 Then
BogusCnxn = True
ElseIf [Link] > 0 Then
BogusCnxn = True
End If
If BogusCnxn = True Then
GotOne = True
[Link](slWarning, 7,
"Connection(s) to Inactive Nozzles")
End If
ThatsAll:
End Sub

When this code has been inserted, the Dehumidifier operation is complete. Any additional Dehumidifier objects
added to the case will automatically access the same code, and function identically to the one already created.
9. Click the OK button to close the Edit Existing Code view and return to the Code page of the User Unit Op view.

- 218 -
Chapter 6 - User Unit Operation

Figure 6.11

The Initialize sub-routine code automatically configures the nozzles appropriately.

TIP
The original instance of the Dehumidifier may invoke Initialize before you have entered the example code.

10. Click the Initialize button in the Manual Invoke group to ensure that the nozzles are reconfigured.
Any future instances of Dehumidifier will not require this explicitly extra Initialize once the macro code has been
entered and debugged.
11. Complete the Connections page by attaching streams as shown in the figure below:

TIP
Deactivate the extra nozzles by clearing the checkboxes to the right of the nozzle names.

- 219 -
Chapter 6 - User Unit Operation

Figure 6.12

When a stream is connected to the first nozzle attachment, the Initialize sub-routine should run. The Execute and
StatusQuery sub- routines should also run, because the attachments are fully defined.

If streams had not already been attached to the nozzles on the Connections page, the StatusQuery would have prompted
you to provide sufficient attachments and information for the Execute to run successfully.

The PFD for the solved case, along with an attached stream table, is shown in the figure below:

Figure 6.13

- 220 -
CHAPTER

7 CUSTOMIZATION FAQ

7.1 Automation FAQ


1. Whenever I change the Basis using Automation, UniSim Design displays a view “Do you want to be left in HOLDING
mode...” which freezes the Automation application (Visual Basic, Excel, etc.). How do I make changes and avoid the
view?
Ans: When changing the Basis via Automation, use the following syntax:

[Link] = False
[Link]
' {make Basis changes}
[Link]
[Link] = True

Where usdCase is a SimulationCase object. This will prevent the view from appearing by putting the simulation into
hold mode before making the Basis changes and taking the simulation out of hold mode once the Basis changes are
complete.
2. How do I add a property package to UniSim Design or change the existing property package using Automation?
Ans: UniSim Design property packages must be referred to by their internal name when using Automation. A list of
the name is below:

Internal Name External UniSim Design Property Package Name

PengRob PR

SRK SRK

SourPR Sour PR

SourSRK Sour SRK

KDSRK Kabadi Danner

ZJRK Zudkevitch Joffee

PRSV PRSV

Wilson Wilson

Uniquac UNIQUAC

Nrtl NRTL

VanLaar van Laar

Margules Margules

CNull Chien Null

- 221 -
Chapter 7 - Customization FAQ

Internal Name External UniSim Design Property Package Name


ExtNRTL Extended NRTL

GenNRTL General NRTL

CS Chao Seader

GSD Grayson Streed

Antoine Antoine

BraunK10 BraunK10

EssoTabular Esso K

AsmeSteamPkg ASME Steam

Steam84Pkg NBS Steam

Amine Amine

TabularPkg Tabular Package

LKP Lee-Kesler Plocker

The text below is a UniSim Design macro which demonstrates the above.

Sub Main
Set usdApp = Application
Set usdCase = [Link]("C:\[Link]")
Set usdBasis = [Link]
Set usdFldPkgs = [Link]
Set usdFldPkg = [Link](0)
Set usdPropPkg = [Link] [Link] "Steam"
Set usdFldPkg = [Link]("Steam")
[Link] = "asme steam"
End Sub

3. How do I use Automation to attach multiple feed and product streams to unit operations which can accept them
(such as the tee, balance, separator, etc.)?
Ans: The Add method of the Feeds property is used to add multiple feed streams to a unit operation object one at a
time.
For example, if usdMix refers to a Mixer unit operation object and usdFeed1 and usdFeed2 refer to material stream
objects, the following syntax would add the material streams as feeds to the mixer.

[Link] usdFeed1
[Link] usdFeed2

The same is true for the Products property of unit operations which can have multiple products. For example,

[Link] usdProduct1
[Link] usdProduct2

The following code is a UniSim Design macro which demonstrates the above.

- 222 -
Chapter 7 - Customization FAQ

Sub Main
' This macro assume an active sheet which
has the following Streams: Feed1, Feed2, Product
Set usdCase = ActiveCase
Set usdFS = [Link]
Set usdOpers = [Link]
Set usdFeed1 = [Link]("Feed1")
Set usdFeed2 = [Link]("Feed2")
Set usdProduct = [Link]("Product")
' Add a Mixer named Mix-100
[Link] ("Mix-100", "MixerOp")
' Set an Object reference To the Mixer
Set usdMix = [Link]("Mix-100")
' **Add feed Streams To the Mix-100
(must be added one at a Time, can’t
use an Array of Streams)
[Link] usdFeed1
[Link] usdFeed2 [Link] =
usdProduct
End Sub

4. How do I use Automation to refer to a stream name which is a number?


Ans: UniSim Design assumes any variable which contains a number (regardless of whether it is text or numeric
format) is an index number. For example,

Stream_Name = "2"
usdStream = [Link](Stream_Name)

usdStream refers to the stream object with an index number of 1, not the stream named 1. An index number is
used to identify the order in which a stream was added. Thus in the above examples usdStream refers to the second
stream added to the flowsheet, regardless of its name.
To be able to use numeric stream names, the following syntax must be used:

Stream = [Link](CStr(Stream_Name))

CStr converts whatever is in the parentheses in to a string, regardless of its original format. Therefore, a 1 is
interpreted as a “1” and Feed is interpreted as “Feed”.
5. How do I obtain a viscosity (or WatsonK or surface tension or any number of other physical properties) from a Fluid
object?
Ans: A viscosity cannot be obtained from the Fluid object, it must be obtained from the FluidPhase objects within
the Fluid object (FluidPhases, VapourPhase, LightLiquidPhase, HeavyLiquidPhase). For example, if there is a
heavy liquid phase then to obtain the viscosity (in UniSim Design internal units of cP), the following syntax is used:

usdViscosity = [Link]
where:
usdFluid = a Fluid object

6. How do I obtain component mass/molar/volume fractions from a Fluid object?


Ans: Unfortunately, the Fluid object differs from the ProcessStream object with regards to accessing component
mass/molar/volume fractions. The following table shows the property object which is used to access the different
types of component fractions from the Fluid and ProcessStream objects.

- 223 -
Chapter 7 - Customization FAQ

Object Fluid ProcessStream

Mass MassFractions ComponentMassFraction

Molar MolarFractions ComponentMolarFraction

Volume IdealLiquidVolumeFractions ComponentVolumeFraction

7. Why can’t I use the Calculate or CalculateAsFluid methods to set a value as Calculated?
Ans: The Calculate and CalculateAsFluid methods can only be used in the Execute function of an extension unit
operation.
8. Can I access the UniSim Design Optimizer using Automation?
Ans: Unfortunately, the UniSim Design Optimizer is not currently available to Automation. However, there is a
workaround, which uses the SendKeys command. SendKeys is used to send keystrokes to an application as if they
were typed at the keyboard. There are a few caveats:
l UniSim Design must be visible to use the SendKeys command.
l UniSim Design must be the active view to use the SendKeys command, SendKeys does not wait between
keystrokes, so if an application does not respond quickly enough, then SendKeys will fail. To reduce the
possibility of SendKeys failing, a Windows “Sleep” function is used to add a 0.1 second pause between
each keystroke.
l Since there is currently no way to determine when the UniSim Design Optimizer has completed its
calculations, the Windows “Sleep” function is used to wait a specified number of seconds for the UniSim
Design optimizer to solve. After this period of time, a user-defined check can be used to determine if the
optimizer is complete. If not, the “Sleep” for another period of time and check again.

9. How do I determine if an object reference actually points to an object?


Ans: When an object reference is made, the reference may point to an object which does not exist. For example,
when using the UniSim Design Macro Language Editor, the ActiveCase object is an object reference to the currently
open case. If no case is currently open, then the ActiveCase reference points to nothing. Use the Is keyword to
compare the object reference to Nothing. The following code demonstrates this:

Set usdCase = ActiveCase If usdCase Is Nothing Then


MsgBox "No UniSim Design Case Is Open."
End If

10. How does UniSim Design represent empty or null values internally?
Ans: UniSim Design uses the integer -32767 to represent empty or null values. Empty values are shown as
<empty> in UniSim Design. For example, if Automation is used to access the temperature of a process stream on
which a temperature has not been specified, a value of -32767 is returned.
11. How do I use UniSim Design Macro Language (WWB) files?
Ans: In the UniSim Design desktop, select Macro LanguageEditor command from the Tools menu. The UniSim
Design Macro Language Editor view appears. Right-click anywhere on the Macro Language Editor view, and select
File | Open command from the Object Inspect menu. In the Open view, select the UniSim Design Macro Language
(*.WWB) file to open.
12. How do I access column specification values?
Ans: The column unit operation is special in that it has its own flowsheet. The flowsheet is where most information
about the column is stored, so it must be used as the access the column specifications. Access the column flowsheet
as shown below (usdCase is an object reference to the simulation case, and A-100 is the column name):

- 224 -
Chapter 7 - Customization FAQ

Set usdCol = [Link]("A- 100").ColumnFlowsheet

Now directly access the column specifications by name:

[Link]("EtOH OH Mass Frac").GoalValue = 0.001


[Link]("MeOH Btms Mass Frac").GoalValue= 0.001

13. How do I access a SpreadSheet unit operation via Automation?


Ans: Use the following syntax:

Set SS = [Link]("SSName")
A1Value = [Link]("A1").CellValue

Where, usdCase is a reference to the current UniSim Design simulation case, SSName is the name of the
spreadsheet being referenced in UniSim Design, and SS is an object reference to the spreadsheet. The second line
uses the SS object reference to set the value of the variable A1Value equal to the value of cell A1 in the referenced
spreadsheet.
14. Can I access UniSim Design utilities via Automation?
Ans: Currently the UniSim Design utilities cannot be accessed directly through Automation. However, the utilities
(and most other objects in UniSim Design) can be accessed indirectly by the SpeadSheet unit operation. Simply
attach the utility inputs and results to the SpreadSheet and access the SpreadSheet via Automation as shown in
#13.
15. How can I determine if UniSim Design is already running?
Ans: The following code demonstrates how the GetObject function can be used to determine if UniSim Design is
currently running:

Set usdApp = GetObject(, "UniSim [Link]")

If UniSim Design is not running, then the above line generates error number 429 in Office 97 and 483 in Office 95.
Error trapping can be used to catch the error and determine if UniSim Design is running.
For example:

On Error GoTo ErrorTrap


Set usdApp = GetObject(, "[Link]")
'{Code here which will be executed only If UniSim Design
Is running}
Exit Sub
ErrorTrap:
If [Link] = 429 Or [Link] = 483 Then
MsgBox "UniSim Design Is Not currently running,
please start UniSim Design."
Else
MsgBox "The following Error occurred: "
& [Link]
End If

16. How do I make UniSim Design visible when accessing it via Automation?

- 225 -
Chapter 7 - Customization FAQ

Ans: By default, when UniSim Design or a UniSim Design simulation case is opened using Automation, it is a hidden
process, with only the UniSim Design splash screen indicating that UniSim Design is running. The Visible Boolean
property, available in both the Application and SimulationCase objects is used to make UniSim Design visible to the
user.
For example,

[Link] = True

where:
usdCase = an object reference to UniSim Design or
a UniSim Design simulation case.

7.2 Extensibility FAQ


7.2.1 General Extensibility
1. What is the difference between registering the EDF instead of the DLL?
Ans: Registering the EDF allows you to interactively run and debug the extension using Visual Basic. However, a
warning message will appear since no DLL was registered. If you want to interactively run and debug the reaction
extension, use the following sequence:
a. Register the EDF file. This displays a warning message which you can ignore.
b. Click the Run button in Visual Basic. This brings up the debug view.
c. Load UniSim Design and add a reaction.

If everything is working properly, your reaction extension will appear in the list. During this time, you can switch to
Visual Basic and add breakpoints to check variable values, debug, etc. Once you are complete with debugging and
want the reaction extension to be available, use the following sequence:

a. Compile the reaction extension into a DLL.


b. Register the DLL file.
c. Load UniSim Design and add a reaction. If everything is working properly, your reaction extension will
appear in the list.

2. How can I interactively run an extension?


Ans: Use the following procedure:
a. Register the extension definition file (EDF).
b. Load the extension Visual Basic project (VBP) file, select Project command from the View menu and
double-click on the class module (the file will have the *.cls suffix).
c. Right-click on an appropriate line of code and select Toggle command - Breakpoint sub-command from
the Object Inspect menu. The line turns red, indicating a breakpoint at which the execution of the code will
be paused.

d. Click the Start icon on the Visual Basic toolbar. The Debug view appears.
e. Load a UniSim Design simulation case and install the extension by, pressing F12 (to open the UnitOps
view) and double-clicking on name of the extension in the Available Unit Operations list.
f. Select extension attachments and parameters as appropriate to make the extension calculate. When
Visual Basic reaches the breakpoint in the extension, it will move in front of UniSim Design. The code will
be paused at the breakpoint. You can step through the code line-by-line interactively while the extension is
running. Use the F8 key to step through the code line-by-line and F5 to stop stepping through the code
and run the remainder non- interactively. While stepping through the code you can interactively view and

- 226 -
Chapter 7 - Customization FAQ

set values in the Debug view.

TIP
UniSim Design calls the extension three times (one Forgetting pass and two Execute passes).
UniSim Design is inactive while the extension is being stepped through.

For example, typing ?[Link] and pressing ENTER will return the
temperature of the stream named StreamName in UniSim Design internal units (°C).

3. How do I reference streams and variables in the EDF?


Ans: Use the FindVariable method of the Container object. For example, the following code makes an object
reference to the stream object with the Tag name “Feed” in the EDF.

Set usdFeed = [Link]("Feed").[Link]

The following code makes an object reference to the real value object with the tag name “PrdTmp” in the EDF.

Set usdProdTemp = [Link]("PrdTmp").Variable

4. When using FindVariable to set an object reference to an object in the EDF, when do I use .Variable and when do I
use .[Link]?
Ans: .Variable is used to access the value of variables in the EDF, such as numeric entry widgets, radio buttons, and
so forth.
.[Link] is used to reference an object directly so that the extension is able to access the object properties
and methods. Typically, .Variable is only used for EDF variables and .[Link] is only used for process stream
attachments.
5. How do I determine if an object reference actually points to an object?
Ans: When an object reference is made, the reference may point to an object which does not exist. For example,
when FindVariable is used to set an object reference to an object in the EDF. If there is no object (for example, when
a feed stream has not been attached), then the reference points to nothing. Use the Is keyword to compare the
object reference to Nothing. The following code demonstrates this:

Set usdFeed = [Link]("FeedStream").[Link]


If usdFeed Is Nothing Then
Exit Sub

7.2.2 Unit Operation Extensions


1. What is the Container for a unit operation extension?
Ans: The ExtnUnitOperationContainer is the Container object for unit operation extensions. It contains the
properties and methods which are available to them. You can view this object with an object browser (such as is
contained in Visual Basic) or you can read the extension help file ([Link]) which is installed in the
UniSim Design directory when the extension SDK is installed.
2. What is the calculation sequence for an extension?

- 227 -
Chapter 7 - Customization FAQ

Ans: When a change is made to a variable which affects the extension, UniSim Design performs a Forgetting pass
and two Calculation passes. The Forgetting pass is used to identify the streams, unit operations, etc. affected by the
change. The first Calculation pass is used to allow the extension to complete its internal calculations. The second
Calculation pass is made so that external references made by the extension use correct values. If the extension
makes no external references, then the second pass can be bypassed using the SolveComplete method of the
Container object.
3. How do I prevent the second Calculation pass?
Ans: Add the following near or at the end of the Execute code.

[Link]

where:
usdContainer = an object reference to the Container object
made in the Initialize function

This method of the Container object prevents the second Calculation pass from occurring. SolveComplete should
only be used when the extension does not make an external reference to a product stream. If the extension makes
no external references, then it is recommended that this line be included to increase efficiency and prevent other
calculation problems.
4. How do I set default values for numeric input or text boxes?
Ans: Use the following procedure:
Make object references to the numeric input boxes in the Initialize function and then set their defaults using the Value
property. For example,

Set usdContainer = Container


Set usdEff = [Link]("Eff").Variable
If IsRecalling = False Then [Link] = ".50"

The first line sets an object reference to the container calling the extension unit operation. The second line sets
usdEff as an object reference to the eff real number variable in the EDF. The Eff variable is the target moniker of a
numeric input widget. The third line determines if the unit operation is being recalled from a saved case. If not, then
the Value property of usdEff is set to 0.50.
5. How do I create an “Ignore This Unit Operation During Calculations” checkbox?
Ans: Use the following procedure:
a. Add a standard checkbox to the extension view.
b. Double-click on the checkbox or right-click and select Check Box Properties command.

c. Double-click the Target Moniker field or click the Ellipsis icon directly beside it.
d. Select Object is Ignored in Calculations from the Select Number Variable view.
e. Change the text in the Label field to &Ignore Unit Operation.

6. How do I create a Delete button?


Ans: Use the following procedure:
a. Add a standard button to the extension view.
b. Double-click on the button widget or right-click and select Button Properties command from the Object
Inspect menu.
c. Double-click the Message field or click the Ellipsis icon directly beside it.

- 228 -
Chapter 7 - Customization FAQ

d. Click the Insert button.


e. Select Delete Object from the list and click the OK buttons on the Select Message view and Edit
Message view.
f. Change the text in the Label field to &Delete.

7. How do I add Radio Buttons?


Ans: Use the following procedure:

a. Go to the Views Manager view and click the Object Manager icon beside the Selected Objects
drop-down list.
b. In the Variables of Selected Object matrix, type the Tag name in the Tag column, enter the name in the
Name column, and select Real Number in the Type column. For example:

Tag Name Type

List List Real Number

c. Check the Persistent checkbox and the Triggers Solve checkbox, select None in the N Dimensions drop-
down list and select Index in the Numeric Type drop-down list.
d. Close the Object Manager view and open the form by double- clicking on it in the Existing Views list.
e. Add a Radio Buttons widget and open the Radio Button Properties view by double-clicking on the widget.
Double-click the Target Moniker field or click the Ellipsis icon beside it to open the Select Number
Variable view. Select the Real Number tag created in the Objects Manager view and click the OK button.
f. In the matrix at the bottom of the Radio Buttons Properties view, add Labels for the Radio Buttons, the
value sent to the extension when the Radio Button is selected, the X, Y and width of the Radio Button and
its placement (justification).
g. Save the *.edf file.
h. In the extension code, use the value of the enumeration as appropriate:

Code Description

Dimension usdRef as an object


in the declaration section.
Dim usdRef as Object
Use usdRef to set a reference
Set usdRef = [Link]("Ref").Variable
Set usdRef = [Link]("Ref").Variable to the Status object in the
If IsRecalling = False Then extension definition file (EDF).
[Link] = 0
The Initialization function in
the extension code is used to
set the default value for the
Radio Buttons.

IsRecalling is only false when the extension is first added to the simulation, so that is when the default value
of usdRef is set to 0, which corresponds to a Radio Button value.

8. How do I add status text and status colour?


Ans: Use the following procedure:

- 229 -
Chapter 7 - Customization FAQ

a. Go to the Views Manager view and click the Objects Manager icon beside the Selected Objects
drop-down list.
b. In the Variables of Selected Object matrix, type the Tag name in the Tag column, enter the name in the
Name column, and select Real Number in the Type column. For example,

Tag Name Type

Status Status Real Number

Make sure the Persistent checkbox is checked, that None is selected in the N Dimensions drop-down list,
and that Index is selected in the Numeric Type drop-down list.
c. Close the Object Manager view and open the form by double- clicking on it in the Existing Views list.
d. Add Static Text objects of the exact same size in the exact same place on the bottom of the form (this can
be easily accomplished using the Position and Size matrix). Give them appropriate Names (such as OK
and Error), Background Colours (yellow for informative text, green for converging and converged and red
for errors) and Fixed Text (such as OK and Error). Check the Framed checkbox for each. Make sure the
Enable Moniker field is empty.
e. Create a Visibility Controller to view the Static Text objects:
i. Right-click on the form and select Open Visibility Manager command from the Object Inspect
menu.
ii. Click on the Create Controller button and then click the Edit button.
iii. On the Visibility Controller Properties view, enter Status in the Name field.
iv. Double-click the Moniker field or click the Ellipsis icon directly beside it.
v. Select Status from the list (the object variable added earlier), and click the OK button.
vi. Type the Static Text object Labels in the Name column of the States matrix.
vii. Type in the same value for both the Low and High columns.

Name Low High

OK 0.0 0.0

Error 1.0 1.0


viii. This value determines which Static Text object will be displayed.
ix. Click the Select Widgets button. The names of the objects on the form appear in the first
column and the names of the States added to the earlier matrix appear in the first row. For the
Static Text objects added earlier named OK and Error, check the Controlled checkbox in the
second column. For the OK Static Text object, check the checkbox in the column entitled OK. For
the Error Static Text object, check the checkbox in the column entitled Error. For example,

Controlled OK Error

OK X X

Error X X
x. Click the OK buttons to close the Visibility Controller Widget Selections view and the Visibility

- 230 -
Chapter 7 - Customization FAQ

Controller Properties view.


xi. The Visibility Controller for the Status is now shown on the Visibility Manager view. Clicking on
one of the radio buttons displays the appropriate text.
xii. In the extension code to set the value of Status as appropriate:

f. Dimension usdStatus as an object in the declaration section. For example:

Dim usdStatus as Object

g. Use usdStatus to set a reference to the Status object in the extension definition file (EDF). For example:

Set usdStatus = [Link]("Status").Variable

h. Set the value of usdStatus as appropriate to show the appropriate Static Text object. The message which
will be shown based on the value that was determined in step #ix.

9. How do I add a drop-down (enumeration) list?


Ans: Use the following procedure:

a. Go to the Views Manager view and press the Objects Manager icon beside the Selected Objects
drop-down list.
b. In the Variables of Selected Object matrix, type the Tag name in the Tag column, enter the name in the
Name column, and choose Enumeration in the Type column. For example,

Tag Name Type

List List Enumeration

c. Check the Persistent checkbox and select the dimension in the N Dimensions drop-down list (none is for a
single selection, vector is for an array of selections).
d. Click the Enumeration Values button and type in the label (the text that will appear in the drop-down list)
and the value (the value which will be used in the unit operation extension when an enumeration is chosen
from the list).
e. Close the Object Manager view and open the form by double- clicking on it in the Existing Views list.
f. Add an Enumeration widget. Double-click on the Target Moniker field or click the Ellipsis icon beside it
and select the enumeration tag created in the Objects Manager. The number of entries in the drop-down
list, the order in which they appear, and how they are matched can also be set here.
g. Save the *.edf file.
h. In the extension code, use the value of the enumeration as appropriate:

Code Description

Dimension usdList as an
object in the declaration
Dim usdList as Object section.
Set usdList = [Link]("List").Variable
Use usdList to set a
reference to the Status object
in the extension definition file
(EDF).

- 231 -
Chapter 7 - Customization FAQ

10. How do I force the simulation to solve?


Ans: Add a new sub-procedure named VariableChanged to the unit operation extension class module. This
procedure is called whenever a variable in the extension is changed. An InternalVariableWrapper object is passed to
it as an argument. This object is used to identify the name of the variable and take an appropriate action, such as
triggering a solve. For example,

Public Sub VariableChanged(ByVal VariableName As


InternalVariableWrapper)
If [Link] = "Name" Then
[Link]
End Sub

If the Tag property of the VarableName object is equal to NAME then the usdContainer object uses the TriggerSolve
method to triggers a solve. NAME is the name of the enumeration widget (or any other widget) in the EDF file.
usdContainer is an object referenced to the Container object which is made in the Function Initialize section of the
class module. For example,

Public Function Initialize(ByVal Container As Object,


ByVal IsRecalling As Boolean) As Long
Initialize = extnCurrentVersion
Set usdContainer = Container
End Function

11. How do I add a single-column Matrix which lists one type of information (for example, Component names)?
Ans: Use the following procedure:
a. Open the UniSim Design extension view editor with the extension definition file (EDF) to be modified.
b. Go to the Views Manager view and click the Objects Manager icon beside the Selected Objects
drop-down list.
c. In the Variables of Selected Object matrix, enter the following in the Tag, Name and Type columns.

Type Triggers N Numeric


Tag Name
Persistent Solve Dimensions Type

ComponentNames ComponentNames Text Unchecked Vector N/A


Checked

MatrixData MatrixData Real Checked Matrix Index


Checked
ComponentNames is the Text object used to put the component names in the matrix column row and
column header. MatrixData is the Real Number object used to hold the matrix data.

Tag Name which is used to access the object from Visual Basic.

Name Alternate name used in the extension view editor (used to be more descriptive).

Type The object type.

Persistent Stores object values with the UniSim Design simulation case.

Triggers Will a change in the object force a solve.


Solve

- 232 -
Chapter 7 - Customization FAQ

Numeric The type of real number. Index is used for unitless numbers. This only applies to objects
Type of the Real Number type.
d. Close the Object Manager view and open the extension view by double-clicking on it in the Existing
Views list.
e. Add a Matrix widget by right-dragging from the Widgets Palette. View the Matrix properties by double-
clicking on it.
i. Vertical Direction and Sticky Last Entry should be unchecked. Multi-Selectable should be
checked.
ii. In the Labels group, the first drop-down list should be Column, the Show Units drop-down list
should be None and the Left Width field should be 0.
iii. In the Cells group, the Width field should be 50, the Height field should be 9, the Wrap field
should be empty, the Grids drop-down list should be Both and the Enter Motion drop-down list
should be None (this determines how the selected cell moves on the matrix when the user
presses ENTER).
iv. The Target Widget drop-down list should be set to <Self>.

f. Double-click on MatrixDataSet1 in the Data Sets list or select MatrixDataSet1 and click the Edit button.
i. Double-click on the Moniker field or press the Ellipsis icon and select ComponentNames
from the Select Number Variable view.
ii. In the Label group, select the Fixed radio button and type ComponentNames in the field below
the radio buttons.
iii. Check the View Only checkbox (this prevent the user from changing the values).
iv. Click the OK button to close the Data Set Properties view.

g. Click the OK button to close the Matrix Properties view.


h. Ensure that the Matrix widget is wide enough to accommodate a scroll bar on the right side if required.
Typically, one-quarter of a column should be adequate.
i. Save the *.edf file.
Next add the following extension code:
j. Add the following to the global declarations section:

Dim usdComponentNames As InternalTextFlexVariable


Dim ComponentNames As Object

k. Add the following to the Execute function:

' Reference the variables


ComponentNames variable In the EDF
Set usdComponentNames =
[Link]("ComponentNames").Variable
' Make an Object reference To the
ComponentNames collection Object
Set ComponentNames =
[Link]
' Set the size of the usdComponentNames
vector using the SetBounds method
[Link] [Link], 0, 0
' Set the values of usdComponentNames
equal To the ComponentNames() vector

- 233 -
Chapter 7 - Customization FAQ

[Link] = [Link]

12. How do I add a Component Matrix (a matrix with Component names along the row and column headers in to the
body of which numbers can be entered)?
Ans: Use the following procedure:
a. Open the UniSim Design extension view editor with the extension definition file (EDF) to be
modified.
b. Go to the Views Manager view and press the Object Manager icon beside the Selected
Objects drop-down list.
c. In the Variables of Selected Object matrix, enter the following in the Tag, Name and Type
columns.

N
Triggers Numeri
Tag Name Type Persistent Dimensio
Solve c Type
ns

ComponentNam ComponentNam ComponentNam Unchecke Vector N/A


es es es d

MatrixData MatrixData Real Checked Checked Matrix Index


ComponentNames is the Text object used to put the component names in the matrix row and
column header. MatrixData is the Real Number object used to hold the matrix data.

Tag Name which is used to access the object from Visual Basic.

Name Alternate name used in the extension view editor (used to be more
descriptive).

Type The object type.

Persistent Stores object values with the UniSim Design simulation case.

Triggers Will a change in the object force a solve.


Solve

Numeric The type of real number. Index is used for unitless numbers. This only applies
Type to objects of the Real Number type.
d. Close the Object Manager view and open the extension view by double-clicking on it in the
Existing Views list.
e. Add a Matrix widget by right-dragging from the Widgets list. View the Matrix properties by double-
clicking on it.
i. Vertical Direction and Sticky Last Entry should be unchecked. Multi- Selectable should
be checked.
ii. In the Labels group, the first drop-down list should be Both, the Show Units drop-down
list should be None and the Left Width field should be 45 (a good width for typical
component names). Double- click on the Moniker field or click the Ellipsis icon
and select Component Names from the Select Text Variable view.

- 234 -
Chapter 7 - Customization FAQ

iii. In the Cells group, the Width field should be 40, the Height field should be 9, the Wrap
field should be empty, the Grids drop-down list should be Both and the Enter Motion
drop-down list should be None (this determines how the selected cell moves on the
matrix when the user presses ENTER).
iv. The Target Widget drop-down list should be set to <Self>.

f. Double-click on MatrixDataSet1 in the Data Sets list or select MatrixDataSet1 and click the
Edit button.
i. Double-click on the Moniker field or click the Ellipsis icon . Select MatrixData from
the Select Number Variable view and click the OK button.
ii. In the Label group, select the Moniker radio button and double- click in the field or click
the Ellipsis icon. Select ComponentNames from the Select Text Variable view and
click the OK button.
iii. Select the number format desired by double-clicking the Format field or clicking the
Ellipsis icon. Typically 0.5 fixed is best for interaction parameters.
iv. Enter the text used when a cell is empty in the matrix in the Empty Text field.
<empty> is the UniSim Design standard.
v. Enter the text used when a cell is uneditable in the Matrix in the Hidden Text field. ---
is the UniSim Design standard, though the default value listed is ***.
vi. In the Units group, the Auto radio button should be selected, Shows Units in Cell
should be unchecked and Hide Units in Label should be unchecked.
vii. Click the OK button to close the Data Set Properties view.

g. Click the OK button to close the Matrix Properties view.


h. Save the *.edf file.
Next add the following extension code:
i. Add the following to the global declarations section:

Dim ComponentNames As InternalTextFlexVariable


Dim MatrixData As InternalRealFlexVariable
Dim DummyMatrix As Variant

j. Add the following to the Initialization function:

If IsRecalling = False Then


Set usdComponents = usdContainer.
[Link]
[Link] [Link], 0, 0
[Link] = [Link]
DummyMatrix = [Link]
ReDim DummyMatrix([Link], [Link])
' This Is used To Set default values For the matrix.
' Note that the diagonal Is Set To -32768, which makes it uneditable
For i = 0 To [Link] - 1
For j = 0 To [Link] - 1
If i = j Then
DummyMatrix(i, j) = -32768
Else
DummyMatrix(i, j) = 0
End If
Next j

- 235 -
Chapter 7 - Customization FAQ

Next i
[Link] [Link],
[Link], 0
[Link] = DummyMatrix
End If

k. Add the following to the Execute function:

DummyMatrix = [Link]
For i = 0 To [Link] - 1
For j = 0 To [Link] - 1
if i = j Then DummyMatrix(i, j) = -32768
Next j
Next i
[Link] = DummyMatrix

13. How do I change the name of an unit operation extension in the PFD?
Ans: A Text Entry widget must be added to the EDF file to allow the name of the extension to be changed. Use the
following procedure:
a. Add a Static Text widget and double-click it or right-click and select Static Text Properties command
from the Object Inspect menu.
b. Change Fixed Text to &Name. The & is used to determine the hot key for the view. (ALT + hot key gives
the focus to this widget). The hot key is shown as underlined.
c. Add a Text Entry widget and double-click it or right-click and select Text Entry Properties command
from the Object Inspect menu.
d. Double-click the Target Moniker field or click the Ellipsis icon directly beside it, select Object Name
from the Select Text Variable list and click the OK button.

14. How do I set the compositions of a stream in UniSim Design?


Ans: Compositions must be set using a Variant array which has been initialized. To initialize the array, set it equal to
the ComponentMolarFractionValue, ComponentMassFractionValue, or ComponentVolumeFractionValue of the
stream whose compositions are going to be changed.
The following code demonstrates this:

Dim Compositions As Variant


Compositions = [Link]
Compositions(0) = .5
Compositions(1) = .2
Compositions(2) = .3
[Link] = Compositions
'where:
'usdFeed = an object reference to a material stream in UniSim Design

15. How do I display results in the EDF?


Ans: Use the following procedure:

- 236 -
Chapter 7 - Customization FAQ

a. Open the UniSim Design extension view editor with the extension definition file (EDF) to be modified.
b. Go to the Views Manager view and press the Object Manager icon beside the Selected Objects
drop-down list.
c. In the Variables of Selected Object matrix, enter the Tag, Name and Type of the variables which are to be
displayed. Ensure that the Persistent checkbox is checked, the Triggers Solve checkbox is unchecked,
N Dimensions is None, and the selected Numeric Type as appropriate.
d. Add Static Text widgets to the EDF to describe the output data. Add Numeric Input widgets beside the
appropriate description. Double-click the Numeric Input widget or right-click and select Numeric Input
Properties command from the Object Inspect menu.
e. Check the View Only checkbox. Select the appropriate variable in the Target Moniker field.
f. Add the following code to the extension:

NOTE

[Link]("EDFVariable").Variable =
ExtnVariable
or
[Link]("EDFVariable").[Link]
Value ExtnVariable, [Required Units]

Depending on whether the value being set has particular units, where EDFVariable is the name of
the variable in the EDF and ExtnVariable is the name of the variable in the extension code whose
value is going to be displayed in the EDF.

16. How do I make a button perform a calculation when clicked?


Ans: Use the following procedure:
a. Open the UniSim Design extension view editor with the extension definition file (EDF) to be modified.
b. Go to the Views Manager view and click the Object Manager icon beside the Selected Objects drop-
down list.
c. In the Variables of Selected Object matrix, enter the following:

Tag Name Type

ActionButton Action Button Message

The Triggers Solve checkbox should be checked or unchecked as appropriate if the calculations affect the
extension.
d. Add a Button widget to the EDF. Double-click the Button widget or right-click and select Button
Properties command from the Object Inspect menu.
e. Change the Label to &About.
f. Double-click on Message field or click on the Ellipsis icon beside it. Click the Insert button, and
select AboutButton from the Select Message list.
g. Click the OK buttons to close the Select Message view, Edit Message view, and Button Properties view.

- 237 -
Chapter 7 - Customization FAQ

h. Add the following Public Sub to the unit operation extension code:

Public Sub VariableChanged(ByVal VariableName As


InternalVariableWrapper)
On Error GoTo ErrorCatch
If [Link] = "AboutButton" Then
{Enter you code here}
End If ErrorCatch:
End Sub

When a variable is changed in the EDF, Sub VariableChanged is executed if it is present. The Code above
checks the Tag of the variable which was changed, if the tag of the variable is AboutButton, then the code
in the braces is executed. Custom calculation code is entered between the braces.

17. How do I automatically set the Calc Level (calculation level) of an extension?
Ans: Add the following to the Initialize function of the extension code:

Set usdContainer = Container


[Link] = 1000

18. How do I automatically attach an existing stream to a Unit Operation Extension when it is added to the PFD?
Ans: In the Initialize function of the extension, make an object reference to the stream which will be attached to the
extension. Then use FindVariable to set the name of the stream defined in the EDF equal to the stream object
reference.
The following code demonstrates this:

Dim usdFeed As Object


Set usdFeed = [Link]("Feed")
[Link]("Feed").[Link] = usdFeed

19. What is a “Forget” Pass?


Ans: UniSim Design unit operations can calculate “product” variables based on “feed” variables, “feed” variables
based on “product” variables, or a combination of the two. This can lead to very complicated interdependency
between the variables in a flowsheet. When a variable is changed, UniSim Design must first “forget” all of the
variables that were calculated based on the original value, and then re-calculate based on the new value. If the
values are not forgotten, an attempt to calculate a new value is misinterpreted by UniSim Design as an
inconsistency.
To illustrate this, assume that the temperature of the inlet stream to a unit operation is changed from 10°C to 41°C.
The following sequence occurs:
a. The stream will “forget” its temperature, as well as any variables it calculated based on temperature (e.g.,
vapour fraction, density).
b. The unit operation will get an Execute pass, with IsForgetting = True. If the unit operation asks its inlet
stream for any of the forgotten variables it will receive <empty> (which can be an E_FAIL error, or the
value -32767).
c. The unit operation is unable to calculate any of the variables it had calculated based on the inlet stream’s
forgotten variables. UniSim Design causes these variables to be forgotten as well. Their owners (e.g., the
unit operations’s outlet stream) will then receive a similar Execute.
d. When the Forget pass has propagated through the flowsheet, the inlet stream recalculates using the new
temperature value. An Execute pass - with IsForgetting = False - will propagate through the flowsheet.

- 238 -
Chapter 7 - Customization FAQ

20. What should my Execute do during a Forget?


Ans: Given the above description of the purpose of the Forget pass, it would seem to make sense for a unit
operation’s Execute to return immediately if IsForgetting = True. All of the variables it had calculated would be
‘forgotten’ by UniSim Design, but recalculated during the subsequent Execute. If a unit operation’s Execute performs
no calculations during the Forget pass, this is exactly what will happen. Indeed, this is a valid method for a unit
operation. Neglecting to perform any calculations during a forget will not cause any errors, but can cause some
inefficiency because more variables than necessary are forgotten.
If efficiency becomes a concern, a solution may be to calculate some variables during the Forget. Non-extension unit
operations generally calculate as much as possible during their Forget, so as to minimize unnecessary propagation
of the Forget. As an example, consider a Cooler operation that has the following specification:
l Inlet Pressure
l Inlet Temperature
l Pressure Drop
l Outlet Temperature

The Cooler calculates its Duty and Outlet Pressure based on these values. If the inlet temperature is changed, the
Cooler will get a Forget, in which the inlet temperature appears <empty>, but the inlet pressure is available. If the
Cooler does not calculate anything, the outlet Pressure will be forgotten, and the Forget will propagate through all
objects downstream of the Cooler. If, however, the Cooler re-calculates its outlet pressure during the Forget, the
outlet stream will remain fully calculated, and will not receive any Execute calls. Only the Cooler’s duty will be
forgotten.
It is important for any unit operation to avoid using variables that it has previously calculated for the calculation of
other variables. In the above example, the Cooler can “see” its outlet temperature and its duty (which it had
calculated) during its Forget. These two values can (erroneously) be used to calculate its inlet temperature. In this
case, this would cause an inconsistency error, as the calculated value would not match the new specified value.
Often, the problem is subtler, and results in the two values being calculated, each thinking that the other is a
specification. To avoid this, the Cooler must check that it is not a variable’s “CalcBy” object, before using that
variable’s value to calculate other variables.
21. Why do I get Three Execute calls?
First-time extension writers are almost always surprised to receive a second non-Forgetting Execute call from
UniSim Design. In fact, non-Extension unit operations only receive two Execute passes. An additional Execute is
necessary for some extensions that need to see the results of the Balance calls they make during their Execute.
When a unit operation calculates a value to a stream’s variable, the unit operation cannot then “see” the value until
the stream has recalculated. If the unit operation calculates a stream’s temperature during its Execute, and needs to
use the stream’s temperature later in the Execute, it will not be able to ask the stream for the value. When the unit
operation’s Execute knows the value (as in this case), it can simply keep the value itself as long as it needs to.
A problem arises when the unit operation uses a “Balance” call to calculate the compositions and flow of its streams.
The “Balance” performs all the logic to detect which values are specified and which need to be calculated, combines
multiple feeds to produce a single product, etc., all without the unit operation needing to be aware of the calculations.
Unfortunately, the results of these calculations will be unavailable to the unit operation until after the streams have
had their Executes. If the unit operation wants to display, e.g., the flow of a key component in each of its attached
streams, these values will be unavailable. However, the unit operation will receive a third Execute, after the streams
have had theirs, during which the values “Balance” had calculated will be available. Proper use of the third Execute
for this purpose is tricky, as the unit operation must avoid repeating the work of the previous Execute.
Relatively few unit operations require the third Execute call. If a unit operation can perform all of its calculations in the
first Execute, it should call “SolveComplete”, which will prevent the third Execute call from being made by UniSim
Design.
22. Why is my Unit Operation’s PFD icon yellow?

- 239 -
Chapter 7 - Customization FAQ

Ans: UniSim Design will outline a unit operation in yellow if it cannot complete its calculations. Usually, the unit
operation uses its StatusQuery method to provide the user with a specific reason why the solve can not be
completed, but the “Not Solved” warning is provided by default.
To prevent this warning from being added, the unit operation must call “SolveComplete” when it has satisfactorily
completed its calculations. This unit operation’s Execute is responsible for determining whether it has calculated all
of the variables it wants to calculate.

7.2.3 Kinetic Reaction Extensions


1. What is the Container for a Kinetic Reaction Extension?
Ans: The ExtnKineticReactionContainer is the Container object for Kinetic Reaction Extensions. It contains the
properties and methods which are available to them. You can view this object with an object browser (such as is
contained in Visual Basic) or you can read the extension help file ([Link]) which is installed in the
UniSim Design directory when the extension SDK is installed.
2. Why is the Triggers Solve checkbox greyed out in the Objects Manager in the EDF?
Ans: For Kinetic Reaction Extensions, the Triggers Solve box must always checked, which is why it is disabled
(greyed out).
3. How do I access the liquid phase if my reaction only occurs in the vapour phase? If I select combined phase, then my
reaction rate changes.
Ans: UniSim Design multiplies the reaction rate, which you pass to it, by the volume of the phase selected. This is
wherein the problem lies as UniSim Design should actually only use the volume of the Liquid Phase instead of the
volume of the Combined Phase. Here is the workaround:

Code Description

Set the Phase property to


[Link] = ptCombinedPhase ptCombinedPhase.
Temp = [Link]
rate = rate * (1 - [Link]) Access the Liquid phase for your rate
calculations (make sure to identify it as
HeavyLiquidPhase or LightLiquidPhase).

Multiply the rate you calculate by (1 -


[Link])

The corrected rate will now be used by UniSim Design.

- 240 -
NOTICES

Trademarks
l Experion®, PlantScape®, SafeBrowse®, TotalPlant®, and TDC 3000® are registered trademarks of Honeywell
International, Inc.

l ControlEdge™ is a trademark of Honeywell International, Inc.

l OneWireless™ is a trademark of Honeywell International, Inc.

l Matrikon® and MatrikonOPC™ are trademarks of Matrikon International. Matrikon International is a business unit of
Honeywell International, Inc.

l Movilizer® is a registered trademark of Movilizer GmbH. Movilizer GmbH is a business unit of Honeywell International,
Inc.

l Experion®, PlantScape®, and SafeBrowse® are registered trademarks of Honeywell International, Inc.

l Experion® and SafeBrowse® are registered trademarks of Honeywell International, Inc.

l PlantCruise™ is a trademark of Honeywell International, Inc.

l Experion® is a registered trademark of Honeywell International, Inc.

l ControlEdge™ is a trademark of Honeywell International, Inc.

l OneWireless™ is a trademark of Honeywell International, Inc.

Other trademarks
Microsoft and SQL Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or
other countries.

Trademarks that appear in this document are used only to the benefit of the trademark owner, with no intention of trademark
infringement.

Third-party licenses
This product may contain or be derived from materials, including software, of third parties. The third party materials may be
subject to licenses, notices, restrictions and obligations imposed by the licensor. The licenses, notices, restrictions and
obligations, if any, may be found in the materials accompanying the product, in the documents or files accompanying such third
party materials, in a file named third_party_licenses on the media containing the product, or at
[Link]

- 241 -
Documentation feedback
You can find the most up-to-date documents on the Honeywell Process Solutions support website at:
[Link]

If you have comments about Honeywell Process Solutions documentation, send your feedback to: hpsdocs@[Link]

Use this email address to provide feedback, or to report errors and omissions in the documentation. For immediate help with a
technical problem, contact your local Honeywell Process Solutions Customer Contact Center (CCC) or Honeywell Technical
Assistance Center (TAC).

How to report a security vulnerability


For the purpose of submission, a security vulnerability is defined as a software defect or weakness that can be exploited to
reduce the operational or security capabilities of the software.

Honeywell investigates all reports of security vulnerabilities affecting Honeywell products and services.

To report a potential security vulnerability against any Honeywell product, please follow the instructions at:

[Link]

Support
For support, contact your local Honeywell Process Solutions Customer Contact Center (CCC). To find your local CCC visit the
website, [Link]

Training classes
Honeywell holds technical training classes that are taught by process control systems experts. For more information about these
classes, contact your Honeywell representative, or see [Link]

- 242 -

You might also like