Copyright: Copyright © 1993-1996 Powersim Corp.


Powersim Help

  Introduction to Constructor 2.5

  User Guide

  Constructor Quick Tours

  Sample Models

  Reference Information

  How to use Constructor Help

  What's new?


How to use Powersim Help

Various

Hit F1 to get context sensitive help while you are using Powersim Constructor 2.5.

Hit Escape to close the Help system, and its secondary windows.

The help file structure

You will find the following symbolic conventions throughout this guide.

Symbol	Used for
	The link leads to a new level. There might be information in addition to links on this page.
	As above, but the next level is shown indented below.
	The lowest level, text will be shown in the right hand window.
Typographical Conventions

You will find the following typographical conventions throughout this guide.

Type style	Used for	Examples
ALL CAPITALS	Names of functions, fields and DDE commands	PULSE, TIME
Italics Initial Capitals	Variable names	Population AverageLifetime
Font Color Red	Click at hotspot text to open another application, normally Powersim with a sample model	WAVEFUN.SIM
Printing a help topic

To print a help topic from the main window

•	Click the Print button in the toolbar, or

•	Choose File Print Topic.

To print a help topic from a secondary window (Windows 95 only)

1	Click the right mouse button in the secondary window that you want to print.

2	Select Print Topic in the right-button menu that appears (see below).


Printing a help topic

To print a help topic from the main window

•	Click the Print button in the toolbar, or

•	Choose File Print Topic.

To print a help topic from a secondary window (Windows 95 only)

1	Click the right mouse button in the secondary window that you want to print.

2	Select Print Topic in the right-button menu that appears (see below).


Reference Information

The following topics give you reference information about Powersim objects, menu commands, options, functions, etc.:

  Introduction to the reference guide

  About Powersim Constructor 2.5 - System requirements, acknowledgments, Support Services, etc.

  Objects - Describes each object type found in Powersim, their utility and definition

  Menu Commands - Describes all menu commands found in Powersim

  Options - Describes all user options found in the Options dialog box of Powersim

  Functions - An overview and an alphabetical reference, with complete descriptions, of all Powersim functions

  Modeling Language - Formal definition of Powersim's simulation language

  Simulation - Describes the simulation algorithms applied by Powersim and how to utilize some of the powerful simulation capabilities

  Connectivity- Describes how Powersim can be connected to other applications

  Error Messages - Explains error messages that can occur in Powersim

  Terminology - Glossary of Powersim terms and definitions


Introduction to the reference guide

The reference guide is a complete source of information for any question you may have about Powersim functionality. It explains every feature of Powersim, including all the objects, tools, menus, functions and so on. It does not show you how to build models or explain the steps in using Powersims functionality. You will not read it as you could read the other manuals accompanying the software; its purpose is to be your dictionary, explaining everything about Powersim and what you can accomplish with it.

Objects explains everything about all the different types of objects in Powersim. You will be using at least some of these objects from the moment you start using the software. As you become more adept at using Powersim, you will be able to use more and more of this guide.

In each part, there is a logical sequence to the organization. In places where the topics themselves do not actually build on each other, alphabetical ordering is used.

Unless you are already familiar with systems modeling and Powersim, you probably will not find this guide to be an interesting point of departure. In fact, it is not meant to be used first for the average Powersim user. But while modeling, you may need to find more information on a particular feature, and that is where this guide comes into play. It is intended to be a comprehensive account of everything about Powersim. Features are explained but not elaborated on, because this guide assumes a certain level of knowledge that came from the use of the other documenttion materials included in the package.

Using this guide means you are more on your own with your model, however, you are never really alone. If the answers to your questions are not found here, and you have checked the other sources as well, you are always welcome to call the Powersim support lines and ask for further assistance.


POWERSIM.INI - Search Order

When setting up Powersim, it can be of interest to know in which order Powersim searches for the POWERSIM.INI file. Powersim uses this search order:

1	The current directory

2	The Windows directory (e.g. C:\WINDOWS)

3	The Windows system directory (e.g. C:\WINDOWS\SYSTEM)

4	The directory where Powersim was installed (if you run Powersim for the first time) or where POWERSIM.INI was last found

5	The directory containing the Powersim executable (POWERSIM.EXE)

See also

POWERSIM.INI - List of Sections


POWERSIM.INI - List of Sections

The various sections of POWERSIM.INI contain information about components and preferences in your  Powersim system. Some of the sections are automatically updated by Powersim based on the choice of user options etc., while other sections must be edited directly by the user. The following sections can be found in POWERSIM.INI:

CustomColors

Lists the RGB values of the sixteen user defined colors that can be set when defining external objects.

DiagramEditorOptions

Lists user options which apply to the diagram editor of Powersim, such as grid settings etc.

FunctionDLLs

This section contains and entry of the form ListOfDLLs=name,name,... which lists available DLLs containing functions.

Filename (*.DLL)	Description
PSXFPRO	Powersim External Functions: Functions that are part of the professional Powersim package.
PSXOPRO	Functions that are defined together with the professional external objects, for example, the network game object.
The library PSXFSTD.DLL, that contains standard external functions, is assumed to reside in the same directory as POWERSIM.EXE. The entry StandardDLL=name can be used to refer to an alternative location for PSXFSTD.

NumFmt

Lists user defined number formats that can set when defining external objects.

ObjectDLLs

This section contains one entry of the form ListOfDLLs=name,name,… which lists available DLLs containing object types. The table below lists DLLs that may be found here:

Filename (*.DLL)	Description
PSXOSTD	Powersim External Objects: Standard Dynamic Objects , i.e., dynamic objects that are part of the standard Powersim package.
PSXOPRO	Powersim External Objects: Professional Dynamic Objects , i.e., dynamic objects that are part of the professional Powersim package.
Note	The following DLLs became obsolete with Powersim version 2.5: PSXOBTN.DLL, PSXODDEA.DLL, PSXONET.DLL and PSXOSTC.DLL, and should not be listed in the ObjectDLLs section of POWERSIM.INI.

PowersimOptions

Lists user options which apply to the entire Powersim application, such as the visibility of commandbar and statusbar etc.

RecentFileList

Lists the N documents most recently opened. The number of documents listed (N) is 4 by default. This number may be altered by changing MaxRecentFiles to a number from 1 to 9, inclusive

SimulationEngine

Lists simulation parameters. See also: Adjusting Calculation Time of RK4 Variable Step Size

ToolbarsMRUSequences

Settings for restoring the toolbars between Powersim sessions.

See also

POWERSIM.INI - Search Order


Building and Simulating Models

  Flow Diagram Modeling

  Symbols and Building Blocks

  Working with Levels

  Working with Flows

  Working with Auxiliaries

  Working with Constants

  Working with Links

  Working with the Define Variable Dialog box

  Simulating

  Preparing a Simulation Run

  Running Simulations

  Initializing variables when a simulation starts


Introduction
Introduction on how to use Powersim Constructor

The purpose of the Powersim language is to make a description, or model, of an imaginary or real system. When running the model, the resulting behavior may be used to make assumptions about the behavior of the described system. A model consists of a set of interrelated components, called variables. Construction of a model is done by defining variables and the relationships between variables.

Powersim provides a diagram editor for defining simulation models. Variables are represented as graphical objects, which may be connected using links and flows. Each link represents a relationship between the variables connected by the link. The exact definition of the relationship is defined as an equation in the Powersim language. Powersim allows model structure and model behavior to be observed in the same diagram. Model objects convey the structure of the model. Dynamic objects may be placed anywhere in the diagram to display model behavior when simulating.


Flow Diagram Modeling

  Symbols and Building Blocks

  Working with Levels

  Working with Flows

  Working with Auxiliaries

  Working with Constants

  Working with Links

  Using Information links

  Using Delayed links

  Using Initialization links

  Working with the Define Variable Dialog box

  Variable

  Unit of Measure

  Defining Units

  Dimensions

  Definition

  Changing a Level's Flow Definition

  Documentation

  Linked Variables

  Functions

  Buttons


Symbols and Building Blocks

In this section we will cover the types of building blocks that are used in constructing Powersim models. Basically, there are five types: levels (stocks), flows, auxiliaries, constants, and links. In addition, auxiliaries can be paired with flows to create flows-with-rates, and links can be categorized as information links, delayed links, and initialization links. The figures below give an overview of the icons used to symbolize each of the building blocks.

Level: A variable type which accumulates changes. Influenced by flows

Auxiliary: A variable type which contains calculations based on other variables.

Constant: A variable type which contains fixed values that are used in calculations of auxiliary variables or flows.

Flow: Influences levels.

Flow-with-rate: Influences levels. The flow is controlled by the connected rate variable, normally an auxiliary variable

Information link: Gives information to auxiliary variables about the value of other variables.

Delayed info-link: Used only when the auxiliary variable contains special delay functions.

Initialization link: Gives start-up information to level variables about the value of other variables.

Cloud: Undefined source or outlet for a flow to, or from a Level. Denotes that we are at one of the model's outer limits.

The five types and their subdivisions will be documented in the following pages, including step-by-step instructions on how to use them.

See also

Undefined variables

Erroneous flow

Edited flow

Snapshot variables

Array variables


Undefined variables

A variable symbol with a question mark (?) in it means that the variable is not defined or that it has an error in its definition. (Question marks in undefined variables may be switched off using the Diagram View category of the Options dialog box.)


Erroneous flow

A flow with a question mark (?) on it, denotes that the flow is not correctly defined.


Edited flow

A flow with an exclamation mark (!) on it, denotes a flow where the flow has been manually edited by the user (for example, constrained).

See also

Advanced Use of Arrays


Snapshot variables

A variable symbol with an extra set of corners is called a snapshot. It is a picture of or an alias for an "original" variable. Snapshots are useful for linking variables located in different parts of a model. You create a snapshot by using the camera tool.


Array variables

A double frame is used for variables that are arrays.


Working with Levels

Levels in a Powersim model represent accumulations in the system that is being modeled. They can represent physical accumulations, such as inventory and backlogs, as well as intangible accumulations, such as love or hate.

Level symbol

Levels must be given an initial value, which can be a number or the value of another variable, such as a constant or auxiliary. Powersim simulates levels by adding inflows to the initial values and subtracting outflows from them. These computations are made at every time step in the model, so that the value of the level at any point in time equals the value from the previous time step plus any inflows and minus any outflows in the current time step.

See also

Creating Levels in a Model


Creating Levels in a Model

There are two issues in creating a level variable in a model: placing it on the screen and defining it with an initial value.

To place a level on the screen

1	Select the level icon in the toolbar [image] with the left mouse button.

2	Move the cursor from the toolbar to the screen. Notice that the cursor now looks like a level.

3	Position the cursor wherever you would like to place the level and click again on the left mouse button to deposit it there.

4	Give the level a name by typing over the default name "Level_1", for example "Inventory".

To define a level using a numerical value

1	Double-click on the level using the left mouse button. The window that appears is the Define Variable dialog box.

2	Type a definition into the Definition text box. It could be a numerical value or an expression that uses one or more linked variables. We will use "400".

3	Type a unit into the Unit of Measure drop-down box. We will use "Widgets".

4	Type a documentation into the Documentation box. We will use " The number of widgets found in the inventory."

5	Click the OK button to return to the workspace.

To define a level using another variable for initialization

To demonstrate the use of an outside variable to initialize a level, a constant must be added to the screen.

1	Select the constant icon in the toolbar [image] with the left mouse button.

2	Move the cursor from the toolbar to the screen. Notice that the cursor now looks like a constant.

3	Position the cursor wherever you would like to place the constant (it should be close to the level) and click again on the left mouse button to deposit it there.

4	Name the constant "Initial_Inventory" by typing over the default name "Constant_1."

To connect a constant to a level

Connecting the constant to the level involves the use of the information link.

1	Select the information link icon in the toolbar [image] with the left mouse button.

2	Move the cursor from the toolbar to the screen. Notice that the cursor now looks like a link.

3	Place the cursor on the constant, click and hold the left mouse button, and drag the cursor into the level until the level turns black.

4	Release the mouse button to complete the link. Notice that the link is a broken line, signifying an initialization link.

5	Double-click on the level to open the Define Variable dialog box.

6	Double-click on "Initial_ Inventory" in the Linked Variables list. This action replaces the original numerical value with the variable Initial_Inventory:

7	Close the dialog box by clicking the OK button.

Now the level is defined with the constant. To change the value of the level, simply change the value in the constant instead. Levels do not have to be initialized only with numbers or constants; other levels and auxiliaries can also be used.


Working with Flows

Flows in a Powersim model represent the transport of quantities to, from, and between levels.

Flow symbol

While levels are the "state" of the system being modeled, flows are the "action." Flows are the only variables that can change levels, by either adding to them or subtracting from them. Control of the magnitude of the flow is achieved through a rate, which is a variable of any type that is linked to the flow "valve." The most common rate is the auxiliary variable.

Flow with auxiliary rate

Powersim provides both a flow icon [image] and a flow-with-rate icon [image] in the toolbar. The flow-with-rate icon is a flow with an auxiliary attached to it by an information link. The auxiliary is located so close to the flow, however, that the link is not visible, giving the impression of one element. The rate can be separated from the flow by simply dragging it away from the flow valve.

Flow with separated auxiliary rate

See also

Creating Flows in a Model

Splitting and Connecting Flow and Level


Creating Flows in a Model

Flows can add to a level, subtract from a level, and subtract from one level and add to another simultaneously. If the flow is not attached to levels at both ends, a cloud-like symbol appears on the unattached end. This cloud-like symbol is called a source for inflows and a sink for outflows. A source means that the quantity in the flow is coming from somewhere that is not specified in the model. A sink means the opposite, that the quantity in the flow is going somewhere that is not specified in the model.

To place a flow on the screen

1	Click on the flow icon in the toolbar [image] .

2	Move the cursor into the workspace of the screen. The cursor will change into a small flow icon.

3	Position the cursor where you want to place the flow and press the left mouse button.

4	With the button still pressed, move the mouse pointer a little to the left or to right and then release the button. The flow will appear between two cloud symbols on the screen.

Flow without an auxiliary rate

Because flows add to or subtract from levels, it makes more sense to have a flow that is going into a level or one that is coming out of a level. We also need an auxiliary connected to the flow in order to define the magnitude of the flow, so we should choose a flow-with-rate rather than a plain flow. The flow that we just created will not have any effect on the model, so we will delete it from our diagram.

To delete one or more model objects from a diagram

1	Select the objects you want to delete by dragging a frame around them using the left mouse button. A flow object is selected when the small handles on both sides of the flow arrow are visible.

2	Press the Delete button or choose Edit Clear.

To create a flow into or out of a level

1	Click on the flow-with-rate icon in the toolbar [image] .

2	To place the flow on the screen, position the cursor directly to the left of the level.

3	Click and hold the left mouse button down while dragging the flow into the level.

4	Release the mouse button when the level turns black. The connection is made correctly when the sink has disappeared into the level.

5	To create a flow out of a level, place the cursor inside the level and drag it out to the right or left.

6	Release the mouse button when the pipe of the flow is as long as you want it to be. The source will have disappeared inside the level and the sink will be visible.

7	Name your flow rates by typing over the default names "Rate_1" and "Rate_2".

To create a flow between levels

Flows can go from one level into another.

1	Place the cursor, with the flow icon selected, inside the one level.

2	Drag it into the other level and release the mouse button. Both the source and the sink will disappear when this is done correctly.

To define a flow rate

Flow rates are most often auxiliaries or constants. Defining the flow rate is then not different from defining a single auxiliary or constant.

1	Double-click on the flow rate using the left mouse button. The window that appears is the Define Variable dialog box.

2	Type a value or expression in the Definition text box. Any variables listed in the Linked Variables list must be used in the definition.

3	Type a unit into the Unit of Measure drop-down box.

4	Click the OK button to return to the workspace.


Splitting and Connecting Flow and Level

The diagram editor allows you to split and connect existing flows and levels. Some small "handles" appear when the flow symbol is selected.

To split a flow-to-level connection

1	Select a flow.

2	Point at the handle next to the level symbol

3	Press the mouse button and drag the flow away from the level. Once the flow pipe is separated from the level, a cloud symbol appears at the end of the flow pipe.

To connect an existing flow to a level

1	Select the flow.

2	Press down the left mouse button and drag the flow pipe into the level.

3	Release the mouse button when the cloud symbol has disappeared inside the level.


Working with Auxiliaries

Auxiliary variables represent information in a Powersim model. Unlike levels, auxiliaries are used to model elements of the real system that can change instantaneously. Levels, on the other hand, because they represent accumulations that need time to grow or deplete, are often modeled with a time factor that adjusts the flow(s) into or out of them.

Auxiliary symbol

Information between auxiliaries can be delayed using the Delayed Link tool; if the regular Link tool is used between them, they change instantaneously. It is left to the modeler to decide when to link auxiliaries using regular links and when to use delayed links.

Auxiliaries are formulated using algebraic equations, with no initial value given. Any other variables can be used as inputs to the equations. The modeler must decide how to formulate each equation using other auxiliaries, constants, flows, and/or levels as inputs and must decide how to combine the inputs using standard mathematical tools such as division, multiplication, addition, subtraction, and so on.

See also

Creating Auxiliaries in a Model


Creating Auxiliaries in a Model

To place an auxiliary on the screen

1	Select the auxiliary icon in the toolbar [image] with the left mouse button.

2	Move the cursor from the toolbar to the screen. Notice that the cursor now looks like an auxiliary.

3	Position the cursor wherever you would like to place the auxiliary and click again on the left mouse button to deposit it there.

4	Name the auxiliary by typing over the default name "Auxiliary_1."

To define an auxiliary

1	Double-click on the auxiliary using the left mouse button. The window that appears is the Define Variable dialog box.

2	Type a definition into the Definition text box. All linked variables, if any, must be used in the definition. In our example, we will use the definition "100 + STEP(20, 20)".

3	Type a unit into the Unit of Measure drop-down box.

4	Click the OK button to return to the workspace.

Note	If the definition of an auxiliary includes the use of certain functions, it may be that a function indicator symbol appears inside the auxiliary symbol.

To change an auxiliary into a constant

Auxiliaries are automatically changed into constants by Powersim when the definition of the auxiliary is a numerical value. For instance, if you type "100" into the Definition text box of an auxiliary and click the OK button, you will see that your auxiliary has been changed into a constant by Powersim.

Before: Definition = 100 + STEP(20, 20). The variable is an auxiliary.

After: Definition = 100. The variable is a constant.


Working with Constants

Constants are used to represent elements of the system that is being modeled that are unchanging throughout the length of the simulation. If the model should simulate for 100 time units, and each time unit represents one week, then constants should be used to model that which does not change for those 100 weeks. Sometimes, however, we will allow model users to change constants directly during a simulation run. We call such constants parameters.

Constant symbol

Constants are often used to model time factors and reference or initial values. For instance, rates are often adjusted by time factors so that the magnitude of the value being added to the level by the rate can be spread over many time units. If there is a flow of Production in a model, such as the one in our example model, it is often necessary to adjust Production over a period of several weeks. This is because production rates in real factories are not changed instantaneously. If a factory wants to increase production by 20%, the increase will usually not take place overnight. It may take several weeks to change the machines and the personnel schedules to handle such an increase. To model the situation, a constant would be used, representing the time necessary to change production, and it would be used to formulate the rate equation.

We have already used a constant as an initial value for a level (see Working with Levels). Constants as initial values can also be used as inputs to auxiliary equations, to formulate a ratio that measures the change of a variable over or under an initial value. Constants as reference values work the same way. Reference values are values that are unchanging throughout the simulation and serve as "reference points" for other variables to refer to. An example would be a reference cost of a product, such as the base cost of producing one unit of a product.

See also

Creating Constants in a Model

Initializing Constants Using Other Variables


Creating Constants in a Model

To place a constant on the screen

1	Select the constant icon in the toolbar [image] with the left mouse button.

2	Move the cursor from the toolbar to the screen. Notice that the cursor now looks like a constant.

3	Position the cursor wherever you would like to place the constant and click again on the left mouse button to deposit it there.

4	Name the constant by typing over the default name "Constant_1."

To define a constant

1	Double-click on the constant using the left mouse button. The window that appears is the Define Variable dialog box.

2	Type a numerical value such as "6" in the Definition text box.

3	Type a unit, such as "Weeks", into the Unit of Measure drop-down box.

4	Type documentation, such as "Production is set so that one-sixth of the discrepancy between the desired and actual inventory is corrected every week." into the Documentation box.

5	Click the OK button to return to the workspace.

To change a constant into an auxiliary

A constant is changed into an auxiliary by linking another variable to it. Because constants do not change over the course of the simulation, they cannot have any variables affecting them. Linking another variable to a constant therefore causes Powersim to change it into an auxiliary.

1	Create a new constant.

2	Create another variable near the constant.

3	Select the link tool from the toolbar [image] and draw a link from the other variable to the constant.


Initializing Constants Using Other Variables

A constant may only depend on other variables at the initial stage. This means that the only link type that can be connected into a constant is an initialization link. The INICONST.SIM demo illustrates how you may initialize constants using links from other variables. This is useful in many contexts, for example in simulation games where you sometimes want to be able to make the starting values of model parameters dependent on other variables in the model.

To initialize a constant using another variable

1	Start with a model where you have a constant and a another variable that you wish to use in the initialization of the constants.

2	Draw a link from that variable into the constant. The constant is changed to an auxiliary symbol.

3	Double-click on the constant and enter a new definition in the Definition text box of the Define Variable dialog box. You may use the initial value of the connected variable with the help of the INIT function, for example like this: "INIT(Level_B)".

4	Click OK to close Define Variable. The symbol will now change back to a constant symbol and the link will turn into an initialization link, as shown below.


Working with Links

Links are tools to connect the elements of a Powersim model. There are three types of links, information links, delayed links and initialization links.

  Using Information links

  Using Delayed links

  Using Initialization links


Using Information links

Information links are used to represent the transfer of information between variables in a model. The variables connected with these links are updated instantaneously.

To create an information link

1	Select the link tool from the toolbar [image] .

2	Position the mouse pointer in the center of the variable that is supposed to influence another variable.

3	Press the left mouse button, drag the link out of the variable symbol and into an auxiliary or a constant that is going to be influenced.

4	When the target variable changes color release the mouse button.


Using Delayed links

Delayed links are used to represent the transfer of information that is delayed. You can define these links to represent different kinds of delays by choosing the appropriate delay function in the definition of the auxiliary that the delayed link points to.

To create a delayed link

1	Select the delayed link tool from the toolbar [image] .

2	Position the mouse pointer in the center of the variable that is supposed to influence another variable.

3	Press the left mouse button, drag the link out of the variable symbol and into an auxiliary or a constant that is going to be influenced.

4	When the target variable changes color release the mouse button.

5	You may now use a delay function, such as DELAYPPL, in the definition of the influenced variable. Example:

Influenced_variable = DELAYPPL(Influencing_variable, 5, 0)

Hint	The above definition means that the influenced variable is assigned the value that the influencing variable had five time units ago. In other words, the influence is delayed.


Using Initialization links

Initialization links are used to set the initial values of levels. Because only flows can change levels, an information link that is drawn into a level automatically changes into a link that looks dashed, which signifies an initialization link.

To create an initialization link

1	Select the link tool from the toolbar [image] .

2	Position the mouse pointer in the center of the variable that is supposed to determine the initial value of a level variable.

3	Drag the link into a level and release the mouse button when the level changes color. The link becomes broken to signify an initialization link.

You may now use the linked variable as part of the level's initialization expression. The link will have no effect on the level during simulation runs, it only affects the starting value of the level.


Working with the Define Variable Dialog box

Each instance of defining variables in the previous sections has involved the use of the Define Variable Dialog box. Mostly, we used only three or four boxes of the window. This section of the chapter will explain all the features of the Define Variable Dialog box, from left to right and top to bottom. Use this section as a quick reference guide to the use of each of the boxes. A more complete reference is found elsewhere in the documentation.

  Variable

  Unit of Measure

  Defining Units

  Dimensions

  Definition

  Changing a Level's Flow Definition

  Documentation

  Linked Variables

  Functions

  Buttons


Variable

The Variable drop-down list contains all the variables of the model. You can use this list to define variables one-by-one, without closing the Define Variable dialog box and reopening it for each variable that must be defined. If you have made changes in the window and then choose another variable from the Variable drop-down list, Powersim will prompt you to save the changes before moving to the new variable.


Unit of Measure

The Unit of Measure drop-down list contains all the units you have specified for your model. It is important to assign units to your variables as a self-check of the correctness of your equations. In the section on levels, we defined the Inventory level with the unit "Widgets." This not only provides information to anyone wanting to use the model, but also will allow you to check your equations for errors such as if you make an equation that adds variables with the units Widgets and Weeks. Unit consistency in a model is extremely important for building confidence in the model's accuracy and completeness. With the Unit of Measure drop-down list, each time you type a new unit into the box, it will be added to the list, so that you simply have to choose any unit from the list when you want to use it for more than one variable.


Defining Units

For your own reference, units can be defined in a separate dialog box that is accessed through the Edit menu. Choosing Define Unit from the Edit menu will open the Define Unit dialog box, which allows you to add unit definitions using the Add button. If you want to use abbreviations such as "km/s" in the Unit of Measure drop-down list of the Define Variable dialog box, it may be helpful to give further explanations of the abbreviations. The Define Unit dialog box serves this purpose by allowing you to enter the abbreviation and a description of what it stands for. Newcomers to your model will then be able to access the definitions to aid their understanding of your model.


Dimensions

The Dimensions text box is used to help define variables that are arrays. Arrayed variables are defined using a range. Ranges can be specified using the Define Range dialog box (opened from the Edit menu) and apply to the entire model. Any range specified with the Define Range dialog box is then listed in the text box labeled "Ranges" in the Define Variable dialog box. Array functions that are used in the Definition text box use indexes to refer to the individual elements of the array. The indexes are set using the Dimensions text box. For instance, if you have a range labeled "Players" that represents the players in a game, you can set an index by entering "a=Players" in the Dimensions text box. Then, any array function you use in the Definition text box will use "a" when an index is called for.


Definition

The Definition text box contains the numeric value or the algebraic expression that defines the variable. When a definition is entered into this text box and the dialog box is closed, the question mark in the variable is removed. A model will not simulate unless all the questions marks are removed, so it is necessary to use the Definition text box for every variable in the model.

To add comments to the definition

Comments are used to explain the definition of a variable. They do not affect the model's behavior when it is simulated. Instead, comments are useful messages to people unfamiliar with the model. They are initiated by entering a double quote character " or a left "{" bracket into the text of the definition. Any text that follows the start comment character, until the next double quote character or a right "}" bracket, is considered part of the comment. Comments enclosed in quotes may be placed between elements of an expression.

"This is an example of a comment that is terminated by a quote"

"This is an example of a comment that is terminated by the end of the line

{This is an example of a comment inside brackets}


Changing a Level's Flow Definition

Normally you won't need to change the default flow definition of a level. In some special cases, however, you may want to constraint the flow into or out of a level.

An example is when you have an array level where a connected rate has different dimensions from the level. You may then use a constrained expression or an array function to bring the dimension of the flow in correspondence with the level's dimension.

In the example below Rate is a scalar while Level is a one-dimensional array. The effect of the constraint put on the flow definition of Level is that the value of Rate will only flow into the first element of Level while no flow will enter the second element. Note that any other numerical value than zero would be illegal in this expression. (The equations below are taken from Equations view, which can be chosen from the View menu.)

dim	Level = (i=1..2)

init	Level = 0

flow	Level = +dt*(Rate | i=1; 0)

const	Rate = 10

To change a level's flow definition

1	Choose a level as the current variable of the Variables list of the Define Variable dialog box.

2	Click on the Flow button to open the flow definition of the current level. This definition is generated automatically by Powersim when you connect flows to a level in the diagram editor

3	Type in the changes to the flow definition and confirm by clicking the Set button.


Documentation

The Documentation text box is used to add comments for each variable in the model. It is generally used for comments relating to the variable itself (what it represents in the real system) and not for comments about each element used to define the variable. Comments about each element are better placed in the Definition text box, as outlined above; therefore, the comments added here are in addition to or instead of the comments you can add to the definition of the variable. You can write anything you feel is necessary to explain the variable to someone who is unfamiliar with your model. Each model consists of a person's assumptions. What is obvious to one modeler may not be obvious to another, so these comments can be very useful when the model will be shared among several people.


Linked Variables

The list of linked variables is helpful for defining the variable. Each variable in this list must be used in the definition of the variable. The list is generated automatically by Powersim, according to the links you place in the model. All variables that are linked to the current variable as an input (with a link from another variable into the current variable) are placed into the list by Powersim. Double-click on any name in the list to have it appear in the Definition text box.


Functions

Powersim contains numerous built-in functions, including financial functions, statistical functions, array functions, standard mathematical functions, and so on. If the Functions list is not showing in your Define Variable dialog box, click on the More button in the lower right corner. To access any function, double-click on it in the list. It will then appear in the Definition text box, complete with syntax, so that you can add variables to the appropriate places to complete the function.

See also

Functions


Buttons

The buttons of the Define Variable dialog box are standard windows buttons. To use them, simply click on them once.

OK button

The OK button saves and closes the Define Variable dialog box.

Cancel button

The Cancel button closes the Define Variable dialog box without saving any changes made in the box.

Set button

The Set button checks the current definition and saves the contents of the Define Variable dialog box without closing it.

Locate button

The Locate button moves the underlying model so that the current variable is shown at the center of the window. You can then move the Define Variable dialog box aside to see the variable and the surrounding structure.

Graph button

The Graph button opens the Define Graph dialog box, which enables you to create a table function using one linked variable.

More button

The More button opens a keypad that can be used to define the variable. The keypad contains numbers and symbols so that you can enter a definition by clicking on the keypad with the mouse rather than using the keyboard.


Simulating

Simulating a model means to have Powersim compute the results over time based on the assumptions you made when you connected and defined the variables in our model.

  Preparing a Simulation Run

  Choosing Start- and Stop Time

  Choosing Time Unit

  Choosing Integration Method

  Choosing Time Step

  Putting a Model in Start-up Position

  Using the Auto Pause Facility

  Slowing Down Simulation Speed

  Running Simulations

  Performing a Continuous Simulation Run

  Performing a Stepwise Simulation Run

  Adjusting Parameters

  Initializing variables when a simulation starts

  Overview

  Initializing by equation

  Loading values from a file

  Loading values from an application using DDE

  Loading values from a co-model using Chain

  Keeping values between simulations

  Initializing parameters before the simulation starts

  Initializing values from the network simulation object


Preparing a Simulation Run

Running a simulation requires that all the variables in your model must be defined. There must be no variables that have question marks in them. Furthermore, no input dynamic objects, such as the slider/bar, must be connected to auxiliaries with an Allow Input option switched on. Powersim will issue an error message if any of the conditions mentioned keeps it from simulating your model.

  Choosing Start- and Stop Time

  Choosing Time Unit

  Choosing Integration Method

  Choosing Time Step

  Putting a Model in Start-up Position

  Using the Auto Pause Facility

  Slowing Down Simulation Speed


Choosing Start- and Stop Time

An important aspect of the modeling of a problem is the choice of a time horizon for your model. The default start- and stop times in Powersim models is 0 and 100 respectively. But very often another setting is required. In general, you should choose a time horizon that allows your model to play out the behavior of interest. For example, Jay Forrester's classical World Dynamics model is typically simulated over 200 years, from 1900 to 2100, because this is a time span where dramatic changes in the global variables, such as world population, of interest take place. And that time horizon is sufficient in order to observe the "overshoot-and-collapse" behavior that is played out by the model.

To change the start- and stop time of your model

1	Choose Simulation Setup from the Simulate menu.

2	Type the desired times in the Start Time and Stop Time text boxes of the Simulation Setup dialog box.

4	Click OK to close Simulation Setup.


Choosing Time Unit

When building a model you also have to determine the time unit of your simulation. What you should choose as your time unit depends on the problem you are modeling. While "Week" could be a natural choice in a model portraying the development of an industrial system, such as an inventory of widgets, "Year" could be more appropriate in a long term simulation of world population. What time unit you choose will have no impact on the simulation results. But it is still a good habit to state the time unit explicitly in the Simulation Setup dialog box. Furthermore, the time unit that you define will appear as labels on the time axis of all time graphs by default.

To define and apply a time unit

1	Choose Edit Define Unit to open the Define Unit dialog box.

2	Click Add and type in the time unit you wish to use, let's say "Week".

3	Click OK until you are back in the workspace and then choose Simulate Simulation Setup.

4	From the Time Unit list box select Week.

5	Click OK to close Simulation Setup.


Choosing Integration Method

The integration method you should choose depends on several conditions. In general, Euler is a good choice. However, if you anticipate that your model will generate oscillations, the Runge-Kutta methods will normally eliminate most of the integration error that can potentially, and erroneously, reinforce the oscillations.


Choosing Time Step

In general, you should choose a time step small enough to capture the shortest time frame of interest in your model. The smaller the time step you choose, the more accurate the simulation results will be. On the other hand, this makes Powersim perform more calculations per time unit, which reduces simulation speed. As a rule of thumb, the time step should be less than 1/2 but greater than 1/5 the size of the shortest first order delay in the model.


Putting a Model in Start-up Position

When testing models or running simulators we often need to make parameter adjustments from the beginning of a simulation run. In order to make our adjustments take effect from the very start of the simulation, we must begin by putting the simulation in start-up position.

To put a model in start-up position

1	With the simulation being switched off (run button is not pressed) click the run step button [image] . The run button and the pause button will now both activate, as such:

2	You can now change the parameters to the values you choose. When you are satisfied, you can resume the simulation either stepwise, by clicking run step [image], or continuously, by clicking pause [image] .


Using the Auto Pause Facility

Sometimes you wish to pause a simulation run at a specific point in time in order to change a parameter or inspect simulation results at that point. Powersim offers an easy way of doing this: Auto Pause.

To automatically pause a simulation

1	Choose Run Setup from the Simulate menu.

2	Type a number, let's say 5, into the Every <n> Time Units text box.

3	Click OK.

When the simulation reaches time 5, Powersim will now automatically switch pause on. The Pause button on the commandbar (if present) will be set to a pushed state and the Pause entry on the Simulate menu will become checked. When you switch pause off again, the simulation will run for another auto pause interval. In this way you may run a simulation in desired "time portions" until the stop time is reached.


Slowing Down Simulation Speed

In some cases you may want to reduce the speed of a simulation to be able to follow the development better. You may achieve his by using the Delay option of the Run Step dialog box.

To slow down simulation speed

1	Choose Run Setup from the Simulate menu.

2	Type a number, let's say 100, into the Delay (ms / time step) text box.

3	Click OK.

Powersim will now automatically wait for 100 milliseconds between each time step of a simulation.


Running Simulations

  Performing a Continuous Simulation Run

  Performing a Stepwise Simulation Run

  Adjusting Parameters


Performing a Continuous Simulation Run

Simulations can be run either continuously or time step by time step. The fastest way is to run it continuously and that is the way you will prefer when you are more interested in the general behavior pattern of your model than in specific variable values at certain points in time.

To run a continuous simulation from start time to stop time

1	Click on the run button [image] or choose Simulate Run.

2	You may pause and resume a simulation whenever you like by clicking the pause button [image] .

3	Let the simulation run until it has reached its stop time, or stop it manually by clicking stop [image] . You can not resume a simulation after you have stopped it. You will then have to start a new simulation run.


Performing a Stepwise Simulation Run

To run a simulation step by step

1	Click on the run step button [image] or choose Simulate Run Step.

2	The simulation will now develop one more time step each time you click the run step button. You may at any time click pause to let the simulation go on continuously or click stop to cancel the simulation.


Adjusting Parameters

In simulating mode you can use the pointer tool to adjust parameters of the model by using the buttons of slider/bar or gauge objects that control the parameters.

To set up an input object for parameter adjustment

1	Create a new input dynamic object, such as a slider/bar.

2	Drag and drop a parameter constant into the new object.

3	Set appropriate min and max values for the parameter if necessary (use Edit Scale).

4	When a simulation is in start-up position, pausing or running you may adjust the value of the parameter by using the input object.


Connectivity

The following topics describe how data may be transferred to and from Powersim using the clipboard and Dynamic Data Exchange (DDE) and how Powersim diagrams may be included in other applications as embedded or linked objects (OLE).

See

  Clipboard Services Provided by Powersim

  Transferring Model Equations

  Transferring Diagram Symbols

  Transferring Graph Function Data

  Transferring Time Series from Time Graph and Time Table Objects

  DDE Services Provided by Powersim

  Obtaining Values of Scalar Variables

  Obtaining Values of Array Variables

  Obtaining Values of Variables in Co-models

  Obtaining Values of Control Variables

  Obtaining System Information

  Controlling the Simulator

  Setting Values of Variables

  List of DDE Commands

  OLE Services Provided by Powersim

  Understanding OLE

  Powersim and OLE

  Using Powersim Data in Other Applications

  API Services Provided by Powersim


Clipboard Services provided by Powersim

See

  Transferring Model Equations

  Transferring Diagram Symbols

  Transferring Graph Function Data

  Transferring Time Series from Time Graph and Time Table Objects


Transferring Model Equations

Powersim diagrams may be transferred as text and metafiles to the clipboard. This is useful, e.g., when documenting models. This also makes it possible to export model equations to a file, which in turn may be used to translate the model to another language, etc.

To copy one or more variable equations to the clipboard

1	Select View Equations from the menus

2	Use the Format Options Equations View dialog box if you want to alter the way variables are displayed

3	Select one or more entries from the list of equations

4	Select Edit Copy from the menus (or press Ctrl+C or Ctrl+Insert)

You may now switch to another application, e.g. a word processor, and paste the copied equations.

The definition of a variable may be copied or pasted from within the Define Variable dialog box.

To copy (part of) a variable's definition to the clipboard

1	Open the Define Variable dialog box

2	Select the part of the definition you want to copy

3	Press the Copy button (or press Ctrl+C or Ctrl+Insert)

You may now switch to another variable or to another application and paste the copied text.


Transferring Diagram Symbols

If you need to include your diagram in a document, e.g., in order to make a presentation or a documentation of a model, you should use the copy area feature of Powersim's diagram editor.


Transferring Graph Function Data

Graph functions are sometimes used to represent data that has been collected or produced outside Powersim. Instead of typing in the data, you may transfer fix-points of a graph function (or vector literal) via the clipboard. This may be done either in the Definition section of the Define Variable dialog box, or using the Paste button of the Edit Graph/Vector dialog box.

Correspondingly the current fix-points of a graph function or literal vector may be copied to the clipboard using the Copy button of the Edit Graph/Vector dialog box.


Transferring Time Series from Time Graph and Time Table Objects

Simulated values are stored as time series by Time Graph and Time Table objects. These values may be transferred to the clipboard via the Copy Time Series dialog box. This dialog box is opened from the Display dialog box by pressing the Copy button. In simulation mode the Display dialog box is opened by double-clicking on a Time Graph or Time Table object. In editing mode you must open the Define Time Graph or Define Time Table dialog box and then select the Display button.


DDE Services provided by Powersim

Powersim may be connected to other applications using Dynamic Data Exchange (DDE). This topic describes how Powersim may be used as a DDE source for other applications. Powersim may also be a DDE destination (The term DDE server is sometimes used instead of DDE source. The term DDE client is sometimes used instead of DDE destination.). This is done by creating DDE objects in your document.

See

  Obtaining Values of Scalar Variables

  Obtaining Values of Array Variables

  Obtaining Values of Variables in Co-models

  Obtaining Values of Control Variables

  Obtaining System Information

  Controlling the Simulator

  Setting Values of Variables

See also

  Writing MS-EXCEL macros accessing Powersim via DDE

  Writing Lotus 1-2-3 macros to access Powersim via DDE


Obtaining Values of Scalar Variables

A DDE destination (client application) may obtain the values of Powersim variables using a request or advice transaction where the DDE-service, DDE-topic, and DDE-item are defined like the following:

Service Name	Topic Name	Item Name
Powersim	Name of Powersim document	Reference to Powersim variable
Example	The following EXCEL definition will display the value of the variable Coffee_Temp of the Powersim model COFF_TMP.SIM.

=POWERSIM|COFF_TMP.SIM!Coffee_Temp

To run the example above

1	Start Powersim and load the model COFF_TMP.SIM

2	Start EXCEL

3	Enter the definition =POWERSIM|COFF_TMP.SIM!Coffee_Temp in a cell

4	Start simulating the COFF_TMP.SIM model

5	Observe how the EXCEL cell is updated as the simulation goes on

You should position the Powersim and the EXCEL windows side-by-side before executing step 4.

Values may currently be requested only as text (in the CF_TEXT format). Numbers are represented in the format defined by Powersim's Format Options General Numerical Format setting.


Obtaining Values of Array Variables

Values of array variables are obtained one element at the time. The syntax for specifying the Item Name for an array variable follows that of the Powersim language, like this:

<variablename> <subscript>

Example	The demo model POPARRAY.SIM contains several array variables. The variable Pop has two dimensions, Age and Region. The following are examples of Item Names for accessing element values of the Pop variable.

Item Name	Explanation
Pop(Age, North)	The population in the northern region
Pop(Youth, South)	The number of young people in the southern region


Obtaining Values of Variables in Co-models

References to variables of co-models are constructed by prefixing the variable reference with the name of the co-model, followed by a period. The full syntax for an Item Name becomes:

[ <comodelname> '.' ] <variablename> [ <subscript> ]

Example item names:

Income

Price(Car)

Comodel.Area

Comodel.Population(North)


Obtaining Values of Control Variables

A special "meta co-model" Control may be used to obtain the current value of the simulation time, start and stop time, etc. See List of Control Variables

See also

Control Variables


Obtaining System Information

Powersim supports the following standard topics and items, as defined by the DDE protocol. The associated values may be obtained using the DDERequest transaction.

Topic Name	Item Name	Explanation
System	Formats	Obtain list of supported data formats. (At the time of writing only "CF_TEXT" is supported.)
System	Status	Returns the string Ready.
System	SysItems	Obtain tab-separated list of items supported under the System topic, i.e., FORMATS, STATUS, SYSITEMS, TOPICS.
System	Topics	Obtain tab-separated list of topics supported at the current time, i.e, a list starting with SYSTEM, followed by the names of all open documents.
Name of Powersim document	TopicItemList	Obtain tab-separated list of items supported under a non-System topic, i.e., the names of all parameters (scalars and array elements) of a document.


Controlling the Simulator

A DDE destination (client application) may use DDEExecute transactions to control the simulation of a Powersim model. The DDE-service, DDE-topic, and DDE-item section of an Execute transaction with Powersim looks like this:

Service Name	Topic Name	Item Name
Powersim	Name of Powersim document	Command
Powersim	System	Command
The reserved topic name System may be used to issue commands that do not refer to a document. When appropriate, System commands implicitly refer to the active document (the model owning the active window).

Available Item Names (Commands) are listed in List of DDE Commands . A DDEExecute transaction may list several commands, enclosed in square brackets. As an example, the following is a valid command argument to DDEExecute:

[OPEN(MODEL.SIM)][RUN][QUIT]

The above command consists of three single commands, OPEN(MODEL.SIM), RUN, and QUIT. Always remember to put commands inside square brackets.

Commands may have parameters that are text strings or numbers. String parameters must be put inside quotation marks (") if characters other than alphanumeric characters, '_', '$' or '.' are used. A backslash (\) may be used inside a quoted string to take the next character literally. The commands may be grouped into three groups:

Application Commands

Document Commands

Document Window Commands

Example

The following Microsoft Word macro will open the diagram COFF_TMP.SIM and start simulating the model:

ChanNum=DDEInitiate("Powersim", "System")

DEEExecute ChanNum, "[Open(" + Chr$(34) + "COFF_TMP.SIM" + Chr$(34) + ")][Run]"

DDETerminate ChanNum

Note	If COFF_TMP.SIM is not in the search path of Powersim, the entire path should be specified, e.g., like this: DEEExecute ChanNum, "[Open(" + Chr$(34) + "C:\\POWERSIM\\MOD\\COFF_TMP.SIM" + Chr$(34) + ")][Run]"


Application Commands

APP.MAXIMIZE - Maximize application window

APP.MINIMIZE - Minimize application window

APP.MOVE - Move application window to given position

APP.RESTORE - Restore application window

APP.SIZE - Size application window

QUIT - Exit application


Document Commands

FILE.CLOSE - Close active document

NEW - Create new document

OPEN - Open existing file

PAUSE - Switch pause on or off

RUN - Start simulation

RUN.STEP - Step simulation

SAVE - Save active document

SAVE.AS - Save active document in named file

STOP - Stop simulation


Document Window Commands

CLOSE - Close active window

CLOSE.ALL - Close all windows

NEW.WINDOW - Create new window for active document

WINDOW.MAXIMIZE - Maximize active or named window

WINDOW.MINIMIZE - Minimize active or named window

WINDOW.MOVE - Move active or named window

WINDOW.RESTORE - Restore active or named window

WINDOW.SIZE - Size active or named window


Setting Values of Variables

Variables of a Powersim model may be set from a DDE destination (client application) using DDEPoke transactions. The use of the Service-, Topic- and Item-names is the same as for Advice and Request transactions:

Service Name	Topic Name	Item Name
POWERSIM	Name of Powersim document	Reference to Powersim variable
Example

The following Microsoft Word macro will set the value of Room_Temp to 24 in our COFF_TMP.SIM model.

ChanNum=DDEInitiate("POWERSIM", "COFF_TMP.SIM")

DDEPoke ChanNum, "Room_Temp", "24.0"

DDETerminate ChanNum

Example

The following Microsoft Excel (version 7.0 for Windows '95) macro will set the value of Room_Temp equal to the value of spread sheet cell A2, and run the model COFF_TMP:

Sub PokeToPowersim()

Dim ChanNum As Integer

ChanNum = DDEInitiate("POWERSIM", "COFF_TMP.SIM")

DDEExecute ChanNum, "[pause][run]"

DDEPoke ChanNum, "Room_temp", Worksheets("Sheet1").Range("A2")

DDEExecute ChanNum, "[pause]"

DDETerminate ChanNum

End Sub

It is important to observe that the final parameter to DDEPoke must be a cell reference in Excel -- it cannot be a number or a string. Unfortunately Excel does not give an error message in this situation.

Note that in WordBasic (which is used to write Word macros), quotation marks indicate the beginning and end of  a text string. Therefore you must use Chr$(34) to include a quotation mark in a command string. For example, the following instruction tells Powersim to open MYMODEL.SIM:

DDEExecute CharNum, "[Open(" + Chr$(34) + "D:\\POWERSIM\\MYMODEL.SIM" + Chr$(34)+") ]"


List of DDE Commands

Overview of DDE commands recognized by Powersim

ACTIVATE - Activate document window

APP.MAXIMIZE - Maximize Powersim window

APP.MINIMIZE - Minimize Powersim window

APP.MOVE - Move Powersim window

APP.RESTORE - Restore Powersim window

APP.SIZE - Size Powersim window

CLOSE - Close active document window

CLOSE.ALL - Close all document windows

FILE.CLOSE - Close active document

NEW - Create new document

NEW.WINDOW - Create new window for active document

OPEN - Open existing document

PAUSE - Pause or resume simulation of active document

QUIT - Exit Powersim

RUN - Start simulating active document

RUN.STEP - Step simulation of active document

SAVE - Save active document

SAVE.AS - Save active document under given name

STOP - Stop simulating active document

WINDOW.MAXIMIZE - Maximize document window

WINDOW. MINIMIZE - Minimize document window

WINDOW.MOVE - Move document window

WINDOW.RESTORE - Restore document window

WINDOW.SIZE - Size document window


DDE Command Definitions


ACTIVATE - Activate document window

Syntax

ACTIVATE(window_text)

Purpose

Switches to a window if more than one window is open

In

window_text - Name of the window to switch to (e.g. "Diagram1")


APP.MAXIMIZE - Maximize Powersim window

Syntax

APP.MAXIMIZE()

Purpose

Equivalent to choosing the Maximize command from the Control menu for the application window.


APP.MINIMIZE - Minimize Powersim window

Syntax

APP.MINIMIZE()

Purpose

Equivalent to choosing the Minimize command from the Control menu for the application window.


APP.MOVE - Move Powersim window

Syntax

APP.MOVE(x_num, y_num)

Purpose

Equivalent to choosing the Move command from the Control menu for the application window. Moves the Powersim window. If the application window is already maximized, nothing happens.

In

x_num - Horizontal position of the Powersim window measured in points (1/72 inch) from the left edge of your screen to the left side of the Powersim window.

y_num - Vertical position of the Powersim window measured in points (1/72 inch) from the top edge of your screen to the top of the Powersim window.


APP.RESTORE - Restore Powersim window

Syntax

APP.RESTORE()

Purpose

Equivalent to choosing the Restore command from the Control menu for the application window. Restores the Powersim window to its previous size and location.


APP.SIZE - Size Powersim window

Syntax

APP.SIZE(width_num, height_num)

Purpose

Equivalent to choosing the Size command from the Control menu for application window. Changes the size of the Powersim window.

In

width_num - Width of the Powersim window in points.

height_num - Height of the Powersim window in points.


CLOSE - Close active document window

Syntax

CLOSE(save_logical)

Purpose

Closes the active window. CLOSE is equivalent to choosing the Close command from the document control menu.

In

save_logical - Logical value that specifies whether to save file before closing the window. The following values are accepted:

TRUE - Saves the file

FALSE - Does not save the file

Omitted - If you've made changes to the file, Powersim asks if you want to save the file


CLOSE.ALL - Close all document windows

Syntax

CLOSE.ALL()

Purpose

Equivalent to choosing the Close All command from the Window menu.


FILE.CLOSE - Close active document

Syntax

FILE.CLOSE(save_logical)

Purpose

Equivalent to choosing the Close command from the File menu.

In

save_logical - Logical value that specifies whether to save the file before closing the window. The following values are accepted:

TRUE - Saves the document

FALSE - Does not save the document

Omitted - If you've made changes to the file, Powersim asks if you want to save the file


NEW - Create new document

Syntax

NEW()

Purpose

Equivalent to choosing the New command from the File menu.


NEW.WINDOW - Create new window for active document

Syntax

NEW.WINDOW()

Purpose

Equivalent to choosing the New Window command from the Window menu.


OPEN - Open existing document

Syntax

OPEN(file_text)

Purpose

Equivalent to choosing the Open command from the File menu.

In

file_text - Name of the document you want to open. The name can include a drive and path, and can be a network pathname.


PAUSE - Pause or resume simulation of active document

Syntax

PAUSE(pauseon_logical)

Purpose

Equivalent to choosing the Pause command from the Simulate menu. Switches pause mode on or off for the active document.

In

pauseon_logical - Is a logical value that specifies whether to switch pause mode on or off for the active document.

TRUE - Switches pause mode on (if not already on)

FALSE - Switches pause mode off (if not already off)

Omitted - Toggles pause mode


QUIT - Exit Powersim

Syntax

QUIT()

Purpose

Equivalent to choosing the Exit command from the File menu.


RUN - Start simulating active document

Syntax

RUN()

Purpose

Equivalent to choosing the Run command from the Simulate menu.


RUN.STEP - Step simulation of active document

Syntax

RUN.STEP(steps_num)

Purpose

Runs the simulation in the active document for the given number of time steps.

In

steps_num - Number of steps to run. If omitted, the simulation is run for one time step.


SAVE - Save active document

Syntax

SAVE()

Purpose

Equivalent to choosing the Save command from the File menu.


SAVE.AS - Save active document under given name

Syntax

SAVE.AS(document_text)

Purpose

Equivalent to choosing the Save As command from the File menu. Use SAVE.AS to specify a new filename or to create a backup file.

In

document_text - Specifies the name of a document to save, such as MYMODEL.SIM. You can include a full path in document_text, such as C:\POWERSIM\MODELS\MYMODEL.SIM


STOP - Stop simulating active document

Syntax

STOP()

Purpose

Equivalent to choosing the Stop command from the Simulate menu.


WINDOW.MAXIMIZE - Maximize document window

Syntax

WINDOW.MAXIMIZE(window_text)

Purpose

Change window to full size. This is equivalent to double-clicking the title bar.

In

window_text - Name (caption) of window to switch to and maximize. If omitted, the active window is maximized.


WINDOW. MINIMIZE - Minimize document window

Syntax

WINDOW.MINIMIZE(window_text)

Purpose

Shrink a window to an icon. This is equivalent to clicking the minimize button on a window.

In

window_text - Name (caption) or window to minimize. The name should be enclosed in quotation marks. If omitted, the active window is minimized.


WINDOW.MOVE - Move document window

Syntax

WINDOW.MOVE(x_num, y_num, window_text)

Purpose

Equivalent to choosing the Move command from the Control menu or moving a window by dragging its title bar or its icon. Moves the window so that its upper-left corner is at the specified horizontal and vertical positions.

In

x_num - Horizontal position to which you want to move the window, measured in points (1/72 inch) from the left edge of the workspace to the left edge of the window.

y_num - Vertical position to which you want to move the window, measured in points (1/72 inch) from the top edge of the workspace to the top edge of the window.

window_text - Name (caption) of window to move. The name should be enclosed in quotation marks. If omitted, the active window is moved.


WINDOW.RESTORE - Restore document window

Syntax

WINDOW.RESTORE(window_text)

Purpose

Change window from maximized or minimized state to its previous size.

In

window_text - Name (caption) of window to switch to and restore. The name should be enclosed in quotation marks. If omitted, the active window is restored.


WINDOW.SIZE - Size document window

Syntax

WINDOW.SIZE(width_num, height_num, window_text)

Purpose

Equivalent to choosing the Size command from the Control menu or to adjusting the sizing borders. Changes the size of the active window by moving its lower-right corner so that the window has the width and height you specify. WINDOW.SIZE does not change the position of the upper-left corner of the window, nor does it affect whether the specified window is active or inactive.

In

width_num - Width of the window measured in points (1/72 inch).

height_num - Height of the window measured in points.

window_text - Name (caption) of window to size. The name should be enclosed in quotation marks. If omitted, the active window is sized.


OLE Services Provided by Powersim

The following topics give a detailed description of the linking and embedding features available in Powersim. Diagrams created in Powersim can now be included in other applications as embedded or linked objects. But before we plunge into the finer details, we will give a short description of what OLE (Object Linking and Embedding) is all about.

See

  Understanding OLE

  Linking vs. Embedding

  When to Use Linking and Embedding

  Verbs

  Powersim and OLE

  Using Powersim Data in Other Applications

  Embedding a New Object

  Creating Embedded Objects From Existing Files

  Creating a Link to an Entire File

  Using the Clipboard

  Pasting an Embedded Object

  Pasting a Linked Object

  Maintaining Links


Understanding OLE

OLE enables users to manipulate information in an intuitive manner, using an environment that is more "document-centric" and less "application-centric". Users can create compound documents with data, or objects, of different formats, and focus directly on the data rather than on the applications responsible for the data. The data can be embedded within the document, or linked to it, so that only a reference to the data is stored in the document

A compound document is a document within a container application that seamlessly integrates data of different formats. Each piece of integrated data, referred to as a compound document object, is created and maintained by its object application (or server application).

See also

  Linking vs. Embedding

  When to Use Linking and Embedding

  Verbs


Linking vs. Embedding (OLE)
Linking vs. Embedding

The main difference between linking and embedding is where the data is stored.

When an object is linked, the source data, or link source, continues to physically reside wherever it was initially created, either at another point within the document or within a different document altogether. Linked data is updated when the data in the source document changes. Linked data is stored in the source file; the container application stores only the location of the source, but displays a representation of the linked data. Linked objects cannot travel with documents to another machine; they must remain within the local file system or be copied explicitly.

In the case of an embedded object, a copy of the original object is physically stored in the compound document as is all the information needed to manage the object. A compound document containing embedded objects will be larger than one containing the same objects as links. But on the other hand, compound documents can be transferred to another computer and edited there.


When to Use Linking and Embedding (OLE)
When to Use Linking and Embedding

Embed data that are fairly stable, when you don't need to have the most current versions in your document, when the embedded data does not need to be included in more than one document, or when the source documents would not be available for updating if they were linked.

Embedded objects can also be edited, or activated, in place (linked objects cannot). This means all maintenance of the object can be done without leaving the compound document (if the object application supports in-place editing)

Link data that are likely to change, when it is essential that your document includes the latest version available, when the source documents are available on your computer or across a network whenever they need to be updated, when it is important to keep the size of the compound document small, or when the source data need to be shared with more than one document.


Verbs (OLE)
Verbs

Verbs are the set of operations supported by a particular object. The set of object-specific verbs can differ for each object type because different verbs make sense for different objects. For example, a sound object's verbs might include play, rewind, and edit, while a text object might only support edit.

Hint	If you want to take advantage of OLE, make sure your system has sufficient RAM for both the object application and the container application to run simultaneously.


Powersim and OLE

Powersim Object Application

You can use Powersim documents as source documents for data you link or embed in documents created in other applications (container documents). In this case, Powersim is referred to as the object application.

In some applications, an embedded object remains in place when you double-click to activate it, and the container document remains visible surrounding it. This is called in-place activation.

In-place activation requires that both the container application and the object application support the in-place activation protocol. Powersim does not support in-place activation; therefore double-clicking a Powersim object in another application starts Powersim in a separate window and opens the object for editing. To return to the container application you can choose the Exit command on the File menu.

Powersim supports both linking and embedding. Links can be established to an entire document or to an area within a document (often referred to as a pseudo-object). We'll see some examples of this later on. There is one limitation though, embedding doesn't work with co-models, i.e., only pure main-models can be the source of an embedded object. Linking works also with co-models.

Powersim supports two verbs: Play and the ubiquitous Edit. The primary verb Edit launches the Powersim application and opens the object for editing. The secondary verb Play launches the application, opens the object, and starts simulating it.


Using Powersim Data in Other Applications

Suppose you are putting together a presentation of a simulation model (using your favorite word processor, let's say Microsoft Word). Sooner or later, you want to include diagrams from the underlying model and this is when object linking and embedding comes in handy.

See also

  Embedding a New Object

  Creating Embedded Objects From Existing Files

  Creating a Link to an Entire File

  Using the Clipboard

  Pasting an Embedded Object

  Pasting a Linked Object

  Maintaining Links


Embedding a New Object

If you have not yet written the Powersim model, you have to create a new Powersim object from scratch. Position the insertion point where you want the object to appear, and then choose Object from Word's Insert menu (some applications use an Insert Object command in the Edit menu). The Object dialog appears, displaying a list of the types of objects you can create and embed. Select the Create New option, select Powersim 2.0 Diagram as the object type, and choose the OK button.

Word opens Powersim, and you can begin working on the Powersim object you want to add to your Word document. When you are working on an embedded object, you will notice some small differences in Powersim's File menu.

The Save command is replaced by Update, which forces the picture of the current object to be updated within the container document. Save As is replaced by Save Copy As which writes a copy of the current object to a file. Save All is replaced by Save and Update All since embedded objects will be updated rather than saved. Close is changed to Close and Return to <container document>.

When you exit Powersim, the diagram is displayed in your Word document. When you want to edit the diagram, double-click it to start Powersim and make whatever modifications you like. You can also edit an embedded object by using the Object command on the container application's Edit menu.

If you can see the windows of both applications while working on the Powersim object, you will notice that the picture representation in Word is displayed under a hatch pattern to indicate that the object is currently open. When you quit Powersim and return to Word, this hatch pattern disappears.

When an embedded Powersim object is created with the Create New option of the Insert Object dialog, the upper left corner of the object is displayed in the container document. If you want to show another part of the object, create an area that encloses the requested part and then choose Update on Powersim's File menu. When an area exists, Update sets the rectangle to use for the picture representation of the object.

You can display the embedded object as an icon when the container document will be used primarily on-screen or when the Powersim object contains supplementary information. To do this (in our example), select the Display As Icon check box in the Object dialog box. The icon can even be changed by choosing the Change Icon button.


Creating Embedded Objects From Existing Files

In addition to creating embedded objects as you work, you can embed existing Powersim files. If you embed an existing file, the container application stores an independent copy of the file in its document. The original file remains unchanged, even if you change the embedded file.

To embed an entire existing document in our example, choose Object from Word's Insert menu. Select the Create From File option, select the filename, and then choose the OK button. The picture displayed in the container does not show the entire document, only a section of the first page. As usual, you can change which part of the document to show by dragging out an area and then choosing the Update command on the File menu (see above). To display the object in the Word document as an icon instead of the object itself, select the Display As Icon check box.


Creating a Link to an Entire File

You can create a link to an entire Powersim document without leaving the container application. In our example with Microsoft Word, choose Object from the Insert menu. Select the Create From File option, in the File Name box, type or select the name of the file to which you want to link, select the Link To File check box, and choose the OK button. Linked objects also can be displayed as icons, by selecting Display as Icon in the Object dialog box.

To edit a linked Powersim object, you can either double-click the object, or you can select it and then choose the object's name from the Edit menu. In our case, the Edit menu (of for example Word) displays the command "Linked Diagram Object". When you choose the Edit command from this cascaded entry, Powersim opens the linked document for editing.


Using the Clipboard

When you cut or copy data, Powersim temporarily stores the data on the clipboard. You can then paste the data into a document created with another application, such as Microsoft Word. In Powersim, there are two different copy operations. If an area exists, the contents of this rectangular area is copied to the clipboard . (Note that Edit Cut doesn't work with areas). If an area doesn't exist, the current selection is copied to the clipboard (Edit Cut also removes the current selection).

Only the copy operation based on an area, works with linking and embedding. To transfer a Powersim object via the clipboard, you drag out an area in a diagram, choose Edit Copy, switch to another application, and paste an embedded or linked Powersim object into the container document (using the Paste or Paste Special commands).

In previous versions of Powersim, a copy operation based on an area copied the enclosed rectangle as a metafile and as a bitmap including even the selection markers if they existed (This is sometimes useful for documentation purposes.) If Shift is pressed while copying an area, the copy operation works in the same way as in previous versions.

Some applications allow you to select data or graphics and drag them to another active application window. This drag-and-drop functionality, is, however, not supported by Powersim.


Pasting an Embedded Object

To paste an embedded Powersim object into a container document

1	Copy an area in Powersim by choosing Edit Copy.

2	Switch to the container application, e.g. Microsoft Word, and choose Paste Special from the Edit menu.

3	Select the Paste option button.

4	In the As box, select the item named "Powersim 2.0 Diagram Object".
To display the embedded information as an icon in the container document, select the Display As icon check box.

5	Choose the OK button.


Pasting a Linked Object

To paste a linked Powersim object into a container document

1	Make sure that you save the source file before you link the information.

2	Copy an area in Powersim by choosing Edit Copy.

3	Switch to the container application, e.g. Microsoft Word, and choose Paste Special from the Edit menu.

4	Select the Paste Link option button.

5	In the As box, select the format you want.
To display the embedded information as an icon in the container document, select the Display As icon check box.

6	Choose the OK button.


Maintaining Links

For information on how to maintain links (reconnect, change and update) see the user's manual of the container application. Containers normally provide link maintenance through the Links dialog box.


API Sercives Provided by Powersim
API Services Provided by Powersim

Application Programmers Interface (API) is a set of components that allows programmers to access Powersim from other applications, including Visual Basic, C++ and Delphi. By controlling Powersim using the APIs, you can create custom interfaces to models or embed models in other applications.

Note	API is only available in Professional version. The reference documentation of the API features is only available in online Help format.


Error Explanations
Error Messages

This topic lists error messages issued when you try to confirm erroneous variable definitions or dimension declarations in the Define Variable dialog box.

C0001 - <...> is expected

C0002 - Error in number

C0003 - Index expression out of range

C0004 - Dimension mismatch

C0005 - Unknown name '...'

C0006 - Illegal variable reference

C0007 - The linked variable '...' is not used

C0008 - Index variable constrained twice

C0009 - Internal error during second pass!

C0010 - Dimension check error! (CAUSE)

C0011 - Constrained expression ambiguous

C0012 - Constrained expression incomplete

C0013 - The only valid number in flow definitions is 0

C0014 - The only rate reference allowed is '...'

C0015 - Not enough memory to compile variable

C0016 - Function '...' not allowed inside parameter no <n> of function '...'

C0017 - '...' is not a delayed link variable

C0018 - The delayed link variable '...' is not used

C0019 - Constrained expressions not allowed inside functions returning arrays

C0020 - Index variables not allowed in functions returning arrays

C0021 - Cannot convert '...' to a real number

C0022 - Cannot mix elements from different enumeration ranges

C0023 - Minimum greater than maximum in range '...'

C0024 - Cannot perform operation '...' + '...'

C0025 - Cannot perform operation '...' - '...'

C0026 - Index variables cannot be converted using a subrange

C0027 - The index '...' used twice

C0028 - The range '...' is not well-defined

C0029 - Link from the variable '...' is needed

C0030 - The dimensions of the variable '...' is not well-defined

C0031 - Nested constraints not allowed

C0032 - The element '...' is not defined

C0033 - The expression is too complex

C0034 - Arithmetic expressions involving multiple indices not allowed

C0035 - Cannot compile function '...' due to a license mismatch in function library '...'

C0036 - Integer out of range


Error C0001
Error C0001 - '...' is expected

When a variable definition is not complete, according to the Powersim syntax, this error message points out what might be missing. Powersim automatically selects the part of the definition where the missing element should be inserted.

For example, if you enter "A +" in the Definition box of Define Variable and hit the Set button, the error message will say: "Operand is expected". This is because the + operator requires an operand behind it. A legal definition would be: "A + B", provided that both the operands A and B are linked to the variable that is being defined.

Examples

Examples of elements that may be pointed out as expected in this error message:

Element	Example	Explanation
, (comma)	IF(A > 0, B C)	Comma between arguments B and C in the function call
Operand	A +	The + operator must be followed be, for example a variable name, a function call, or a number
)	IF(A > 0, B, C	Right parenthesis after last argument of the function
(	IF A > 0, B, C)	Left parenthesis before first argument of the function
End of definition	A B
Integer	i = 1..	Dimension definition where upper range limit is missing


Error C0002
Error C0002 - Error in number

The selected number is not legal according to the Powersim syntax. Example of a legal number is: "1.23".


Error C0003
Error C0003 - Index expression out of range

A definition contains a reference to an array variable using a subscript where the selected index exceeds the actual range of the referenced variable. In the example below:

dim	A = 1..3

aux	B = A(4)

the definition of B is illegal because A contains only three elements.


Error C0004
Error C0004- Dimension mismatch

The dimension of the selected expression does not match the dimension declaration of the variable that is being defined. See examples below:

Declaration/Definition	Comment
aux B(i=1..4) = [1,2]	Illegal: There are only two elements in the definition of B, while the variable is declared with 4 elements.
aux B(i=1..4) = [1,2,5,7]	Legal: Both the declaration (i=1..4) and the definition ([1,2,5,7]) contains 4 elements.
aux A(1..2) = TIME aux B(i=1..4) = A	Illegal: Since A is declared as having 2 elements and B is declared as having 4 elements, A must be subscripted to be used in the definition of B.
aux A(1..2) = TIME aux B(i=1..4) = A(i) | i=1..2 ; 0	Legal: Despite of the different dimension declarations of A and B, we can still define B in terms of A since A has been subscripted and constrained to match the dimensions of B.


Error C0005
Error C0005 - Unknown name '...'

The selected text string is not a known variable or function. Maybe it is due to a misspelling?


Error C0006
Error C0006 - Illegal variable reference

The selected variable is not linked to the current variable, or it is erroneously connected using a delayed link instead of a regular link. Close the Define Variable dialog box and draw a connection from the selected variable to the variable to be defined, using a proper link type.


Error C0007
Error C0007- The linked variable '...' is not used

All linked variables must be used in the definition of the current variable. The list box labeled Linked Variables in the Define Variable dialog box contains all linked variables. If some of the linked variables are not needed in the definition, close the dialog box and delete the links in question. This may be done by first selecting the links and then choose Edit Clear.


Error C0008
Error C0008 - Index variable constrained twice

An index variable is used twice in a guard list. In the example below:

dim	A = (i=1..10)

aux	A = TIME WHEN i>2 AND i<7 BUT TIME/2 OTHERWISE

the index variable i is used in two different guards in the same guard list. A legal definition would be:

dim	A = (i=1..10)

aux	A = TIME WHEN i=3..6 BUT TIME/2 OTHERWISE


Error C0009
Error C0009 - Internal error during second pass!

This is an error that should never occur. Please save document and report to Powersim.


Error C0010
Error C0010 - Dimension check error! ('...')

A function does not accept the dimensions of the selected parameter.

If the following definition is attempted:

aux	B = ARRMAX(3)

the error message will signal: Dimension check error! ('Array expected!)

Note	Functions that accept array parameters are greedy, that means that if the variable passed is not subscripted, the function will grab all dimensions.


Error C0011
Error C0011 - Constrained expression ambiguous

Some of the elements of the current array variable is defined twice. In the example below the variable is defined twice for i=3:

dim	A = (i=1..4)

aux	A = 5 WHEN i<=3 BUT 3 WHEN i>2

See also

Constrained Expressions


Error C0012
Error C0012 - Constrained expression incomplete

Some of the elements of the current array variable is not defined. In the example below the variable is not defined for i=3.

dim	A = (i=1..4)

aux	A = 5 WHEN i<3 BUT 3 WHEN i>3

See also

Constrained Expressions


Error C0013
Error C0013 - The only valid number in flow definitions is 0

The selected number is not legal in the flow definition. It may be substituted with zero (0) for the flow definition to become legal. This error occurs when you edit a level's default flow definition (generated from the flows connected in the diagram). You may substitute the flow (or parts of the flow if the level is an array) with zero but not with another numerical value. In the example below the number 10 in the flow definition of Level is illegal.

dim	Level = (i=1..2)

init	Level = 0

flow	Level = +dt*(Rate | i=1; 10)

const	Rate = 10


Error C0014
Error C0014 - The only rate reference allowed is '...'

The selected text is not recognized as the name of a connected flow rate. Replace the selection with the correct rate name or another legal flow definition.


Error C0015
Error C0015 - Not enough memory to compile variable

Powersim can not allocate enough memory to add a new variable definition to the current model. Try to free up memory, for example by closing other running applications.


Error C0016
Error C0016 - Function '...' not allowed inside parameter no <n> of function '...'

Functions that allocate memory or generates internal levels may not be used as computational parameters. In the example below, the second parameter of the IF function is illegal since a function that generate internal levels is used as a computational parameter.

aux	A = TIME

aux	B = IF(TIMEIS(5), DELAYMTR(A, 3), 0)


Error C0017
Error C0017 - '...' is not a delayed link variable

The selected variable must be connected to the current variable using a delayed link. This is required for all input arguments to delay functions. In the example below, A must be connected to B using a delayed link for the definition of B to be legal.

aux	A = TIME

aux	B = DELAYINF(A, 1)


Error C0018
Error C0018 - The delayed link variable '...' is not used

The actual variable, which is connected to the current variable using a delayed link, must be used as a delayed parameter in order for the definition to be legal. In the first example below A is a delayed parameter , while in the second example, A is not a delayed parameter:

aux	B = DELAYINF(A, 1)	"A is a delayed parameter"

aux	B = SQRT(A)	"A is not a delayed parameter"


Error C0019
Error C0019 - Constrained expressions not allowed inside functions returning arrays

The selection indicates that you tried to use a constrained expression as part of an argument to a function that returns an array. In the example below the constrained expression "1 WHEN i=1 ; 2" is illegal inside the LOOKUP function, since the function returns an array in this case.

dim	A = (1..3, 1..2)

const	A = [[2,4], [6,1], [3,5]]

dim	B = (i=1..2)

aux	B = LOOKUP(A, 1 WHEN i=1 ; 2)


Error C0020
Error C0020 - Index variables not allowed in functions returning arrays

The function where the selected index variable is used returns an array. Therefore it doesn't accept that parameters are expressed in terms of index variables. In the example below, using the index variable i inside the VECTOR function is illegal.

dim	A = (i=1..2)

aux	A = VECTOR(1, B(i))

dim	B = (1..2)

const	B = 1


Error C0021
Error C0021 - Cannot convert '...' to a real number

The selected expression contains an attempt to convert a range to a real number, which is not possible. In the example below the definition of A is illegal because the FIRST function attempts to convert Region to a real number. B is legal because the range Region is converted to an index, which is an integer.

range	Region = NORTH, EAST, SOUTH, WEST

aux	A = FIRST(Region)

dim	B = (R=Region)

const	B = 10 WHEN R=FIRST(Region) BUT 0


Error C0022
Error C0022 - Cannot mix elements from different enumeration ranges

The selected range specification is not legal since the elements origin from different range variables. In the example below the dimension of A tries to mix elements from the ranges Age and Region.

range	Age = YOUNG, ADULT, OLD

range	Region = NORTH, EAST, SOUTH, WEST

dim	A = (i=YOUNG..SOUTH)


Error C0023
Error C0023 - Minimum greater than maximum in range '...'

The selected dimension specification is illegal. In the example below the dimension of B is illegal, since the minimum must always be less then the maximum:

dim	B = (i=4..3)

aux	B = A(i)


Error C0024
Error C0024- Cannot perform operation '...' + '...'

The plus (+) operation attempted by the selected part of the dimension declaration is illegal. In the examples below, A is illegal while B and C are legal. The general rule is that you may add a range element and a number, but not you may not add two range elements.

range	Region = NORTH, EAST, SOUTH, WEST

dim	A = (i=NORTH..NORTH+SOUTH)	"Illegal"

dim	B = (i=NORTH..2+NORTH)	"Legal"

dim	C = (i=NORTH..NORTH+2)	"Legal"


Error C0025
Error C0025 - Cannot perform operation '...' - '...'

The minus (-) operation attempted by the selected part of the dimension declaration is illegal. In the examples below, A and B are illegal while C and D are legal. The general rule is that you may subtract a number from a range element, but not vice versa.

range	Region = NORTH, EAST, SOUTH, WEST

dim	A = (i=NORTH..4-SOUTH)	"Illegal"

dim	B = (i=NORTH..WEST-YOUNG)	"Illegal"

dim	C = (i=NORTH..WEST-NORTH)	"Legal"

dim	D = (i=NORTH..WEST-2)	"Legal"


Error C0026
Error C0026 - Index variables cannot be converted using a subrange

The selection contains an attempt to convert an index variable using a subrange, which is illegal. In the example below, the definition of A is illegal because it contains a conversion of the index variable i using the subrange Subregion.

range	Age = YOUNG, ADULT, OLD

range	Region = NORTH, EAST, SOUTH, WEST

range	Subregion = NORTH..EAST

dim	A = (i=1..3)

aux	A = B(Subregion(i))

dim	B = (Age)

const	B = 1


Error C0027
Error C0027 - The index '...' used twice

This error message is no longer used.


Error C0028
Error C0028 - The range '...' is not well-defined

The selected range is not well-defined. If the range is defined as a global range you should open the Define Range dialog box and redefine the range. Example

range	ErrRange = 1..0


Error C0029
Error C0029 - Link from the variable '...' is needed

The actual variable must be connected to the current variable using a link. In the example below, there must be an initialization link from A to B, since the DELAYINF function uses ist first argument, which is A, as a default initialization of the delay.

aux	A = TIME

aux	B = DELAYINF(A, 1, 1)


Error C0030
Error C0030 - The dimensions of the variable '...' is not well-defined

The dimension of the selected variable is erroneous. Redefine the dimension of the selected variable and make sure it is well-defined. In the example below the dimension of variable A is illegal and therefore B is illegal as well.

range	ErrRange = 1..0

dim	A = (ErrRange)

aux	A = 1

aux	B = A(1)


Error C0031
Error C0031 - Nested constraints not allowed

Constrained expressions may not be nested. In the example below, A is illegal, while B expresses the same as was intended by A by using the AND operator.

dim	A = (i=1..3,j=1..2)

const	A = (1 WHEN i=1 BUT 0 OTHERWISE) WHEN j=1 BUT 2 OTHERWISE

dim	B = (i=1..3,j=1..2)

const	B = 1 WHEN i=1 AND j=1 BUT 2 WHEN j >1 BUT 0 OTHERWISE


Error C0032
Error C0032 - The element '...' is not defined

The selected range element is outside the defined range interval. In the example below both A and B are illegal.

range	Region = NORTH, EAST, SOUTH, WEST

dim	A = (i=Region(1)..Region(7))

dim	B = (i=NORTH..NORTH+4)


Error C0033
Error C0033 - The expression is too complex

The definition exceeds the complexity limit for Powersim expressions. The selection indicates at which level the limit was approached. The example below would become legal by removing the outer SIN function.

aux	A = SIN(SIN(SIN(SIN(SIN(SIN(SIN(SIN(SIN(SIN(SIN(SIN(SIN(TIME)))))))))))))


Error C0034
Error C0034 - Arithmetic expressions involving multiple indices not allowed

The selected array index is illegal because it consists of multiple index variables. In the example below the definition of A is illegal since we tried to use i + j as index to B.

dim	A = (i=1..3,j=1..3)

aux	A = B(i+j)

dim	B = (1..5)


Error C0035
Error C0035 - Cannot compile function '...' due to a license mismatch in function library '...'

The indicated function belongs to a function library which the current Powersim system are not licensed to use.


Error C0036
Error C0036 - Integer out of range

Integers must be in the range [-32750..32750]. The dimension below is illegal.

dim	A = (i=32750..32750+1)


Answers to Common Questions
Frequently Asked Questions

This chapter gives you answers to a number of frequently asked questions about Powersim. The questions are divided into three subgroups. When you have a question, please look at the answered questions below before consulting Powersim Support Services.

See

Diagram editor, view, and copying

Printing

Advanced uses, miscellaneous

Updated FAQ

Our Internet Homepage contains a Frequently Asked Questions section, which is updated regularly. We will also make an updated help file of the most important FAQs, which may be downloaded from our Web Site. To view the updated FAQ file, please click the link above.


Diagram editor, view, and copying

1	How can I copy a selection in a diagram and paste it as a picture in another application?

2	Why does the last part of my object text sometimes disappear when I change the zooming of a diagram?

3	I could not move a selected group of objects in a diagram. Why?

4	What happens when I use auto reports on array variables?

5	When I name a variable, the name disappears as soon as I hit the Return key!

6	If I choose Normalized View for my time graph, everything disappears, including axis, values and titles!

Note	To display the answer to a question, click on it!


How can I copy a selection in a diagram and paste it as a picture in another application?

Answer: You must copy the selection as an area, this means you must use the right mouse button to drag out the selection.

See also

Creating Areas


Why does the last part of my object text sometimes disappear when I change the zooming of a diagram?

Answer: Powersim formats texts according to 100% scaling of the diagram. Since MS-Windows is not capable of sizing fonts accurately when scaled, texts may appear too wide or too narrow when the diagram is zoomed. Normally you may avoid this problem by making the objects containing the text a little larger than seems necessary when zoomed to 100%.


I could not move a selected group of objects in a diagram. Why?

Answer: When a group of selected variables contains more than one item, at least one of which is a rate directly connected to a flow valve (see left figure below), the selection may be moved only for dropping purposes. This means that the selection may be dropped into a dynamic object (see Adding Variables to Dynamic Objects) but may not be moved to another location in the diagram. When you start to move such a selection, the statusbar (if present) will display: "Selection available for dropping only". If you try to complete the move operation without dropping the selection into a dynamic object, a message box will appear saying: "Attempt to move a selection that was available for dropping only". If you want to move a rate along with other variables, you must include the flow object to which the rate is connected in the selection (see right figure below).

Selection may be moved only for dropping	Selection may be moved in the diagram


What happens when I use auto reports on array variables?

Answer: When using arrays in combination with auto reports, it is only the values of the first dimension in the array variable that show. To be able to see all values of the array, you may use an array graph or a time table.


When I name a variable, the name disappears as soon as I hit the Return key!
When I name a variable, the name disappears as soon as I hit the Return key.

Answer: The name is already used by another variable.


If I choose Normalized View for my time graph, everything disappears, including axis, values and titles!
If I choose Normalized View for my time graph, everything disappears, including axis, values and titles.

Answer: In Normalized View the scaling of each variable is displayed to the left of the time graph. The solution is to make the time graph object larger and/or switch off Labeled Scales in the Define Time Graph dialog box.


Printing

1	Why don't my bitmap picture show on a printout?

2	Why do graphs with light colors turn to black when I print them?

3	How can I see and/or print a full documentation of my model, including my own documentation of each equation?

4	Text is cut off in the printout.

Note	To display the answer to a question, click on it!


Why don't my bitmap pictures show on printout?
Why don't my bitmap picture show on a printout?

Answer: If your document contains picture objects of type Bitmap, these objects may not show on printouts. To avoid this, follow the recommendation given in Picture Object . For example, if you copy bitmaps from Microsoft Windows Paintbrush, you should clear Options Omit Picture Format.


Why do graphs with light colors turn to black when I print them?

Answer: It is possible that your printer does not distinguish between different color shadings. If you cannot find the solution in the printer setup, try this:

1	Open the Define Time Graph dialog box.

2	Choose either the Background or Graph Area button. There you may define the Interior part for the graph.

3	Choose None in the list for Pattern.

4	Click your way out with OK.

5	Try to print again.


How can I see and/or print a full documentation of my model, including my own documentation of each equation?

Answer:

1	Open Format Options.

2	Select the Equations View category.

3	Now choose the elements you want to display when you are in the Equations View.

4	Print the model with documentation by choosing "Equations" or "Diagram and Equations" in the Print dialog box.


Text is cut off in print.
Text is cut off in the printout

Why does my model sometimes appear different on paper than it does on the computer screen? In particular, names of variables and information in text boxes are sometimes cut off.

Answer: Try the following:

•	Spread the variables out more on the screen to leave room for their names.

•	You may need to leave a lot of space between items, depending on the resolution of your printer.

•	Make text boxes larger on the screen to avoid losing some letters during printing.


Advanced uses, miscellaneous
Advanced uses, and miscellaneous information

1	Why do I loose settings saved in a co-model?

2	Arrays as input parameters to delay functions?

3	What is the maximum number of variables allowed in a Powersim model?

4	I wish to make sure that a flow runs only in one direction (uniflow). Is this possible with Powersim?

5	How do I import data using DDE?

6	Generations in time graph

7	Oscillations are amplified

Note	To display the answer to a question, click on it!


I loose settings saved in a co-model.
Why do I loose settings saved in a co-model?

Question: A main model with a window into a co-model contains a time table. The time table was saved with the Time option Step not equal to the Auto setting. Why does the Step value go back to Auto when I open the main model after having closed it?

Answer: This happens because Times and Scale settings of dynamic objects are instance data. This means that if one model is used as a co-model by several main models, these options may have different values, which are saved in each main model. The solution to your problem is to make sure that you save the main model after having edited Times and Scale settings of a co-model object.


Arrays as input parameters to delay functions?

Question: I tried to use an array variable as input parameter to a delay function, for example: DELAYPPL(ArrayVar, 5), but then a message box appeared, saying that a scalar was expected. Does it mean you can not pass arrays as input parameters to delay functions?

Answer: Yes, you can, but you must make use of an index variable to do so. In the example below, the index variable i, declared in the Dimensions part of the definintion of ArrayDelayed, is used as a subscript of ArrayVar. This makes the DELAYPPL function return the delayed values for each element of ArrayVar.

	dim ArrayDelayed = (i=1..3) aux ArrayDelayed = DELAYPPL(ArrayVar(i), 5) dim ArrayVar = (1..3) const ArrayVar = [1,2,3]


What is the maximum number of variables allowed in a Powersim model?

Answer:

For Windows 3.x:

6500 variables or array elements. This means that the number labeled "Array Elements + Scalars" in the File Properties Statistics dialog box can not exceed 6500.

For Windows 95 and NT:

In earlier versions of Powersim, only 6500 array elements were allowed. Now, if you run Windows 95 or Windows NT, your model can contain up to 30000 array elements. The maximum number of variables allowed is still 6500, and the maximum number of elements per array variable is still 4000. One more constraint applies to the maximum number of array elements, namely that the maximum number of level elements cannot exceed 8000.

This means that the number labeled "Array Elements + Scalars" in the File Properties Statistics dialog box can not exceed 30000.


I wish to make sure that a flow runs only in one direction (uniflow). Is this possible with Powersim?

Answer: In the definition of the flow rate you may use the MAX function, for example, like this: MAX(0, SINWAVE(-5, 5)).


How do I import data using DDE?

Question: I tried to import data from a spreadsheet using the DDE object. But the constant that I used as a parameter for the DDE import still has a question mark within it after I have defined the DDE object, and Powersim says "Unable to simulate". What did I do wrong?

Answer: You must give the constant a default definition, such as 0. The DDE link will update this value anyway.


Generations in time graph

Question: I used generations in a time graph to show several different simulations for some chosen variables. I did not like the setting for the three last simulation runs, so I deleted them from the Display list (inside the Define Time Graph). But when I now continue the simulations, nothing new gets added to the graph itself.

Answer: What happened is that you have deleted the parameter that contains the values from the latest run. This one has no number (i.e. #8) indicator after the variable name. When you delete this one, you automatically say that you are not interested in any further values for this particular variable. When used with intention, this might come in handy at some other time.


Oscillations are amplified

Question: I copied a classic model which was supposed to show sustained oscillations. But when I simulated it, the oscillations amplified (increased) rapidly. What is wrong?

Answer: You might need to reduce the time step or choose a higher-order integration method, such as Runge-Kutta 2, 3, or 4. Both settings are found in the Simulation Setup Dialog box.


Functions

This topic provides you with an overview and an alphabetical reference, with formal descriptions, of all functions found in Powersim. The functions are organized into 17 function groups.

Note	Some functions are assigned to more than one group. This makes it easier to select the correct group when searching for a function, for example in the Functions list of the Define Variable dialog box.

Function Groups

  Array Functions - Functions that utilize one or more arguments which are arrays

  Built-in Functions - Functions that are part of the simulation language

  Complex Functions - Functions that operate on complex numbers.

  Conditional Functions - Functions that perform different tasks, based on conditions passed as arguments

  Control Functions - Functions used to control a simulation run.

  Conversion Functions - Functions that convert a value from one type to another.

  Delay Functions - Functions that imply a delayed influence.

  Financial Functions - Functions that compute present value, future value, and periodic payments

  Graph Functions - Functions whose results are tabulated for given input values

  History Functions - Functions where past values of arguments are used in computing the value of the function

  Logical Functions - Functions returning a logical value representing True or False.

  Mathematical Functions - A function group containing all kinds of mathematical calculations

  Miscellaneous Functions - Functions that do not fit well into other groups

  Random Functions - Functions that depend on a random number generator

  Statistical Functions - Functions that perform computations on a set of data provided as arguments

  Time Related Functions - Functions that utilize parameters or return values that are expressed in the time unit of the simulation

  Trigonometric Functions - Functions for performing trigonometric operations

See also

  Alphabetical list of functions

  Function Reference

  List of Functions

  List of Operators

  Using Powersim Functions


Array Functions

Array functions utilize one or more arguments which are arrays.

  ABSC - Absolute value of complex number or array

  ADD - Sum of arrays

  ADDCR - Sum of complex and real numbers or arrays

  ADDRC - Sum of real and complex numbers or arrays

  ANGLEC - Angle of complex number or array

  ARRAVG - Average of Array Elements

  ARRMAX - Maximum of Array Elements

  ARRMIN - Minimum of Array Elements

  ARRPROD - Product of Array Elements

  ARRSTDDEV - Standard Deviation of Array Elements

  ARRSUM - Sum of Array Elements

  CARTOPOL - Convert complex number or array from Cartesian to Polar form

  DELAYPPLINFV - Variable Time Information Pipeline Delay through Vector

  DELAYPPLMTRV - Variable Time Material Pipeline Delay through Vector

  ELEMCOUNT - Number of Elements in an Array

  IMAGC - Imaginary part of complex number or array

  INVERT - Inverted square matrix

  INVERTC - Inverted complex number or square matrix

  LOOKUP - Lookup Value of Array Element

  MATRIXPROD - Matrix Product

  POLTOCAR - Convert complex number or array from Polar to Cartesian form

  PROD - Product of Expressions Over Indices

  PRODC - Product of complex numbers, vectors or arrays

  PRODCR - Product of complex and real numbers, vectors or arrays

  PRODRC - Product of real and complex numbers, vectors or arrays

  REALC - Real part of complex number

  SCANEQ - Scan Vector for Equal Element

  SCANGT - Scan Vector for Greater Element

  SCANGTEQ - Scan Vector for Greater or Equal Element

  SCANLT - Scan Vector for Smaller Element

  SCANLTEQ - Scan Vector for Smaller or Equal Element

  SCANNEQ - Scan Vector for Unequal Element

  SHIFTCIF - Conditional Circular Shift of Vector Elements

  SHIFTLCNT - Linear Shift of Vector Elements

  SHIFTLIF - Conditional Linear Shift of Vector Elements

  SPROD - Scalar Vector Product

  TRANSPOSE - Transpose Matrix

  TRANSPOSEC - Transposed matrix of complex numbers

  VECTLEN - Vector Length

  VECTOR - Create Vector

  VECTPROD3D - 3D Vector Cross Product


Built-in Functions

Built-in functions are part of the simulation language.

  | - Guard Operator

; - Constraint operator

  AND - Conjunction, Logical And

  BUT - Constraint operator

  COUNT - Get Number of Elements of Range or Base Range of Index

  DEFAULT - Default Guard of Constrained Expression

  FIRST - Get Lower Limit of Range or Base Range of Index

  INDEX - Convert Index Variable to Scalar

  LAST - Get Upper Limit of Range or Base Range of Index

  OR - Logical Or

  OTHERWISE - Default Guard Operator

  SUM - Sum of Expressions Over Indices

  WHEN - Guard Operator

See also

  Using Built-in functions


Complex Functions

This group contains functions operating on complex numbers.

  ABSC - Absolute value of complex number or array

  ADD - Sum of arrays

  ADDCR - Sum of complex and real numbers or arrays

  ADDRC - Sum of real and complex numbers or arrays

  ANGLEC - Angle of complex number or array

  CARTOPOL - Convert complex number or array from Cartesian to Polar form

  IMAGC - Imaginary part of complex number or array

  INVERTC - Inverted complex number or square matrix

  POLTOCAR - Convert complex number or array from Polar to Cartesian form

  PRODC - Product of complex numbers, vectors or arrays

  PRODCR - Product of complex and real numbers, vectors or arrays

  PRODRC - Product of real and complex numbers, vectors or arrays

  REALC - Real part of complex number

  TRANSPOSEC - Transposed matrix of complex numbers

See also

  A Short Guide to Using Complex Functions


A Short Guide to Using Complex Functions

In order to increase readability, it may be a good idea to define Complex as a named range with two elements. Both of the range definitions below can be used:

range	Complex = 1..2

range	Complex = (Re, Im)

The definition below define a complex number C with the real part set to 3 and the imaginary part set to 4.

range	Complex = 1..2

const	C(Complex) = [3, 4]

A constant vector V with three complex numbers is defined below:

const	V(1..3, Complex) = [[1, 4], [2, 0], [0, 1]]

A matrix M with complex numbers is defined next:

const	M(1..2, 1..2, Complex) = [[[1, 4], [0, 1]], [[3, 4], [-8, 7]]]


Conditional Functions

Conditional functions perform different tasks, based on conditions which are passed as arguments to the functions.

  IF - Arithmetic If

  PULSEIF - Conditional Pulse

  SAMPLEIF - Conditional Sample

  SHIFTCIF - Conditional Circular Shift of Vector Elements

  SHIFTLIF - Conditional Linear Shift of Vector Elements


Control Functions

Control functions are used to control a simulation run.

  PAUSEIF - Conditional Pause

  PAUSEWHILE - Continuing Pause

  STOPIF - Stop Simulation

  STOPRUNIF - Stop Current Run


Conversion Functions

Conversion functions convert a value from one type to another.

  % - Percent

  ABS - Absolute Value

  BOOL - Convert Number to Boolean

  CARTOPOL - Convert complex number or array from Cartesian to Polar form

  CEIL - Round Number Up to Nearest Integer

  DEGTOGRAD - Convert Degrees to Gradients

  DEGTORAD - Convert Degrees to Radians

  FLOOR - Round Number Down to Nearest Integer

  FRAC - Fraction of Number

  GRADTODEG - Convert Gradients to Degrees

  GRADTORAD - Convert Gradients to Radians

  INDEX - Convert Index Variable to Scalar

  INT - Integer Part of Number

  PCT - Convert Number to Percent

  POLTOCAR - Convert complex number or array from Polar to Cartesian form

  RADTODEG - Convert Radians to Degrees

  RADTOGRAD - Convert Radians to Gradients

  ROUND - Round Number to Nearest Integer

  SIGN - Sign of Number

See also

  Table of Relationship Between Some Conversion Functions


Table of Relationship Between Some Conversion Functions
Table Showing Relationship Between Some Conversion Functions

x	FLOOR(x)	ROUND(x)	CEIL(x)	INT(x)	FRAC(x)
-2.2	-3	-2	-2	-2	-0.2
-1.8	-2	-2	-1	-1	-0.8
0.2	0	0	1	0	0.2
2.6	2	3	3	2	0.6


Delay Functions

Delay functions imply a delayed influence.

  DELAYINF - N-th Order Information Delay

  DELAYMTR - N-th Order Material Delay

  DELAYPPL - Pipeline Delay

  DELAYPPLINF - Variable Time Information Pipeline Delay

  DELAYPPLINFV - Variable Time Information Pipeline Delay through Vector

  DELAYPPLMTR - Variable Time Material Pipeline Delay

  DELAYPPLMTRV - Variable Time Material Pipeline Delay through Vector

See also

  Introduction to Delays

  Average Delay Time

  Transient Response

  Five Delay Examples


Introduction to Delays

Delays occur frequently in real world systems. Time delays arise in every stage of system activity - in decisions, in transportation, in averaging data and stocks of all kinds. For instance, an order for widgets does not necessarily result in an immediate delivery of widgets. People contracting a disease may not immediately show its symptoms. Information about daily sales must accumulate before a picture of average monthly sales can be created, and accumulation takes time.

Delays are conveniently divided into two types: Delays resulting from the time necessary to process physical material, and delays resulting from time required to perceive and act upon information. These two delays are called material delays and information delays.


Five Delay Examples

  First Order Material Delay

  Third Order Material Delay

  Infinite Order Material Delay

  First Order Information Delay

  Third Order Information Delay


First Order Material Delay

Let us consider a simple epidemic model that illustrates a delay in a system. In this model, susceptible individuals get infected and go through an incubation period before they show symptoms. This is shown in the structure presented below. There is a certain time delay involved before developing symptoms.

There is a delay from the time a person becomes infected until he develops symptoms and becomes sick. The delay is determined by the (average) incubation time. The part of the model that is inside the frame of the diagram above has the structure of a first order material delay. The order is one, because there is only one level involved in the delay.

The general structure of a first order material delay is given below:

First order material delay

Equations of a First Order Material Delay

The model equations corresponding to the diagram above are:

aux	Input = "Input rate to be delayed"

aux	DelayTime = "Average delay time"

level	InTransit = "Initial" - dt*Output + dt*Input

aux	Output = InTransit/DelayTime

The initial value of InTransit, the value of Input and DelayTime may be set to different values.

Function for First Order Material Delay

Using the DELAYMTR function, this class of delays may be modeled as shown below:

Note

The definition of Output is:

aux	Output = DELAYMTR(Input, DelayTime, 1, "Initial")

If no initial value is given for DELAYMTR, Input will be used by default. This means that Input is both a delayed parameter and a non-delayed start-up parameter to Output. We therefore need to add a normal link arrow from Input to Output as well. This link will become an initialization link, as shown in the figure above.


Note	The two double lines crossing the arrow linking Input to Output indicate that Output is a delayed value of Input. You must use the delayed link arrow when defining inputs to the DELAYMTR function in the diagram editor. The level symbol inside the Output variable indicates that an internal level is implicitly defined by the DELAYMTR function.


Third Order Material Delay

If we assume that the time to show symptoms is three months, we may divide the incubating individuals into those in their first month, Stage_1, those in their second month, Stage_2, and those in their third month, Stage_3.

The portion of the above diagram that lies inside the frame is a third order material delay. The order of three comes from the fact that the flow goes through three levels. The general structure of a third order material delay is presented next:

Third order material delay

Equations of a Third Order Material Delay

aux	Input = "Input rate to be delayed"

aux	DelayTime = "Delay time"

level	InTransit_1 = "Init" + dt*Input - dt*Progress_1

level	InTransit_2 = "Init" + dt*Progress_1 - dt*Progress_2

level	InTransit_3 = "Init" + dt*Progress_2 - dt*Output

aux	Progress_1 = InTransit_1/(DelayTime/3)

aux	Progress_2 = InTransit_2/(DelayTime/3)

aux	Output = InTransit_3/(DelayTime/3)

The initial values of the transit levels, and the value of Input and DelayTime, are parameters to the delay structure.

Function for Third Order Material Delay

Just as in the case of a first order material delay, the third order material delay may be modeled using the DELAYMTR function.

See: Note

The definition of Output is:

aux	Output = DELAYMTR(Input, DelayTime, 3, "Init")


Infinite Order Material Delay

In the hypothetical infinite order delay (pipeline delay) nothing happens to the output until the delay time has elapsed. At this time the input variable is reproduced exactly. A pipeline delay may be looked upon as a "moving sidewalk" or conveyor belt, where items are put on the conveyor at one end, and expelled at the other end after a fixed time.

This delay may be modeled using a number of levels that equal the number of time steps in the delay time, i.e., DelayTime/TIMESTEP. Each time step, material is moved from one level to the next, until it reaches the final level, where it is output. In Powersim this may be modeled using a vector level, and applying the SHIFTLIF function at each time step to shift elements from one position to the next.

Pipeline delay

Equations of an Infinite Order Material Delay

If we assume there are ten steps in a delay time, the equations become:

aux	Input = "Input rate to be delayed"

init	InTransit = "Initial contents of delay"

dim	InTransit = 1..10

flow	InTransit(i) = dt*(Input | i=1;0) - dt*(Output | i=LAST(i);0)

aux	Output = SHIFTLIF(TRUE, InTransit)

Function for Infinite Order Material Delay

The function DELAYPPL may be used to express this kind of delay directly.

The definition of Output is:

aux	Output = DELAYPPL(Input, DelayTime, 0)

As with the DELAYMTR function, Input must be connected to Output using an additional non-delayed link if Input is used to initialize the delay. This is the default behavior of the DELAYPPL function if the optional last parameter is omitted.

See: Note


First Order Information Delay

Just as material takes time to flow from one point in a system to another, so does information. For instance, economists do not know the gross domestic product for today. It also takes time for information about the availability of jobs to reach people who are seeking them. Peoples' perceptions are bound to lag behind a true picture. Such delays are frequently an unavoidable part of a system structure, and should therefore be captured in our models.

Let us consider an example where production rate decisions are based upon sales information. However, when organizations make decisions, they tend to rely more heavily on recent information than on older data. The next figure shows the structure of a so-called exponential averaging of sales information, with a particular averaging time.

The average sales may also be used as a measure for expected sales.

The information delay is sometimes also referred to as a smoothing of an input. The next diagram displays the general structure of the first order information delay:

First order information delay

The output may be thought of as the perceived value of the input.

Equations of a First Order Information Delay

level	Output = "Init" + dt*ChangeInInput

aux	ChangeInInput = (Input-Output)/DelayTime

aux	DelayTime = "Delay time"

aux	Input = "Input to be delayed"

Function for First Order Information Delay

The effect of this delay structure may be achieved using the DELAYINF function.

The definition of Output is:

aux	Output = DELAYINF(Input, DelayTime, 1, "Init")

See: Note


Third Order Information Delay

For another example, let's examine a production/distribution system, where a stream of information flows in the form of orders moving from consumers to a supplier. The structure of the system is shown below. The information being sent from market to the supplier is adjusted by every sector, with a particular averaging time.

The diagram has the structure of a third order information delay. The general structure of a third order information delay is given below:

Equations of a Third Order Information Delay

aux	DelayTime = "Delay time"

aux	Input = "Input rate to be delayed"

aux	ChangeInInput_1 = (Input-Output_1)/(DelayTime/3)

aux	ChangeInInput_2 = (Output_1-Output_2)/(DelayTime/3)

aux	ChangeInInput_3 = (Output_2-Output)/(DelayTime/3)

level	Output_1 = "Init" +dt*ChangeInInput_1

level	Output_2 = "Init" +dt*ChangeInInput_2

level	Output = "Init" +dt*ChangeInInput_3

Function for Third Order Information Delay

The effect of the third order information delay may be achieved through use of the DELAYINF function, like this:

aux	Output = DELAYINF(Input, DelayTime, 3, "Init")

See: Note


Average Delay Time

The Five Delay Examples all refer to an average delay time. This is an important characteristics of a delay, and determines the steady state effect of the delay. Under these unvarying circumstances, the inflow and outflow must be equal. In a steady state the inflow multiplied by the average delay time gives the quantity in transit in the delay.


Transient Response

The transient response of a delay tells how the behavior of the outflow is related to the behavior of the inflow. Different kinds of delays can have very different transient responses to changes in input, even if the average delay time is the same. When building models, the selection of transient delay response is a crucial determinant. If the transient response is grossly incorrect, it may have an important effect on the qualitative behavior of the model.

Various computational processes might be used to create a delay in a flow channel within a mathematical model. We consider here a delay function of only a single class - exponential delays. Exponential delays are simple in form and have adequate scope to fit our usual degree of knowledge about the actual systems we model. The transient response of an exponential delay changes as its order (i.e., its number of levels) is increased.

The graph below displays the transient response to a step input exhibited by delays of various orders. More specifically, the graph lists the response of material delays of increasing order, all having a delay time of 10.

Below the behavior of the same delays are displayed in response to a pulse input.

The transient response of information delays and material delays of the same order are the same, provided that the delay time is also the same.

Material delays refer to the flow of specific physical items, and should therefore not destroy or create any units in the flow that is traveling through it. This means that, in a material delay with a constant inflow, the outflow will exhibit a transient change (a change that lasts for a short time) if the delay time is changed. This is because it is necessary for a delay's output to be different from its input for a time long enough to allow its internal level to adjust. For example, if the delay time is reduced, a delay's output will increase for a while, bringing the amount of delayed material gradually down to the new steady state condition.

An information delay, on the other hand, behaves differently. The delayed output of a constant information input is not affected by a change in delay time. In the steady state (when there is a constant input) the averaged value of an information input will have the same value as the input. Therefore the value of DelayTime can be changed without affecting the value of the averaged output. (Output is changed by the flow: (Input-Output)/DelayTime, which will be zero in the steady state, independent of the value of DelayTime. See equations in First Order Information Delay.)


Financial Functions

Financial functions cover computations of present value, future value, and periodic payments.

  FV - Future Value

  NPV - Net Present Value

  PMT - Periodic Payment

  PV - Present Value

See also

  Introduction to Financial Functions

  The Simple Case - Working with One Period

  Extending to Several Periods

  Net Present Value

  Using the Finance demo model


Introduction to Financial Functions

Powersim uses the following equation to solve for one financial argument in terms of the others, when the payment is constant (annuity payment):

If the interest rate r = 0, the equation becomes:

Where:

PV	- Present value

PMT	- Payment (cash flow)

r	- Interest rate (for example, % per annum)

n	- Number of periods (for example, years)

FV	- Future value

For PV, PMT, and FV the following convention is used: cash received is depicted by a positive number and cash paid out is depicted by a negative number.

The formulas (functions) assume that the first payment takes place at the end of the first period.

Keep in mind that interest rates are given relative to a period of given length. For example, if one period is a year, the interest rate should be specified as interest rate per year.


The Simple Case - Working with One Period

Present value is a discounted value of future cash flows. A dollar today is worth more than a dollar tomorrow, because the dollar today can be invested to start earning interest immediately. This is the first basic principle of finance.

Present and Future Value

Thus, a present value of a delayed payoff may be found by multiplying the payoff by a discount factor which is less than 1. (If the discount factor is more than one, a dollar today would be less than a dollar tomorrow.)

If FV1 denotes the expected payoff one period into the future, the present value may be found like this:

where D is the discount factor. If you are confused about the negative sign in the formula above, please recall the sign conventions used in the financial formulas. If, for example, the future payoff (FV1) is to be positive, an amount of cash has to be paid out now (i.e. the present value (PV) will be negative).

If the interest rate is r, the discount factor (over one period) is defined like this:

Rewriting to make the right hand side zero, yields the following equation:

Suppose your house burns down, leaving you with a vacant lot worth $50,000 and a check for $200,000 from the fire insurance company. You should consider rebuilding, but your real estate adviser suggests putting up an office building instead. The construction cost would be $300,000, and there would also be the cost of the land, which might otherwise be sold for $50,000. On the other hand, your adviser foresees a shortage of office space and predicts that a year from now the new building will fetch $400,000 if you sold it. Thus you would be investing $350,000 now with the expectation of realizing $400,000 one year hence. (In the text, the sign of a cash flow is given by the context. For example, the term "investing $350,000" suggests that -350,000 will be used when applied in a formula.) You should go ahead and do this if the present value of the expected $400,000 payoff compares favorably with the investment of $350,000. Therefore, you need to ask yourself, what is the value today of $400,000 one year from now?

Let us consider the real estate investment, assuming for the moment that the $400,000 payoff is the sure thing. The office building is not the only way to obtain $400,000 a year from now. You could invest in government securities maturing in a year. Suppose these securities yield 7% interest. How much would you have to invest in order to receive $400,000 at the end of the year? According to our formula, the investment is calculated as follows:

The two alternative investments are compared in the table below.

Two alternatives	Investment	FV1
Invest in building	$350,000	$400,000
Invest in securities	$373,832	$400,000
Alternative investments

Since investing in the building will cost you less than investing in securities, you should follow your real estate adviser's advice.

The present value of the security investment case is easily obtained using the PV function like this:

PV(7%, 1, 0, 400000) = -373832

Let's assume that as soon as you have committed the land and begun construction on the building, you decide to sell your project. How much could you sell it for? That's another easy question. Since the property produces $400,000, investors would be willing to pay $373,832 for it. That's what it would cost them to get a $400,000 payoff from investing in government securities.

The present value is the only feasible price that satisfies both buyer and seller. Therefore, the present value of the property is also its market price.


Extending to Several Periods

There are shortcuts that make it very easy to calculate the present value of an asset that pays off in several periods. Let us look at some examples.

Perpetuities

Securities that have been issued by the government are called perpetuities. These are bonds that the government is under no obligation to repay but that offer a fixed income for each year to perpetuity.

The rate of return on a perpetuity is equal to the promised annual payment divided by the present value.

Obviously we can twist this around and find the present value of a perpetuity given the discount rate r and the cash payment PMT.

Suppose some worthy person wishes to endow a chair in finance at a business school. If the rate of interest is 10% p.a. and the aim is to provide $100,000 a year in perpetuity, the amount that must be set aside today is calculated as follows:

In this example we want the absolute value of PV to be the same as FV, which is verified using the equation:

PV(10%, 1, 100000, 1000000) = -1000000

Annuities

An annuity is an asset that pays a fixed sum each year for a specified number of years. The equal-payment house mortgage or installment credit agreement are common examples of annuities.

The equations below illustrate a simple trick for valuing annuities. First we present a perpetuity that produces a cash flow of PMT each period beginning in period one. It has a present value of

The next perpetuity produces a cash flow of PMT in each period, beginning in period n+1. It will have a present value of :

Both perpetuities provide a cash flow from period n+1 onwards. The only difference is that the first one also provides a cash flow in each of the periods 1 through n. In other words, the difference between the two perpetuities is an annuity of PMT for n periods. The present value of the annuity is therefore the difference between the values of the two perpetuities.

The expression in the brackets is the annuity factor, which is the present value at discount rate r of an annuity of 1 currency unit (for example, $1) paid at the end of each period.

Rewritten, with the right hand side set to zero, the equation is:

Suppose that our benefactors begin to vacillate and wonder what it would cost to endow the chair by providing $100,000 a year for only 20 years. The answer is calculated by the formula:

The same result is obtained from the PV function like this:

PV(10%, 20, 100000, 0) = -851356.4

You received an automobile loan of $10,000 at an effective yearly rate of 10%. You must repay the loan in 5 yearly payments made at the end of each year. What is your annuity payment?

The same result is returned by the following call to the PMT function:

PMT(10%, 5, 10000, 0) = -2637.975

The following model illustrates the process of paying down the above loan:

level	Loan = 10000 + dt*Interest - dt*Annuity

aux	Annuity = -PMT(10%, 5, INIT(Loan), 0)

aux	Interest = Loan*10%

aux	Instalment = Annuity-Interest

The table below shows the annuity payment, interest rate and installment from year to year:

Year	Loan	Annuity	Interest	Installment
1	10,000.000	2,637.975	1,000.000	1,637.975
2	8,362.025	2,637.975	836.203	1,801.772
3	6,560.253	2,637.975	656.025	1,981.950
4	4,578.303	2,637.975	457.830	2,180.145
5	2,398.158	2,637.975	239.820	2,398.155
Annuity, Interest, and Installment from year to year

Future Value

Future value (FV) is defined in terms of the present value (PV), the interest rate (r), and the number of periods (n) like this:

We sometimes need to calculate how much a series of annual payments earning a fixed annual interest would amass to by the end of n periods. In this case it is easiest to calculate the present value and then multiply by (1+r)n to find the future value.

Thus, suppose our benefactors wish to know how much wealth $100,000 will produce if it were invested each year, instead of being given to those no-good academics. The answer would be:

The same result is found by the FV function using these parameters:

FV(10%, 20, 0, -851356.4) = 5727500

Instead of using the present value, the annual payments may be used to obtain the same result:

FV(10%, 20, -100000, 0) = 5727500


Net Present Value

Periodic Payment and Constant Interest Rate

When the interest rate is constant, the net present value (NPV) used to evaluate the desirability of investments can be defined as follows:

In the above formulas, PMTt is the payment at the end of period t, PMT0 is the initial investment outlay (a negative value), and r is the interest rate.

Periodic Payment and Variable Interest Rate

Let's take a look at the net present value when both the interest rate, and the payment, vary:

PMTt is the payment at the end of period t, PMT0 is the initial investment outlay (a negative value), and rt-1 is the interest rate used during the period from t-1 to t.

The above formula is implemented by the NPV function of Powersim. As an example of the NPV function, consider the following project: Initially there is an investment outlay of $1,000, which yields an income of $200 the next ten years. The first three years the interest rate is 7%, and for the remaining years it is 9%. The net present value for this project can be calculated using the following model:

The corresponding equations are:

aux	NetPresentValue = NPV(Payment,InterestRate)

aux	Payment = IF(TIMEIS(STARTTIME),-1000,200)

aux	InterestRate = IF(TIME < STARTTIME+3, 7%, 9%)

The time table below shows the development of the net present value as well as the payment and the interest rate over ten years:

Since the net present value of the ten year project is positive, the project should be accepted. An imaginary five year project with the same cash flows, however, would be rejected because of a negative net present value.


Graph Functions

Graph functions are functions whose results are tabulated for given input values.

  GRAPH - Linear Graph with Horizontal Asymptotes

  GRAPHCURVE - Polynomial Graph with Linear Asymptotes

  GRAPHLINAS - Linear Graph with Linear Asymptotes

  GRAPHSTEP - Horizontal Graph with Horizontal Asymptotes

See also

  Introduction to Graph Functions

  Interpolation

  Extrapolation


Introduction to Graph Functions

Graph functions are useful when we do not know the exact mathematical formula of a function, or if we want to use statistical or empirical data to express a relationship between two variables.

Say that we have empirical data showing the relative growth rate of salmon weighing 1 kg at different temperatures. (The numbers are provided by Akvaforsk, a Norwegian research institute.)

Temp	Daily growth rate	Data displayed graphically
4ºC 6ºC 8ºC 10ºC 12ºC 14ºC 16ºC	3.3% 3.7% 4.2% 5.5% 6.0% 7.0% 8.0%
The following equation will express the same relationship between temperature and relative growth rate in percent:

Growth = GRAPH(Temp, 4.00,2.00,[3.3,3.7,4.2,5.5,6,7,8])

Note	Graph functions can be edited graphically using the Edit Graph/Vector editor of the Define Variable dialog box. Data may be input from spread sheets or other applications using the clipboard (Copy/Paste).

The different kinds of graph functions are characterized by the way they compute values that lie between the fix points, or outside the boundaries of the given range of fix-points. These two aspects are technically labeled interpolation (between points) and extrapolation (beyond points). Below you'll find a brief explanation of these terms.


Interpolation

Powersim defines three ways for determining values that lie between the fix points of a graph; namely horizontal, linear, and polynomial interpolation. In the first case, the function will use the value of the fix point to the left of the given input. In the linear case, an imaginary line is drawn between the two fix points enclosing the input value, and the value of the function is found where the input value crosses this line. In the polynomial case, a third order polynomial is constructed from all the fix points, and solved for the given input value. The figure below illustrates horizontal, linear, and polynomial interpolation (crosses represent fix points).

Horizontal	Linear	Polynomial
Horizontal, linear, and polynomial interpolation


Extrapolation

When an input value of a graph function lies below the first fix point or above the last, the output value is computed on the basis of either horizontal or linear extrapolation. The lines extending a graph beyond the last fix point at either end are called asymptotes. In the case of horizontal asymptotes, the value at the first and last fix point is continued along a horizontal line at each end of the graph. The other case is the linear one, where the asymptotes are constructed as lines through the two outermost fix points at each end. The figure below illustrates these two cases:

Horizontal	Linear
Graph with horizontal and linear asymptotes


History Functions

History functions are functions where past values of arguments are used in computing the value of the function.

  DELAYINF - N-th Order Information Delay

  DELAYMTR - N-th Order Material Delay

  DELAYPPL - Pipeline Delay

  DELAYPPLINF - Variable Time Information Pipeline Delay

  DELAYPPLINFV - Variable Time Information Pipeline Delay through Vector>

  DELAYPPLMTR - Variable Time Material Pipeline Delay

  DELAYPPLMTRV - Variable Time Material Pipeline Delay through Vector

  DERIVN - N-th Order Time Derivative

  EULER - Sample at Start of Time Step

  FORECAST - Value Forecasting

  HIVAL - Highest Simulated Value

  INIT - Initial Value

  INTEGRATE - Integration

  LOVAL - Lowest Simulated Value

  NPV - Net Present Value

  QUEUE - Queue with multiple clients and servers

  SAMPLE - Periodic Sample

  SAMPLEIF - Conditional Sample

  TREND - Trend Extrapolation

See also

  Queue with Multiple Clients And Servers


Queue with Multiple Clients And Servers

Demo

QUEUE2.SIM

In QUEUE an example is given of a queue with one client and one server. Below is an example with several clients asking for service by a number of servers.

The QUEUE function of Powersim provides a mechanism for modeling a first-in-first-out (FIFO) queue. As an example, we'll model people (clients) entering a bank to see one of the bank tellers (servers). A client entering the bank will have to stand in line if all tellers are busy. When a teller becomes available, the client in the front of the line gets served.

First of all, we define the number of clients and the number of servers as two named ranges, rClients and rServers. We use the Edit Define Range dialog box to enter the ranges. Let us define one flow of clients and two servers. The equations view of the range definitions becomes:

range	rClients = 1..1

range	rServers = 1..2

We now make the following diagram.

The rate EnterBank is defined as the service time requested by the client currently entering the bank. (In this example, the client rate has only one element. EnterBank could therefore be defined as a scalar, without the need for the range rClients.)

The rate of clients entering a bank can be said to be distributed according to a Poisson distribution with a given mean. Let us define the time unit of the simulation to be minutes. (Use the Edit Define Unit dialog box to define the Minutes unit; and the Simulate Simulation Setup to set Time Unit equal to Minutes.)

If we assume that one person (client) enters the bank every other time step, this can be expressed as:

aux	EnterBank = POISSON(1/2)

If we want to make the simulation independent of simulation step, we should alter the definition, like this:

aux	EnterBank = POISSON(1/2 * TIMESTEP) / TIMESTEP

This means that one person enters the bank every other minute, on the average. The final division by TIMESTEP is done in order to treat EnterBank as a pulse flow (remember that flows are implicitly multiplied by dt ).

Clients may need different amounts of service time from the tellers. We may assume that service time is distributed according to the Normal distribution, for example with a mean of four minutes and a deviation of one. This can be expressed as MAX(0, NORMAL(4, 1)). The MAX function is used to avoid negative service times.

If we multiply the above service time into the definition of EnterBank, we get a variable that generates a sequence of service times:

aux	EnterBank = POISSON(1/2 * TIMESTEP) / TIMESTEP * MAX(0, NORMAL(4, 1))

The rate ServeClient defines how each server is serving a client. Each time unit the server performs one unit of service, as expressed below.

aux	ServeClient = MIN(WorkLeftThisClient/TIMESTEP + GoToTeller, 1)

Note that the server will not perform more service than is necessary to complete the current job. Since the flow out of WorkLeftThisClient is equal to ServeClient * dt we use the expression WorkLeftThisClient/TIMESTEP + GoToTeller as an upper limit of the ServeClient rate.

A teller (server) is ready if it has nothing to do or if it will complete its current task within the current time step. This is expressed by the TellerReady variable:

aux	TellerReady = WorkLeftThisClient <= TIMESTEP

Below you'll find the complete definition of our model.

range	rClients = 1..1

range	rServers = 1..2

dim	EnterBank = (rClients)

aux	EnterBank = POISSON(0.5 / TIMESTEP) * TIMESTEP * MAX(0, NORMAL(4, 1))

dim	GoToTeller = (rServers)

aux	GoToTeller = QUEUE(EnterBank, 100, 0, TellerReady, QLen)

const	QLen = 0

dim	ServeClient = (rServers)

aux	ServeClient = MIN(WorkLeftThisClient/TIMESTEP + GoToTeller, 1)

init	SumWorkClientsInLine = 0

flow	SumWorkClientsInLine = -dt*ARRSUM(GoToTeller)

+dt*ARRSUM(EnterBank)

dim	TellerReady = (rServers)

aux	TellerReady = WorkLeftThisClient <= TIMESTEP

dim	WorkLeftThisClient = (rServers)

init	WorkLeftThisClient = 0

flow	WorkLeftThisClient = -dt*ServeClient

+dt*GoToTeller

The time graph below displays the number of people (clients) in line during a simulation over 20 minutes. A simulation time step of 0.125 is used.


Logical Functions

Logical functions is a group of functions returning a logical value representing True or False.

  < - Less Than

  <= - Less Than or Equal To

  <> - Not Equal To

  = - Equal To

  > - Greater Than

  >= - Greater Than or Equal To

  AND - Conjunction, Logical And

  BOOL - Convert Number to Boolean

  FALSE - Logical False

  NOT - Negation

  OR - Logical Or

  TRUE - Logical True

  XOR - Exclusive Logical Or


Mathematical Functions

Mathematical functions is a function group containing all kinds of mathematical calculations.

  ^ - Number Raised to a Power

! - Factorial

  % - Percent

  * - Multiplication

  + - Addition

  - Subtraction

  / - Division

  ABS - Absolute Value

  ADD - Sum of arrays

  ARRPROD - Product of Array Elements

  ARRSUM - Sum of Array Elements

  DERIVN - N-th Order Time Derivative

  DIVZ0 - Division with Zero Result for Zero Denominator

  DIVZ1 - Division with Unit Result for Zero Denominator

  DIVZX - Division with Explicit Result for Zero Denominator

  EXP - Exponential of Number

  HYPOT - Hypotenuse

  INFINITY - Infinitely Large Positive Number

  INTEGRATE - Integration

  INVERT - Inverted square matrix

  LN - Natural Logarithm

  LOG - Base N Logarithm

  MATRIXPROD - Matrix Product

  MOD - Remainder of Division

  NAN - Not a Number

  PCT - Convert Number to Percent

  POLY - Polynomial

  SIGN - Sign of Number

  SPROD - Scalar Vector Product

  SQRT - Square Root

  TRANSPOSE - Transpose Matrix

  VECTLEN - Vector Length

  VECTPROD3D - 3D Vector Cross Product


Miscellaneous Functions

Miscellaneous functions are functions that do not fit well into other groups.

  ASSIGN - Set Value of Variable

  GETPLAYERS - Get number of players

  GETSIMPLAYERS - Get number simulated of players

  GETTOTPLAYERS - Get total number of players

  LIMIT - Limit Variable to Given Range

  PLAYERNUMBER - Get player number

  RUN - Run Number

  RUNCOUNT - Number of Runs

  SELECTDECISION - Select decision value

  SOUND - Output Sound

  STRATEGICMODE - Test if game is in strategic mode


Random Functions

Random functions depend on a random number generator.

  EXPRND - Exponential Distribution

  NORMAL - Normal Distribution

  POISSON - Poisson Distribution

  RANDOM - Uniform Distribution


Statistical Functions

Statistical functions perform computations on a set of data provided as arguments to the functions.

  ARRAVG - Average of Array Elements

  ARRMAX - Maximum of Array Elements

  ARRMIN - Minimum of Array Elements

  ARRSTDDEV - Standard Deviation of Array Elements

  AVG - Average

  MAX - Maximum

  MIN - Minimum

  STDDEV - Standard Deviation


Time Related Functions

Time-related functions utilize parameters or return values that are expressed in the time unit of the simulation.

Functions that return time values

  STARTTIME - Start Time of Simulation

  STOPTIME - Stop Time of Simulation

  TIME - Current Time of Simulation

  TIMESTEP - Time Step of Simulation

Functions that may be used to test for a given time

  ATSTART - Test for Beginning of Simulation

  TIMECYCLE - Test for Cyclic Time or Time Interval

  TIMEIS - Test for Given Time or Time Interval

Functions that use time as an implicit parameter

  COSWAVE - Periodic Cosine Wave

  PULSE - Periodic Pulse

  RAMP - Linear Function

  SAMPLE - Periodic Sample

  SINWAVE - Periodic Sine Wave

  STEP - Step Function

Real-time functions

  SECONDSTHISRUN - Seconds since start of current run

  SECONDSTHISSTEP - Seconds used simulating current time step


Trigonometric Functions

Trigonometric functions are functions for performing trigonometric operations.

  ARCCOS - Arcus Cosine

  ARCSIN - Arcus Sine

  ARCTAN - Arcus Tangent

  COS - Cosine

  COSH - Hyperbolic Cosine

  COSWAVE - Periodic Cosine Wave

  DEGTOGRAD - Convert Degrees to Gradients

  DEGTORAD - Convert Degrees to Radians

  GRADTODEG - Convert Gradients to Degrees

  GRADTORAD - Convert Gradients to Radians

  PI - Trigonometric Constant Pi

  SIN - Sine

  SINH - Hyperbolic Sine

  SINWAVE - Periodic Sine Wave

  TAN - Tangent

  TANH - Hyperbolic Tangent


Function Reference

See

  Function Description

  Function Description Guidelines

  Input Parameter Types

  Unary Operators

  Binary Operators

  Parameters and Return Values

  Parameter Types

  Return Values

  Input and Output Parameters

  Start-up Parameters

  Computational Parameters

  Optional Parameters

  Greedy Functions

  Delayed Parameters

  Invalid Function Parameters


Function Description

The list of functions contains unary and binary operators and normal functions with zero or more parameters.

See

  Function Description Guidelines

  Input Parameter Types

  Unary Operators

  Binary Operators


Function Description Guidelines

Each function is described according to the following guidelines:

Item	Description
Syntax	Description of function and parameters
In	Definition of each input parameter
Out	Definition of each output parameter
Result	Result of function
Note	Special considerations, side effects, etc.
Example	Examples of the use of the function
Diagram	Diagram equivalent of the function
Equations	Equations that may be used to implement the function
Demo	Demo models utilizing the function
Group(s)	Which function group(s) it belongs to
Related functions	List of related functions
Syntax

In the Syntax part, the following notational conventions are used:

Name(...)	Array Name with unspecified dimensions
Name(N)	Vector Name with N elements
Name(M, N)	Array Name with N rows and M columns
[, Name=V]	Optional parameter Name with default value V
X1, ...XN	Greedy function with N arguments
Logical values

For logical values, True and False are used to denote values that are non-zero and zero, respectively.

Note	Parameters may be specified as expressions, unless used as output parameters, which must be either levels or constants.


Input Parameter Types (Function Description)
Input Parameter Types

In a function description, input parameters may be specified as one of the following types:

Computational parameter

Delayed parameter

Optional parameter

Start-up parameter


Unary Operators

The following list displays all unary operators, along with information about their position relative to the operand (before or after).

Operator	Position	Purpose
!	after	Factorial
%	after	Percent
+	before	Plus
-	before	Minus
NOT	before	Negation
The unary operators have higher precedence than the binary operators. The operators which are put after the operand have the highest precedence.


Binary Operators

Binary operators take two operands, one before and one after the operator. When mixed in an expression, the ties between operator and operand (argument) may become ambiguous, as in the following example:

10 + 3 * 2

Is the value of the expression 26 or is it 16? The answer to this depends on the relative precedence of addition and multiplication, i.e., which operator is the "strongest" in fighting for operands (arguments).

As a convention, multiplication is carried out before additions, and hence POWERSIM defines multiplication to have higher precedence than addition. This means that the above expression may be rewritten as:

10 + (3 * 2)

which gives 16 as a result.

Parentheses can always be used to make the order of evaluation clear, or to change the order of evaluation, for example, like this: (10 + 3) * 2.

For some operators it is important to know from what end to start when calculating an expression involving the same operator several times at the same level (i.e., without parentheses). For operators like add and multiply, the order of evaluation does not matter. This is, however, not the case for the division, subtraction and exponential operator. The expressions below illustrate this:

1 / (2 / 3) = 3 / 2

(1 / 2) / 3 = 1 / 6

(1 - 2) - 3 = -4

1 - (2 - 3) = 2

4 ^ (3 ^ 2) = 262144

(4 ^ 3) ^ 2 = 4096

The order to be used when no parentheses are present is determined by the operator's associativity; which may be either left or right. All operators except the exponential operator (^) are left associative, i.e., they group from left to right.

The Binary Operators Table lists all binary operators, along with precedence level and associativity.


Binary Operators Table

Operator	Precedence	Associativity	Purpose
^	7	right	Raised to a power
*	6	left	Multiplication
/	6	left	Division
MOD	6	left	Remainder of division
+	5	left	Plus
-	5	left	Minus
<	4	left	Less than
<=	4	left	Less than or equal to
>	4	left	Greater than
>=	4	left	Greater than or equal to
=	3	left	Equal to
<>	3	left	Not equal to
AND	2	left	Logical and
XOR	1	left	Logical exclusive or
OR - Logical Or	1	left	Logical or


Parameters and Return Values

The arguments of functions are called parameters (or operands in the case of operators like + or *).

See

  Parameter Types

  Return Values

  Input and Output Parameters

  Start-up Parameters

  Computational Parameters

  Optional Parameters

  Greedy Functions

  Delayed Parameters

  Invalid Function Parameters


Parameter Types

Parameters may be either scalars (numbers) or arrays, depending on the function in question.


Return Values

Functions normally return scalars values, except for a few array functions which return arrays. The return value of a scalar function may be used in an expression in any place where a literal scalar may be used. Correspondingly, the return value of an array function may be used in any place where a literal array may be used.


Input and Output Parameters

Normally parameters may be specified as expressions involving functions, operators, parentheses, etc. However, certain parameters are defined as output parameters, i.e., parameters that are modified by the function. Such parameters must be specified as either level or constant variables.

Note	The value set by a function to an output parameter is assigned to the parameter variable at the end of the simulation step.


Start-up Parameters

Some functions, for example INIT, take parameters that are evaluated only during the initialization of the simulation. The function result will depend on the initial values of such parameters for the rest of the simulation, disregarding any changes to the parameters after the initial state.

Input links that are used as start-up parameters only are regarded as initialization links. I.e., they will be displayed as dotted lines once Powersim has detected that they are start-up parameters (see figure below).

Note	Start-up parameters are always computational.


Computational Parameters

Parameters are normally evaluated before a function is called. There are, however, some functions that evaluate parameters conditionally depending on the value of other parameters, current time, etc. IF is the most important example of a function taking computational parameters. This function takes three parameters, where the first one is a condition used to choose one of the two remaining parameters as the result of the function, for example, like this:

IF(Condition, ValueIfTrue, ValueIfFalse)

This function is evaluated like this:

1	The value of Condition is evaluated and passed along with the ValueIfTrue and ValueIfFalse expressions to the IF-function.

2	IF tests the value of Condition, and selects one of the expressions ValueIfTrue or ValueIfFalse. The first one is selected if Condition is not equal to 0; the last one otherwise.

3	At this point IF evaluates the selected expression, and uses the value of that expression as the value of the function.


Optional Parameters

Several functions take optional parameters, i.e., parameters that may be left out when the function is used. An optional parameter has a default value that will be used by the function if the parameter is not specified. Optional parameters must be left out from right to left in the parameter list, i.e., it is not possible to omit one optional parameter while specifying the next one.

As an example, the function DELAYINF takes the parameters Input, DelayTime, Order, and Initial. Order and Initial are optional. The function may therefore be called in the following three ways:

DELAYINF(Input, DelayTime, Order, Initial)

DELAYINF(Input, DelayTime, Order)

DELAYINF(Input, DelayTime)

It is, however, not possible to leave out Order, while keeping Initial.


Greedy Functions

Some functions take a varying number of parameters. Examples are MIN and MAX, which take from 1 to 255 parameters. It is, for example, possible to write all of the following expressions (given proper definitions of A, B, and S):

MAX(1,3,5,2,3,1)

MAX(A, B)

MAX(3, A, 2, B, S(1))


Delayed Parameters

The first parameter of a delay function is a delayed parameter. This parameter is used as an inflow to an internal level of the function. This means that the value of the parameter will not influence the function result directly, but indirectly through the internal level. As a consequence, delayed parameters may take part in a circular definition in a model, just as if the function was implemented as a structure of levels and rates.

As an example, the diagram above displays the structure of a first-order information delay.

In this structure it would be possible to add a link arrow from the level DiaDelayINF to the auxiliary Input, even if this would result in a circular definition. This is possible because a level (DiaDelayINF) is part of the cycle.

The corresponding diagram using the DELAYINF function is displayed above.

Here it would also be possible to make a link from FunDelayINF to Input, since one of the links in the circle that would be created is a delayed link.

This feature is useful in many cases, as delay-functions often take part in circular relationships. The explicit use of delay parameters also makes the diagram easier to understand, as delayed information is explicitly depicted in the diagram as a double line crossing the link arrow. Note also that the function indicator displays an internal level symbol inside the FunDelayINF variable.

Note	If a delay function is initialized by an input parameter, an initialization link must be provided in addition to the delayed link (see figure below). This is because the initialization of the function uses the initialization parameter directly (non-delayed). If no initialization parameter is specified, the initial value is, by default, computed on the basis of the Input parameter. This change corresponds exactly to the modification that must be done to the diagram variant of the same model (by making an initialization link from Input to DiaDelayINF).


Invalid Function Parameters

During simulation, a function may receive parameters for which its result is undefined, or the result may be out of its numerical range (overflow). Errors like this do not stop the simulation, but result in the special abnormal numbers +infinity, -infinity, or not-a-number. In reports these values are displayed as +?, -?, and =?, respectively.

As an example, the expression 10/0 will produce the output +? when displayed in a report. Abnormal numbers will be treated individually by each function if they are passed as arguments to the function.


Alphabetical List of Functions

-Special Characters-

- - Subtraction

- - Unary Minus

! - Factorial

% - Percent

* - Multiplication

+ - Addition

+ - Unary plus

/ - Division

; - Constraint operator

< - Less Than

<= - Less Than or Equal To

<> - Not Equal To

= - Equal To

> - Greater Than

>= - Greater Than or Equal To

^ - Number Raised to a Power

| - Guard Operator

-A-

ABS - Absolute Value

ABSC - Absolute value of complex number or array

ADD - Sum of arrays

ADDCR - Sum of complex and real numbers or arrays

ADDRC - Sum of real and complex numbers or arrays

AND - Conjunction, Logical And

ANGLEC - Angle of complex number or array

ARCCOS - Arcus Cosine

ARCSIN - Arcus Sine

ARCTAN - Arcus Tangent

ARRAVG - Average of Array Elements

ARRMAX - Maximum of Array Elements

ARRMIN - Minimum of Array Elements

ARRPROD - Product of Array Elements

ARRSTDDEV - Standard Deviation of Array Elements

ARRSUM - Sum of Array Elements

ASSIGN - Set Value of Variable

ATSTART - Test for Beginning of Simulation

AVG - Average

-B-

BOOL - Convert Number to Boolean

BUT - Constraint operator

-C-

CARTOPOL - Convert complex number or array from Cartesian to Polar form

CEIL - Round Number Up to Nearest Integer

COS - Cosine

COSH - Hyperbolic Cosine

COSWAVE - Periodic Cosine Wave

COUNT - Get Number of Elements of Range or Base Range of Index

-D-

DEFAULT - Default Guard of Constrained Expression

DEGTOGRAD - Convert Degrees to Gradients

DEGTORAD - Convert Degrees to Radians

DELAYINF - N-th Order Information Delay

DELAYMTR - N-th Order Material Delay

DELAYPPL - Pipeline Delay

DELAYPPLINF - Variable Time Information Pipeline Delay

DELAYPPLINFV - Variable Time Information Pipeline Delay through Vector

DELAYPPLMTR - Variable Time Material Pipeline Delay

DELAYPPLMTRV - Variable Time Material Pipeline Delay through Vector

DERIVN - N-th Order Time Derivative

DIVZ0 - Division with Zero Result for Zero Denominator

DIVZ1 - Division with Unit Result for Zero Denominator

DIVZX - Division with Explicit Result for Zero Denominator

-E-

ELEMCOUNT - Number of Elements in an Array

EULER - Sample at Start of Time Step

EXP - Exponential of Number

EXPRND - Exponential Distribution

-F-

FALSE - Logical False

FIRST - Get Lower Limit of Range or Base Range of Index

FLOOR - Round Number Down to Nearest Integer

FORECAST - Value Forecasting

FRAC - Fraction of Number

FV - Future Value

-G-

GETPLAYERS - Get number of players

GETSIMPLAYERS - Get number simulated of players

GETTOTPLAYERS - Get total number of players

GRADTODEG - Convert Gradients to Degrees

GRADTORAD - Convert Gradients to Radians

GRAPH - Linear Graph with Horizontal Asymptotes

GRAPHCURVE - Polynomial Graph with Linear Asymptotes

GRAPHLINAS - Linear Graph with Linear Asymptotes

GRAPHSTEP - Horizontal Graph with Horizontal Asymptotes

-H-

HIVAL - Highest Simulated Value

HYPOT- Hypotenuse

-I-

IF - Arithmetic If

IMAGC - Imaginary part of complex number or array

INDEX - Convert Index Variable to Scalar

INFINITY - Infinitely Large Positive Number

INIT- Initial Value

INT - Integer Part of Number

INTEGRATE - Integration

INVERT - Inverted square matrix

INVERTC - Inverted complex number or square matrix

-J-

-K-

-L-

LAST - Get Upper Limit of Range or Base Range of Index

LIMIT - Limit Variable to Given Range

LN - Natural Logarithm

LOG - Base N Logarithm

LOOKUP - Lookup Value of Array Element

LOVAL - Lowest Simulated Value

-M-

MATRIXPROD - Matrix Product

MAX - Maximum

MIN - Minimum

MOD - Remainder of Division

-N-

NAN - Not a Number

NORMAL - Normal Distribution

NOT - Negation

NPV - Net Present Value

-O-

OR - Logical Or

OTHERWISE - Default Guard Operator

-P-

PAUSEIF - Conditional Pause

PAUSEWHILE - Continuing Pause

PCT - Convert Number to Percent

PI - Trigonometric Constant Pi

PLAYERNUMBER - Get player number

PMT - Periodic Payment

POISSON - Poisson Distribution

POLTOCAR - Convert complex number or array from Polar to Cartesian form

POLY - Polynomial

PROD - Product of Expressions Over Indices

PRODC - Product of complex numbers, vectors or arrays

PRODCR - Product of complex and real numbers, vectors or arrays

PRODRC - Product of real and complex numbers, vectors or arrays

PULSE - Periodic Pulse

PULSEIF - Conditional Pulse

PV - Present Value

-Q-

QUEUE - Queue with multiple clients and servers

-R-

RADTODEG - Convert Radians to Degrees

RADTOGRAD - Convert Radians to Gradients

RAMP - Linear Function

REALC - Real part of complex number

RANDOM - Uniform Distribution

ROUND - Round Number to Nearest Integer

RUN - Run Number

RUNCOUNT - Number of Runs

-S-

SAMPLE - Periodic Sample

SAMPLEIF - Conditional Sample

SCANEQ - Scan Vector for Equal Element

SCANGT - Scan Vector for Greater Element

SCANGTEQ - Scan Vector for Greater or Equal Element

SCANLT - Scan Vector for Smaller Element

SCANLTEQ - Scan Vector for Smaller or Equal Element

SCANNEQ - Scan Vector for Unequal Element

SECONDSTHISRUN - Seconds since start of current run

SECONDSTHISSTEP - Seconds used simulating current time step

SELECTDECISION - Select decision value

SHIFTCIF - Conditional Circular Shift of Vector Elements

SHIFTLIF - Conditional Linear Shift of Vector Elements

SIGN - Sign of Number

SIN - Sine

SINH - Hyperbolic Sine

SINWAVE - Periodic Sine Wave

SOUND - Output Sound

SPROD - Scalar Vector Product

SQRT - Square Root

STARTTIME - Start Time of Simulation

STDDEV - Standard Deviation

STEP - Step Function

STOPIF - Stop Simulation

STOPRUNIF - Stop Current Run

STOPTIME - Stop Time of Simulation

STRATEGICMODE - Test if game is in strategic mode

SUM - Sum of Expressions Over Indices

-T-

TAN - Tangent

TANH - Hyperbolic Tangent

TIME - Current Time of Simulation

TIMECYCLE - Test for Cyclic Time or Time Interval

TIMEIS - Test for Given Time or Time Interval

TIMESTEP - Time Step of Simulation

TRANSPOSE - Transpose Matrix

TRANSPOSEC - Transposed matrix of complex numbers

TREND - Trend Extrapolation

TRUE - Logical True

-U-

-V-

VECTLEN - Vector Length

VECTOR - Create Vector

VECTPROD3D - 3D Vector Cross Product

-W-

WHEN - Guard Operator

-X-

XOR - Exclusive Logical Or

-Y-

-Z-


Alphabetical List of Operators

Operators are mathematical symbols, such as *, +, /, etc., used in the definition of Powersim variables.

- - Subtraction

- - Unary Minus

! - Factorial

% - Percent

* - Multiplication

+ - Addition

+ - Unary plus

/ - Division

; - Constraint operator

< - Less Than

<= - Less Than or Equal To

<> - Not Equal To

= - Equal To

> - Greater Than

>= - Greater Than or Equal To

^ - Number Raised to a Power

| - Guard Operator

AND - Conjunction, Logical And

BUT - Constraint operator

DIVZ0 - Division with Zero Result for Zero Denominator

DIVZ1 - Division with Unit Result for Zero Denominator

DIVZX - Division with Explicit Result for Zero Denominator

MOD - Remainder of Division

NOT - Negation

OR - Logical Or

OTHERWISE - Default Guard Operator

WHEN - Guard Operator

XOR - Exclusive Logical Or


Function Definitions


- - Subtraction

Syntax

A - B

In

A, B - Any number.

Result

The difference between A and B.

Group

Mathematical Functions


- - Unary Minus

Syntax

- A

In

A - Any number.

Result

A negated, i.e., (0 - A).


! - Factorial

Syntax

A!

In

A - Any number.

Result

Not-a-number (=?), if A is less than 0.

1, if A is zero.

1*2*3*4*...*A, if A is an integer.

Integrate(F) with F = TIME^A * EXP(-TIME), start time equal to 0.0, and stop time equal to infinity, if none of the above rules can be applied.

Example

The following expression is true:

3! = 6

Group

Mathematical Functions


% - Percent

Syntax

A%

In

A - Any number.

Result

A divided by 100.

Example

The following is true:

A/100 = A%

Note

% is a post fix operator converting a value from per cent to a regular number, for example: 7% = 7/100 = 0.07

Groups

Conversion Functions , Mathematical Functions

Related functions

PCT


* - Multiplication

Syntax

A * B

In

A, B - Any number.

Result

A multiplied by B.

Group

Mathematical Functions

Related functions

ARRPROD , MATRIXPROD, PRODC, PRODCR, PRODRC, SPROD, VECTPROD3D


+ - Addition

Syntax

A + B

In

A, B - Any number.

Result

The sum of A and B.

Group

Mathematical Functions

Related functions

ADD, ADDCR, ADDRC, ARRSUM, SUM


+ - Unary plus

Syntax

+ A

In

A - Any number.

Result

A unchanged.


/ - Division

Syntax

A / B

In

A - Any number.

B - Any number except 0.

Result

A divided by B.

Group

Mathematical Functions

Related functions

INVERT, INVERTC, MOD


; - Constraint operator

Syntax

A ; B

In

A, B - Any constrained expression.

Result

A if the constraint of A is true, and B otherwise.

Note

The constraint operator (;) is a built-in operator, and works together with the guard (|) in order to choose between alternative definitions of an array expression. This is often necessary in order to treat the first or the last index separately. The BUT operator may be used as an alternative to ;.

Example

See example with | in | - Guard Operator.

Group

Built-in Functions

Related functions

| , WHEN, BUT


< - Less Than

Syntax

A < B

In

A, B - Any number.

Result

True if A < B and False otherwise.

Group

Logical Functions


<= - Less Than or Equal To

Syntax

A <= B

In

A, B - Any number.

Result

True if A<=B and False otherwise.

Group

Logical Functions


<> - Not Equal To

Syntax

A <> B

In

A, B - Any number.

Result

True if A <> B and False otherwise.

Note

See note for =.

Group

Logical Functions


= - Equal To

Syntax

A = B

In

A, B - Any number.

Result

True if A = B and False otherwise.

Note

Testing for equality should be avoided if possible, since no computer is able to represent all possible floating point numbers accurately. This means that even if the results of two expressions should theoretically be the same, this may not be the case when executed on a computer. The following is an example of a "dangerous" expression:

IF(TIME = 5, B, C)

Group

Logical Functions

Related functions

TIMEIS


> - Greater Than

Syntax

A > B

In

A, B - Any number.

Result

True if A > B and False otherwise.

Group

Logical Functions


>= - Greater Than or Equal To

Syntax

A >= B

In

A, B - Any number.

Result

True if A >= B and False otherwise.

Group

Logical Functions


^ - Number Raised to a Power

Syntax

A ^ B

In

A, B - Any non-negative number.

Result

Returns the value of A raised to the power of B, for example, AB.

Note

The expression A ^ 0 is 1 for all values of A. The expression 0 ^ B is 0 for all values of B.

Group

Mathematical Functions


| - Guard Operator

Syntax

A | B

In

A - Any expression.

B - Any constraint, for example, an expression involving index variables, range references, and literal integers.

Result

A if B is true, and undefined otherwise.

Note

The guard (|) is a built-in operator, and works together with the constraint operator (;) in order to choose between alternative definitions of an array expression. This is often necessary in order to treat the first or the last index separately. The WHEN operator may be used as an alternative to |.

Example

The following definitions copy elements from B to A:

aux	B(1..3) = ...

aux	A(i=1..3) = B(i+1) | i < 3; B(1) | i = 3

The result would be the following:

A(1) = B(2)

A(2) = B(3)

A(3) = B(1)

The above definition of A corresponds to the following mathematical notation:

Group

Built-in Functions

Related functions

; , BUT, WHEN


ABS - Absolute Value

Syntax

ABS (X)

In

X - Any number.

Result

The absolute value of X.

Example

The expression ABS(-3) = 3 is true.

Group

Conversion Functions , Mathematical Functions

Related functions

ABSC


ABSC - Absolute value of complex number or array

Syntax

ABSC(A([...,] 2))

In

A - Complex number or array of complex numbers in Cartesian format.

Result

The absolute value of A.

Example

ABSC([3, 4]) = SQRT(3^2 + 4^2) = 5

ABSC([[1, 2], [3, 4]]) = [2.2361, 5]

Group

Complex Functions

Related functions

ANGLEC, REALC, IMAGC

See also

Using the ABSC function


AND - Conjunction, Logical And

Syntax

A AND B

In

A, B - Any number.

Result

True if both A and B are True, and False otherwise.

Note

The AND operator may also be used in defining constraints, as in the example below:

A(i,j) | i < 2 AND j > 5

A related (but not equivalent) way of expressing A AND B is:

A * B.

Groups

Built-in Functions , Logical Functions

Related functions

BOOL, NOT, OR , XOR, TRUE, FALSE

See also

Using Built-in functions


ADD - Sum of arrays

Syntax

ADD(A(...), B(...))

In

A, B - Arrays with equal dimensions.

Result

Array with the sum of A and B.

Example

The definition

aux C = ADD(A, B)

produces the same result as

aux C = A + B

where A, B and C are arrays.

Note

Complex numbers in Cartesian format may be added using ADD.

Groups

Complex Functions , Mathematical Functions

Related functions

ARRSUM

See also

Using the ADD function


ADDCR - Sum of complex and real numbers or arrays

Syntax

ADDCR(A([D1, D2, ... Dn,] 2), B([D1, D2, ... Dn]))

In

A - Complex number or array of complex numbers in Cartesian format.

B - Real number or array of real numbers.

Result

The sum of A and B.

Example

ADDCR([3, 4], 5) = [8, 4]

Group

Complex Functions

Related functions

ADD, ADDRC

See also

Using the ADDCR function


ADDRC - Sum of real and complex numbers or arrays

Syntax

ADDRC(A([D1, D2, ... Dn]), B([D1, D2, ... Dn,] 2))

In

A - Real number or array of real numbers.

B - Complex number or array of complex numbers in Cartesian format.

Result

The sum of A and B.

Example

ADDRC(2, [3, 4]) = [5, 4]

Group

Complex Functions

Related functions

ADD, ADDCR

See also

Using the ADDRC function


ANGLEC - Angle of complex number or array

Syntax

ANGLEC(A([...,] 2))

In

A - Complex number or array of complex numbers in Cartesian format.

Result

The angle of A measured in radians [-π..π].

Examples

ANGLEC([0, 1]) = 0

ANGLEC([[1, 1], [1, -1]]) = [0.7854, 2.3562]

Group

Complex Functions

Related functions

ABSC, REALC, IMAGC

See also

Using the ANGLEC function


ARCCOS - Arcus Cosine

Syntax

ARCCOS (Value)

In

Value from interval [-1..1].

Result

Angle defined by arcus sine of input value. Angle lies in the interval [-Pi/2 .. Pi/2].

Group

Trigonometric Functions

Related functions

ARCSIN, ARCTAN, COS, DEGTORAD, GRADTORAD


ARCSIN - Arcus Sine

Syntax

ARCSIN (Value)

In

Angle - Angle in radians.

Result

Angle defined by arcus cosine of input value. Angle lies in the interval [0 .. Pi].

Group

Trigonometric Functions

Related functions

ARCCOS, ARCTAN, SIN, DEGTORAD, GRADTORAD


ARCTAN - Arcus Tangent

Syntax

ARCTAN (Value)

In

Value.

Result

Angle defined by arcus tangent of input value. Angle lies in the interval <-Pi/2 .. Pi/2>.

Group

Trigonometric Functions

Related functions

ARCCOS, ARCSIN, TAN, DEGTORAD, GRADTORAD


ARRAVG - Average of Array Elements

Syntax

ARRAVG (A(...))

In

A - Any array.

Result

The average of the elements of A.

Example

ARRAVG([3, 5, 1, 7]) = 4

Groups

Array Functions , Statistical Functions

Related functions

AVG, ARRMIN, ARRMAX, ARRPROD, ARRSUM

See also

Using the ARRAVG function


ARRMAX - Maximum of Array Elements

Syntax

ARRMAX (A(...))

In

A - Any array.

Result

The maximum value of the elements of A.

Example

ARRMAX([3, 5, 1, 7]) = 7

Groups

Array Functions , Statistical Functions

Related functions

MAX, ARRMIN, ARRAVG, ARRPROD, ARRSUM

See also

Using the ARRMAX function


ARRMIN - Minimum of Array Elements

Syntax

ARRMIN (A(...))

In

A - Any array.

Result

The minimum value of the elements of A.

Example

ARRMIN([3, 5, 1, 7]) = 1

Groups

Array Functions , Statistical Functions

Related functions

MIN, ARRMAX, ARRAVG, ARRPROD, ARRSUM

See also

Using the ARRMIN function


ARRPROD - Product of Array Elements

Syntax

ARRPROD (A(...))

In

A - Any array.

Result

The product of the elements of A

Example

ARRPROD([3, 5, 1, 7]) = 105

Groups

Array Functions , Mathematical Functions

Related functions

* , ARRAVG, ARRMAX,, ARRMIN,, ARRSUM, MATRIXPROD, PRODC, PRODCR, PRODRC, SPROD, VECTPROD3D

See also

Using the ARRPROD function


ARRSTDDEV - Standard Deviation of Array Elements

Syntax

ARRSTDDEV (X(N))

In

X - Any array.

Result

The standard deviation of the elements of the array, as defined by the Powersim expression:

SQRT(SUM(i=1..N; (X-ARRAVG(X))^2))/N)

which may be simplified to:

1/N * SQRT(N * SUM(1..N;X^2) - ARRSUM(X)^2)

Groups

Array Functions , Statistical Functions

Related functions

STDDEV

See also

Using the ARRSTDDEV function


ARRSUM - Sum of Array Elements

Syntax

ARRSUM (A(...))

In

A - Any array.

Result

The sum of the elements of A.

Example

ARRSUM ([3, 5, 1, 7]) = 16

Groups

Array Functions , Mathematical Functions

Related functions

+ , ADD, ADDCR, ADDRC, ARRAVG, ARRMAX, ARRMIN, ARRPROD, SUM

See also

Using the ARRSUM function


ASSIGN - Set Value of Variable

Syntax

ASSIGN (Var, X)

In

X - Any number.

Out

Var - Level or constant variable.

Result

The value X.

Note

ASSIGN is one of the very few functions that have side-effects. In this case the value of the first parameter, which must be a level or a constant, is changed by the function to the value of the second parameter. The value is assigned at the end of the current simulation step, meaning that the value change will take effect in the next simulation step. We may therefore say that the use of ASSIGN implies a one time step delay.

Example

The following expression will set the value of A to zero whenever B is True:

IF(B, ASSIGN(A, 0), A)

Note that IF does not compute ASSIGN(A, 0) if B is False. If this was not the case, ASSIGN(A, 0) would always be evaluated and hence, A would always be set equal to zero.

Demo

ASSIGN.SIM

Group

Miscellaneous Functions

See also

Using the ASSIGN function


ATSTART - Test for Beginning of Simulation

Syntax

ATSTART

Result

True at the very beginning of the simulation, and False otherwise.

Group

Time Related Functions

Related functions

STARTTIME, STOPTIME, TIME, TRUE, FALSE


AVG - Average

Syntax

AVG (X1, X2, ...XN)

In

X1, X2,...XN - Any number (N >= 1)

Result

The mean of the arguments, as defined by the expression:

(X1, X2, ...XN)/N

Note

At least one argument must be specified.

Group

Statistical Functions

Related functions

ARRAVG


BOOL - Convert Number to Boolean

Syntax

BOOL (X)

In

X - Any number.

Result

Returns 1 if ROUND(X) is not zero, and 0 otherwise.

Example

The following expression is true:

BOOL(X) = (ROUND(X) <> 0)

See also: boolean values

Groups

Conversion Functions , Logical Functions

Related functions

TRUE, FALSE


BUT - Constraint operator

Syntax

A BUT B

In

A, B - Any constrained expression.

Result

A if the constraint of A is true, and B otherwise.

Note

Alternative name of the constraint operator (;).

Example

See example with | in | - Guard Operator .

Group

Built-in Functions

Related functions

WHEN, | , ;

See also

Using Built-in functions


CARTOPOL - Convert complex number or array from Cartesian to Polar form

Syntax

CARTOPOL(A([...,] 2))

In

A - Complex number or array of complex numbers in Cartesian format.

Result

A in Polar format.

Examples

CARTOPOL([0, 1]) = [1, 1.5798]

CARTOPOL(POLTOCAR(A)) = A

Groups

Complex Functions , Conversion Functions

Related functions

POLTOCAR, ANGLEC, ABSC


CEIL - Round Number Up to Nearest Integer

Syntax

CEIL (X)

In

X - Any number.

Result

Returns the smallest integer that is greater than or equal to X.

Group

Conversion Functions

Related functions

FLOOR, ROUND, INT, FRAC


COS - Cosine

Syntax

COS (Angle)

In

Angle - Angle in radians.

Result

The cosine of Angle.

Group

Trigonometric Functions

Related functions

SIN, TAN, ARCCOS, COSH, DEGTORAD, GRADTORAD, PI


COSH - Hyperbolic Cosine

Syntax

COSH (Value)

In

Value.

Result

The hyperbolic cosine of input value.

Group

Trigonometric Functions

Related functions

SINH, TANH, COS, DEGTORAD, GRADTORAD, PI


COSWAVE - Periodic Cosine Wave

Syntax

COSWAVE (Amplitude, Period)

In

Amplitude - Amplitude of the wave.

Period - Period of the wave.

Result

A time-dependent cosine wave, defined by the equation:

COSWAVE(A, P) = A * COS(TIME*2*PI/P)

Note

Function depends on TIME.

Group

Time Related Functions , Trigonometric Functions

Related functions

COS, SINWAVE, TIME


COUNT - Get Number of Elements of Range or Base Range of Index

Syntax

COUNT (R)

In

R - Range name or index variable

Result

The number of elements of R, if R is a range.

The number of elements in the base range of R, if R is an index variable.

Example

range Age=(Child, Young, Adult, Old)

const Ages = COUNT(Age)

Arrays and Subscripts , Constrained Expressions

Note

The relationship between COUNT, FIRST and LAST is the following:

COUNT(R) = LAST(R)-FIRST(R)+1

Group

Built-in Functions

Related functions

FIRST, LAST

See also

Using Built-in functions


DEFAULT - Default Guard of Constrained Expression

Syntax

DEFAULT

Result

True for all indices that are not part of (previous) guards for this expression.

Example

The following expressions are the same:

(A(i+1) | i<4; A(1) | DEFAULT)

(A(i+1) | i<4; A(1))

Note

DEFAULT works exactly like an empty guard, with the advantage of being more explicit in stating that the guard serves an "otherwise", catching all cases that have not already been covered by other guards.

Group

Built-in Functions

See also

Using Built-in functions


DEGTOGRAD - Convert Degrees to Gradients

Syntax

DEGTOGRAD (Angle)

In

Angle - Angle in degrees.

Result

The equivalent of Angle measured in gradients, as defined by the equation:

DEGTOGRAD(A) = A*400/360

Groups

Conversion Functions , Trigonometric functions

Related functions

DEGTORAD, GRADTODEG


DEGTORAD - Convert Degrees to Radians

Syntax

DEGTORAD (Angle)

In

Angle - Angle in degrees.

Result

The equivalent of Angle measured in radians, as defined by the equation:

DEGTORAD(A) = A*PI/180

Group

Conversion Functions , Trigonometric functions

Related functions

DEGTORAD, RADTODEG, PI


DELAYINF - N-th Order Information Delay

Syntax

DELAYINF (Input, DelayTime[, Order=1[, Initial(Order)=Input]])

In

Input - Variable to be delayed (delayed parameter).

DelayTime - Delay time measured in the time unit of the simulation.

Order - Positive integer specifying the order of the delay. It defaults to 1 if not specified (optional start-up parameter).

Initial - Initial delay value specified as a vector expression with Order number of elements. The elements of Initial default to the value of Input if not specified. If Initial has fewer elements than Order, the last element is replicated for the remaining values (optional start-up parameter).

Result

The n-th order exponential information delay of Input, using an exponential averaging time equal to DelayTime, a given delay order of Order, and a given Initial value for the delay.

Diagram

A first order information delay may be modeled like this:

The value of the level PerceivedInput corresponds to DELAYINF with Order set to one.

Equations

aux	Input = ...

init	PerceivedInput = ...

aux	DelayTime = ...

aux	ChInPerceivedInput = (Input-PerceivedInput)/DelayTime

flow	PerceivedInput = +dt*(ChInPerceivedInput)

Note

Input must be a variable (expressions and literals are not allowed), and in the diagram Input must be connected to the current variable using a delayed link.

If Initial is not specified or if Input is used in defining Initial, a normal link must also be used in the diagram to connect Input to the current variable. This is because Input will be used as both a normal, and a delayed, parameter.

Order should be less than DelayTime/TIMESTEP. Otherwise the function will not behave correctly (the delay time will be Order*TIMESTEP).

Groups

Delay Functions , History Functions


DELAYMTR - N-th Order Material Delay

Syntax

DELAYMTR(Input, DelayTime[, Order=1[, Initial(Order)=Input]])

In

Input - Variable to be delayed (delayed parameter).

DelayTime - Delay time measured in the time unit of the simulation.

Order - Positive integer specifying the order of the delay (optional start-up  parameter with default equal to 1).

Initial - Initial delay value specified as a vector expression, with Order defining the number of elements. The elements of Initial default to the value of Input if not specified. If Initial has fewer elements than Order, the last element is replicated for the remaining values (optional start-up parameter).

Result

The n-th order exponential material delay of Input, using an exponential averaging time of DelayTime, a given delay Order, and a given Initial value for the delay.

Diagram

The first order material delay can be modeled like this:

The value of the rate Output corresponds to DELAYMTR with Order set to one.

Equations

aux	Input = ...

aux	DelayTime = ...

init	InTransit = ...

flow	InTransit = -dt*(Output) +dt*(Input)

aux	Output = InTransit/DelayTime

Note

See note for DELAYINF

Groups

Delay Functions , History Functions


DELAYPPL - Pipeline Delay

Syntax

DELAYPPL (Input, DelayTime[, Initial=Input])

In

Input - Variable to be delayed (delayed parameter).

DelayTime - Delay time measured in the time unit of the simulation (start-up parameter).

Initial - Initial delay value (optional start-up parameter with default equal to Input).

Result

The value of Input at DelayTime time units earlier in the simulation. During the first DelayTime time units of the simulation, the values specified by Initial are returned (Initial is a vector with one element per time step for a period equal to DelayTime).

Diagram

The pipe-line delay may be modeled using a vector with DelayTime/TIMESTEP elements, which is shifted linearly to the right every time step:

Equations

aux	Input = ...

init	InTransit = ...

dim	InTransit = 1..10

flow	InTransit(i) = dt*(Input | i=1;0) - dt*(Output | i=LAST(i);0)

aux	Output = SHIFTLIFSHIFTLIF_Conditional_Linear_Shift_of_Vector_Elements>func(TRUE, InTransit)

The number of elements of InTransit should be set equal to the number of time steps in a DelayTime period, i.e., DelayTime/TIMESTEP.

Note

See note for DELAYINF

Groups

Delay Functions , History Functions


DELAYPPLINF - Variable Time Information Pipeline Delay

Syntax

DELAYPPLINF(Input, DelayTime, MaxDelayTime [, Initial=Input))

In

Input - Value to delayed (delayed parameter)

DelayTime - Delay time measured in the time unit of the simulation.

MaxDelayTime - Maximum delay time measured in the time unit of the simulation. This variable is used, in combination with the simulation time step to determine the maximum size of the internal storage that is used by the function.

Initial - Initial delay value (optional start-up parameter with default equal to Input).

Result

The "infinite" order information delay of Input with delay time DelayTime.

Note

The difference between DELAYPPLINF and DELAYPPL is that DELAYPPLINF will adjust to a changing DelayTime during simulation (while DELAYPPL uses the initial value of DelayTime for the entire simulation).

The difference between DELAYPPLMTR and DELAYPPLINF lies in the transient response to a change in DelayTime (see Delay Functions).

Use DELAYPPL if the delay time is constant.

Groups

Delay Functions , History Functions


DELAYPPLINFV - Variable Time Information Pipeline Delay through Vector

Syntax

DELAYPPLINFV(Input, DelayTime, V(N) [, Order])

In

Input - Value to delayed (delayed parameter)

DelayTime - Delay time measured in the time unit of the simulation. The maximum delay time used by the function is N*TIMESTEP, where N is the number of elements in V.

V - Vector with N elements. The number of elements in V should be determined like this:

N = ROUND(MaxDelayTime/TIMESTEP)

where MaxDelayTime is the maximum value that can be assigned to DelayTime during a simulation.

Out

V - Updated to reflect the state of the delay

Order - Number of used elements of V (optional output parameter). Order is determined from the current value of DelayTime and the simulation time step:

Order = ROUND(DelayTime/TIMESTEP)

Result

The infinite order information delay of Input with delay time DelayTime.

Note

The initial state of the delay is determined by the inital value of V.

The difference between DELAYPPLMTRV and DELAYPPLINFV lies in the way changes in DelayTime are handled. Assume that a change in the delay time causes the order to change from 2 to 4, and that V initially holds the values [4, 2, ...]. In the case of an information delay, the new values of V will be [4, 4, 2, 2, ...]. Observe that the average of (the used part of) V is kept unchanged. Comparing to the material delay, the resulting V would be [2, 2, 1, 1, ...].

Groups

Array Functions , Delay Functions , History Functions


DELAYPPLMTR - Variable Time Material Pipeline Delay

Syntax

DELAYPPLMTR(Input, DelayTime, MaxDelayTime [, Initial=Input))

In

Input - Value to delayed (delayed parameter)

DelayTime - Delay time measured in the time unit of the simulation.

MaxDelayTime - Maximum delay time measured in the time unit of the simulation. This variable is used, in combination with the simulation time step to determine the maximum size of the internal storage that is used by the function.

Initial - Initial delay value (optional start-up parameter with default equal to Input).

Result

The "infinite" order material delay of Input with delay time DelayTime.

Note

The difference between DELAYPPLMTR and DELAYPPL is that DELAYPPLMTR will adjust to a changing DelayTime during simulation (while DELAYPPL uses the initial value of DelayTime for the entire simulation).

The difference between DELAYPPLMTR and DELAYPPLINF lies in the transient response to a change in DelayTime (see Delay Functions).

Use DELAYPPLMTRV if you need to access the internal state of the delay. Use DELAYPPL if the delay time is constant.

Groups

Delay Functions , History Functions


DELAYPPLMTRV - Variable Time Material Pipeline Delay through Vector

Syntax

DELAYPPLMTRV(Input, DelayTime, V(N) [, Order])

In

Input - Value to delayed (delayed parameter)

DelayTime - Delay time measured in the time unit of the simulation. The maximum delay time used by the function is N*TIMESTEP, where N is the number of elements in V.

V - Vector with N elements. The number of elements in V should be determined like this:

N = ROUND(MaxDelayTime/TIMESTEP)

where MaxDelayTime is the maximum value that can be assigned to DelayTime during a simulation.

Out

V - Updated to reflect the state of the delay

Order - Number of used elements of V (optional output parameter). Order is determined from the current value of DelayTime and the simulation time step:

Order = ROUND(DelayTime/TIMESTEP).

Result

The infinite order material delay of Input with delay time DelayTime.

Note

The initial state of the delay is determined by the inital value of V.

The difference between DELAYPPLMTRV and DELAYPPLINFV lies in the way changes in DelayTime are handled. Assume that a change in the delay time causes the order to change from 2 to 4, and that V initially holds the values [4, 2, ...]. In the case of a material delay, the new values of V will be [2, 2, 1, 1, ...]. Observe that the sum of (the used part of) V is kept unchanged. Comparing to the information delay, the resulting V would be [4, 4, 2, 2, ...].

Example

The diagram below shows a context in which DELAYPPLMTRV is used.

The equations are:

aux	Input = IF(TIME < 50, SIN(TIME/20), 0)

const	DelayTime = 3

const	Order = 0

const	State(1..12) = 0

init	SumDelayed = ARRSUM(State)

flow	SumDelayed = -dt*DelayedInput + dt*Input

aux	DelayedInput = DELAYPPLINFV(Input, DelayTime, State, Order)

Groups

Array Functions , Delay Functions , History Functions


DERIVN - N-th Order Time Derivative

Syntax

DERIVN (Input[, Order=1])

In

Input - Expression to be derivated.

Order - Order of derivation. Default value is 1 (optional start-up parameter).

Result

Returns N-th Order time derivative of Input, as defined by the formula:

Note

Function result depends on previous values of Input.

Groups

History Functions , Mathematical Functions

Related functions

INTEGRATE


DIVZ0 - Division with Zero Result for Zero Denominator

Syntax

A DIVZ0 B

In

A, B - Any number.

Result

IF(B<>0, A/B, 0)

Group

Mathematical Functions

Related functions

DIVZ1, DIVZX


DIVZ1 - Division with Unit Result for Zero Denominator

Syntax

A DIVZ1 B

In

A, B - Any number.

Result

IF(B<>0, A/B, 1)

Group

Mathematical Functions

Related functions

DIVZ0, DIVZX


DIVZX - Division with Explicit Result for Zero Denominator

Syntax

DIVZX(A, B, X)

In

A, B, X - Any number.

Result

IF(B<>0, A/B, X)

Group

Mathematical Functions

Related functions

DIVZ0, DIVZ1


ELEMCOUNT - Number of Elements in an Array

Syntax

ELEMCOUNT (A(...))

In

A - Any array

Result

The number of elements in A.

Example

ELEMCOUNT ([3, 5, 1, 7]) = 4

Group

Array Functions

Related functions

VECTLEN


EULER - Sample at Start of Time Step

Syntax

EULER (X)

In

X - Any variable (computational parameter).

Result

The value of X at the beginning of the current time step.

Note

X must be a variable (expressions and literals are not allowed), and in the diagram X must be connected to the current variable using a delayed link.

This function is sometimes useful with higher order integration methods (defined in the Simulation Setup dialog box), where several computations are performed between each time step. If we want a value (for example, a rate) to be constant during the intermediate calculations of a higher order integration, EULER may be used.

Example

The two models below produce the same result if Euler integration is used, but not if a higher order integration like Runge-Kutta 4 is chosen:

	init A = 1 aux Direct_A = A flow A = +dt*(Direct_A)
	init B = 1 aux Euler_B = EULER(B) flow B = +dt*(Euler_B)
	When simulated using RK4 Fixed Step and a step of 0.5 the graphs to the left appears.
Group

History Functions

Related functions

INIT, SAMPLE, SAMPLEIF


EXP - Exponential of Number

Syntax

EXP (X)

In

X - Any number.

Result

Returns the exponential of X (e raised to the power of X (ex)).

Note

This is the inverse function of LN, i.e., LN(EXP(X)) = X.

Group

Mathematical Functions

Related functions

^, LN - Natural Logarithm


EXPRND - Exponential Distribution

Syntax

EXPRND ([Mean=1[, Seed]])

In

Mean - Mean value of distribution (optional parameter with default equal to one).

Seed - Initialization of random number generator (optional start-up parameter with random default value).

Result

Generates a series of exponentially distributed random numbers with a mean of Mean.

Examples

EXPRND generates exponentially distributed random numbers with mean equal to 1.

EXPRND(5) is the same as 5*EXPRND, both generating a series of exponentially distributed numbers with a mean of 5.

Group

Random Functions

Related functions

NORMAL, POISSON, RANDOM


FALSE - Logical False

Syntax

FALSE

Result

The value zero.

Group

Logical Functions

Related functions

TRUE


FIRST - Get Lower Limit of Range or Base Range of Index

Syntax

FIRST (R)

In

R - Range name or index variable.

Result

The lower limit of R, if R is a range.

The lower limit of the base range of R, if R is an index variable.

Example

The following definitions will compute the number of people that will enter a given age group because of age. The variable ALen is supposed to hold the length (duration) of each age group.

range	Age=(Child, Young, Adult, Old)

aux	AIn(A=Age) = Pop(A-1)/ALen(A-1) | A>FIRST(A); 0

Group

Built-in Functions

Related functions

COUNT, LAST

See also

Using Built-in functions


FLOOR - Round Number Down to Nearest Integer

Syntax

FLOOR (X)

In

X - Any number.

Result

Returns the largest integer that is less than or equal to X.

Examples

FLOOR (3.14) = 3

FLOOR (-5.5) = -6

Group

Conversion Functions

Related functions

CEIL, INT, FRAC, ROUND


FORECAST - Value Forecasting

Syntax

FORECAST (Input, PastTime, FutureTime[, Initial=0])

In

Input - Value to be predicted.

PastTime - Positive number determining the averaging time used in computing the trend in Input, measured in the time unit of the simulation.

FutureTime - Non-negative number determining how far into the future a forecast is going to be, measured in the time unit of the simulation.

Initial - Initial trend value (optional start-up parameter with default equal to zero).

Result

The forecasted value of Input at a time FutureTime into the future. The function computes the first order exponential average of Input by using an averaging time of PastTime, and then extrapolates the trend a distance equal to FutureTime into the future.

Diagram

The following diagram builds on the diagram of the TREND function, and extrapolates the value of Input into the future.

	aux Input = ... aux FutureTime = ... aux PastTime = ... init AverageOfInput = ... flow AverageOfInput = +dt * (ChangeInInput) aux ChangeInInput = (Input-AverageOfInput) / PastTime aux ForecastOfInput = Input + Input * TrendInInput * FutureTime aux TrendInInput = ChangeInInput / AverageOfInput
Note

The function depends on previous values of its first parameter.

Group

History Functions

Related functions

TREND

See also

Using the Forecast function


FRAC - Fraction of Number

Syntax

FRAC (X)

In

X - Any number.

Result

The fractional (decimal) part of X.

Note

The relationship between X, INT(X) and FRAC(X) is the following (for all values of X):

X = INT(X) + FRAC(X)

Examples

FRAC(3.14) = 0.14

FRAC(-5.5) = -0.5

Group

Conversion Functions

Related functions

CEIL, INT, FLOOR, ROUND


FV - Future Value

Syntax

FV (Rate, Periods, Payment, PresentValue)

In

Rate - Rate per period.

Periods - Number of periods.

Payment - Periodic payment.

PresentValue - Present value.

Result

Future value (see Introduction to Financial Functions )

Group

Financial Functions

Related functions

NPV, PMT, PV

See also

Using the Finance demo model


GETPLAYERS - Get number of players

Syntax

GETPLAYERS

Result

The number of players (personal) participating in the game. The number is taken from the game set-up file.

Group

Miscellaneous Functions

Related functions

GETSIMPLAYERS, GETTOTPLAYERS, PLAYERNUMBER


GETSIMPLAYERS - Get number simulated of players

Syntax

GETSIMPLAYERS

Result

The number of simulated players participating in the game. The number is taken from the game set-up file.

Group

Miscellaneous Functions

Related functions

GETPLAYERS, GETTOTPLAYERS, PLAYERNUMBER


GETTOTPLAYERS - Get total number of players

Syntax

GETTOTPLAYERS

Result

The number of players (personal) and simulated players participating in the game. The number is taken from the game set-up file.

Group

Miscellaneous Functions

Related functions

GETPLAYERS, GETSIMPLAYERS, PLAYERNUMBER


GRADTODEG - Convert Gradients to Degrees

Syntax

GRADTODEG (Angle)

In

Angle - Angle in gradients.

Result

The equivalent of Angle measured in radians, as defined by:

GRADTODEG(A) = A*360/400

Group

Conversion Functions , Trigonometric functions

Related functions

GRADTORAD, DEGTORAD


GRADTORAD - Convert Gradients to Radians

Syntax

GRADTORAD (Angle)

In

Angle - Angle in gradients.

Result

The equivalent of Angle measured in radians, as defined by:

GRADTORAD(A) = A*PI/200

Group

Conversion Functions , Trigonometric functions

Related functions

GRADTODEG, RADTOGRAD, PI


GRAPH - Linear Graph with Horizontal Asymptotes

Syntax

GRAPH (X, X1, Dx, Y(N))

In

X - Any number (independent variable).

X1 - Value of X corresponding to the first sample, i.e., Y(1).

Dx - Increment between sampled X values. Must be positive.

Y - Vector.

Result

GRAPH is used to express a function by providing a set of function values or a series of equally spaced input values, as listed below:

Input	Output
X1	Y(1)
X1+Dx	Y(2)
X1+2*Dx	Y(3)
...	...
X1+(N-1)*Dx	Y(N)
If X is less than X1 then Y(1) is returned. If X is greater than X1 + (N-1)*Dx then Y(N) is returned, where N is the number of elements in Y. In other words, the function has horizontal asymptotes. If an input value X lies between two points in the X1 + k*Dx series, the value is calculated by linear interpolation (see figure above).

Example

The expression GRAPH(X, 0, 1, [0.2, 0.38, 0.52, 0.43, 0.22]) produces the graph above.

Note

Graph functions can be edited either as text, or by using the Graph button of the Define Variable dialog box.

Group

Graph Functions

Related functions

GRAPHCURVE, GRAPHLINAS, GRAPHSTEP


GRAPHCURVE - Polynomial Graph with Linear Asymptotes

Syntax

GRAPHCURVE (X, X1, Dx, Y(N))

In

X - Any number (independent variable).

X1 - Value of X corresponding to the first sample, i.e., Y(1).

Dx - Increment between sampled X values. Must be positive.

Y - Vector. The initial value of Y will be used for the rest of the simulation.

Result

GRAPHCURVE is used to express a function by providing a set of function values for a series of equally spaced input values, as listed below:

Input	Output
X1	Y(1)
X1+Dx	Y(2)
X1+2*Dx	Y(3)
...	...
X1+(N-1)*dx	Y(N)
If an input value X lies between two points in the X1 + k*Dx series, the value is calculated by third order polynomial interpolation (see figure above). This yields a smoother function than GRAPH and GRAPHLINAS. The function uses linear asymptotes for points that lie outside the range X1 to X1 + (N-1)*Dx.

Example

The expression GRAPHCURVE(X, 0, 1, [0.2, 0.38, 0.52, 0.43, 0.22]) produces the graph above.

Note

Graph functions can be edited either as text, or by using the Graph button of the Define Variable dialog box.

Group

Graph Functions

Related functions

GRAPH, GRAPHLINAS, GRAPHSTEP


GRAPHLINAS - Linear Graph with Linear Asymptotes

Syntax

GRAPHLINAS (X, X1, Dx, Y(N))

In

X - Any number (independent variable).

X1 - Value of X corresponding to the first sample, i.e., Y(1).

Dx - Increment between sampled X values. Must be positive.

Y - Vector with at least one element.

Result

GRAPHLINAS is used to express a function by giving a set of function values for a series of equally spaced input values, as listed below:

Input	Output
X1	Y(1)
X1+Dx	Y(2)
X1+2*Dx	Y(3)
...	...
X1+(N-1)*Dx	Y(N)
If X is less than X1 then the value is extrapolated on the basis of Y(1) and Y(2), i.e., a line through the two first points of the sample.

If X is greater than X1 + (N-1)*Dx then the value is extrapolated on the basis of the last two points in the sample, i.e., Y(N-1) and Y(N). This means that the function uses linear asymptotes based on the two most extreme points at both edges of the sample.

The relationship between GRAPH and GRAPHLINAS is as follows; GRAPH(X, X1, Dx, Y(...)) = GRAPHLINAS(X, X1-Dx, Dx, Z(...)), where Z = [Y(1), Y(1), Y(2), ..., Y(N-1), Y(N), Y(N)].

Example

The expression GRAPHLINAS(X, 0, 1, [0.2, 0.38, 0.52, 0.43, 0.22]) produces the graph above.

Note

Graph functions can be edited either as text, or by using the Graph button of the Define Variable dialog box.

Group

Graph Functions

Related functions

GRAPH, GRAPHCURVE, GRAPHSTEP


GRAPHSTEP - Horizontal Graph with Horizontal Asymptotes

Syntax

GRAPHSTEP (X, X1, Dx, Y(N))

In

X - Any value (independent variable).

X1 - Value of X corresponding to the first sample, i.e., Y(1).

Dx - Increment between sampled X values. Must be positive.

Y - One-dimensional array with at least one element.

Result

GRAPHSTEP is used to express a function by giving a set of function values for a series of equally spaced input values, as listed below:

Input	Output
X1	Y(1)
X1+Dx	Y(2)
X1+2*Dx	Y(3)
...	...
X1+(N-1)*Dx	Y(N)
If X is less than X1 then Y(1) is returned. If X is greater than X1 + (N-1)*Dx then Y(N) is returned, where N is the number of elements in Y. In other words, the function has horizontal asymptotes. If an input value X lies between two points in the X1 + k*Dx series, the value of the leftmost point is returned (see figure above).

Example

The expression GRAPHSTEP(X, 0, 1, [0.2, 0.38, 0.52, 0.43, 0.22]) produces the graph above.

Note

Graph functions can be edited either as text, or by using the Graph button of the Define Variable dialog box.

Note

You must reduce the time step to a value below 1 (in this example it is 0.1) to see the difference between a horizontal graph function (GRAPHSTEP) and a linear graph function (for example, GRAPH) in a time graph object if TIME is used as the independent variable.

Group

Graph Functions

Related functions

GRAPH, GRAPHCURVE, GRAPHLINAS


HIVAL - Highest Simulated Value

Syntax

HIVAL (X)

In

X - Any number.

Result

The highest value of the expression X so far in the simulation.

Note

Function depends on previous values of its parameter.

Group

History Functions

Related functions

LOVAL, MAX


HYPOT - Hypotenuse

Syntax

HYPOT (X, Y)

In

X, Y - Any number.

Result

The square root of X2 + Y2, i.e., the length of the hypotenuse of a square-angled triangle. See figure below:

This may also be expressed as: SQRT(X^2+Y^2).

Group

Mathematical Functions

Related functions

ABSC, VECTLEN


IF - Arithmetic If

Syntax

IF (Condition, Value1, Value2)

In

Condition - Logical value (True or False).

Value1 - Any numeric expression (computational parameter).

Value2 - Any numeric expression (computational parameter).

Result

The value of Value1 is evaluated and returned if Condition is True. The value of Value2 is evaluated and returned otherwise.

Notes

Only one of the expressions, Value1 or Value2, is computed by the function, depending on the value of the Condition. This means that functions with side effects, for example, SOUND and ASSIGN, will not be carried out if used in the false part of IF.

The IF function can be nested as many as 8 times, in the following manner:

IF(A<B,C,(IF(C>A,E,(IF(D=B,C,(IF(E<B, A,(IF(B>D, E,(IF(E=A,C,(IF(A>=D, C,(IF(A=B, D,0)))))))))))))))

Group

Conditional Functions

See also

Using the IF function


IMAGC - Imaginary part of complex number or array

Syntax

IMAGC(A([...,] 2))

In

A - Complex number or array of complex numbers in Cartesian format.

Result

The imaginary part of A.

Examples

REALC([1, 2]) = 2

REALC([[1, 2], [3, 4]]) = [2, 4]

REALC(A) = A(2) 'Where A is a complex number'

Group

Complex Functions

Related functions

ABSC, ANGLEC, REALC


INDEX - Convert Index Variable to Scalar

Syntax

INDEX (Idx)

In

Idx - Index variable.

Result

The numeric value of Idx.

Note

The function may also be used in array subscripts.

Example

The following expression computes the sum of the squares of the numbers 1 through 9:

SUM(i=1..9; INDEX(i)^2)

Groups

Built-in Functions , Conversion Functions

Related functions

COUNT, LAST, FIRST

See also

Using Built-in functions


INFINITY - Infinitely Large Positive Number

Syntax

INFINITY

Result

A value that is used to represent a number that is too large to be represented by the computer.

Note

Use -INFINITY to denote an infinitely large negative number.

The largest number that may be stored by Powersim is 1.0E+300.

Group

Mathematical Functions

Related functions

NAN, TRUE, FALSE


INIT - Initial Value

Syntax

INIT (X)

In

X - Any numeric expression (computational start-up parameter).

Result

The initial value of X.

Note

The function depends on previous value of its parameter.

X will only be evaluated during the initialization stage of the simulation, and the resulting value will be returned for the rest of the simulation.

Examples

Examples of Test Data Distributions

Group

History Functions

Related functions

SAMPLE, SAMPLEIF, EULER , Initializing Constants


INT - Integer Part of Number

Syntax

INT (X)

In

X - Any number.

Result

Returns the integer part of X.

Note

The relationship between X, INT(X) and FRAC(X) is the following (for all values of X):

X = INT(X) + FRAC(X)

Examples

INT(3.14) = 3

INT(-5.5) = -5

Group

Conversion Functions

Related functions

CEIL, FLOOR, FRAC, ROUND


INTEGRATE - Integration

Syntax

INTEGRATE (X)

In

X - Variable to be integrated over time (delayed parameter).

Result

The integrated value of X, i.e., the sum Xt/ for all time steps from the beginning of the simulation to the current time.

Diagram

The INTEGRATE(X) function produces the same result as the following model:

	init IntegrateX = ... aux X = ... flow IntegrateX = +dt * X
Note

The function depends on previous values of its parameter.

X must be a variable (expressions and literals are not allowed), and in the diagram X must be connected to the current variable using a delayed link.

Groups

History Functions , Mathematical Functions

Related functions

DERIVN


INVERT - Inverted square matrix

Syntax

INVERT(A(N, N))

In

A - Square matrix

Result

A inverted, i.e., A-1

Groups

Array Functions , Mathematical Functions

Related functions

/ - Division , ADD, INVERTC, MATRIXPROD


INVERTC - Inverted complex number or square matrix

Syntax

INVERTC(A([N, N,] 2))

In

A - Complex number of square matrix of complex numbers in Cartesian format.

Result

A inverted, i.e., A-1

Examples

INVERTC([1, 2]) = [0.2, -0.4]

INVERTC(INVERTC(A)) = A

PRODC(A, INVERTC(A)) = [1, 0]

Group

Complex Functions

Related functions

INVERT, ADD, PRODC


LAST - Get Upper Limit of Range or Base Range of Index

Syntax

LAST (R)

In

R - Range name or index variable.

Result

The upper limit of R, if R is a range.

The upper limit of the base range of R, if R is an index variable.

Example

The following definitions will compute the number of people that will leave a given age group because of aging. The variable ALen defines the length (duration) of each age group.

range	Age=(Child, Young, Adult, Old)

aux	AOut(A=Age) = Pop(A)/ALen(A) | A<LAST(Age); 0

Group

Built-in Functions

Related functions

COUNT, FIRST

See also

Using Built-in functions


LIMIT - Limit Variable to Given Range

Syntax

LIMIT (Var, MinVal, MaxVal)

In

Var - Level or constant variable.

MinVal, MaxVal - Any numbers, where MinVal <= MaxVal.

Out

Var - Original value limited to the range MinVal..MaxVal.

Result

The difference between the constrained and the unconstrained value of Var :

MAX(MinVal, MIN(Var, Max)) - Var

Note

The variable Var is updated with its new, constrained value at the end of the simulation step.

The function has side effects (it modifies its first parameter).

Related functions

ASSIGN, MIN, MAX, HIVAL, LOVAL

Group

Miscellaneous Functions


LN - Natural Logarithm

Syntax

LN (X)

In

X - Any positive number.

Result

The natural logarithm of X.

Group

Mathematical Functions

Related functions

EXP, LOG


LOG - Base N Logarithm

Syntax

LOG (X[, Base=10])

In

X - Any positive number.

Base - Base of logarithm (optional parameter with default equal to 10).

Result

The base N logarithm of X.

Group

Mathematical Functions

Related functions

EXP, LN - Natural Logarithm


LOOKUP - Lookup Value of Array Element

Syntax

LOOKUP(A(...), Idx1, Idx2, ..., IdxN)

In

A - Array with at least N dimensions.

Idx1, Idx2, ..., IdxN - Indices into the array A. Indices are in the range from 1 and up.

Result

The value of A(Idx1, Idx2, ..., IdxN). If one or more indices are out of range NAN is returned. If N is less than the number of dimensions in A an array is returned.

Note

LOOKUP is typically used when we need to index an array with a normal variable or expression instead of a subscript expression.

If A is a vector and Idx is an index variable, the expressions A(Idx) and LOOKUP(A, INDEX(Idx)) produce the same result. The first expression is preferred both because of readability and efficiency in terms of simulation speed.

If Y is a vector and X is a scalar, the expression LOOKUP(Y, X) is equivalent to GRAPHSTEP(ROUND(X), 1, 1, Y)

Demo

LOOKUP.SIM

Group

Array Functions

Related functions

VECTOR, INDEX, GRAPH, GRAPHCURVE, GRAPHLINAS, GRAPHSTEP


LOVAL - Lowest Simulated Value

Syntax

LOVAL (X)

In

X - Any number.

Result

The lowest value of the expression X so far in the simulation.

Note

The function depends on previous values of its parameter.

Group

History Functions

Related functions

HIVAL, MIN


MATRIXPROD - Matrix Product

Syntax

MATRIXPROD(A(m, n), B(n, p))

In

A, B - Two-dimensional arrays where the number of columns of the first matrix must equal the number of rows of the second.

Result

A m x p matrix C holding the matrix product of A and B. Element C(r, s) of the result matrix is defined like this:

Equations

The matrix product may also be computed like this:

aux	C(r=1..m, s=1..p) = SUM(i=1..n;A(r,i)*B(i,s))

Groups

Array Functions , Mathematical Functions

Related functions

ARRPROD, PRODC, PRODCR, PRODRC, SPROD, TRANSPOSE, VECTPROD3D


MAX - Maximum

Syntax

MAX (X1, X2, ...XN)

In

X1, X2, ...XN - Any number.

Result

The maximum of the arguments.

Group

Statistical Functions

Related functions

ARRMAX, HIVAL, MIN, AVG, STDDEV


MIN - Minimum

Syntax

MIN (X1, X2, ...XN)

In

X1, X2, ...XN - Any number.

Result

The minimum of the arguments.

Group

Statistical Functions

Related functions

ARRMIN, MAX, AVG, STDDEV


MOD - Remainder of Division

Syntax

A MOD B

In

A - Any number.

B - Any number except zero.

Result

The remainder of A / B, defined as the value R such that:

A = B * k + R

where k is an integer and ABS(R) < ABS(B).

Group

Mathematical Functions

Related functions

/


NAN - Not a Number

Syntax

NAN

Result

A value that is used to represent an invalid number.

Group

Mathematical Functions

Related functions

INFINITY, TRUE, FALSE


NORMAL - Normal Distribution

Syntax

NORMAL ([Mean=0[, Deviation=1[, Seed]]])

In

Mean - Mean value of distribution, with default equal to 0 (optional parameter).

Deviation - Deviation of distribution, with default equal to 1 (optional parameter).

Seed - Initialization of random number generator (optional start-up parameter with random default value).

Result

Generates a series of normally distributed random numbers with a mean of Mean and a standard deviation of Deviation.

Examples

5 + NORMAL generates normally distributed random numbers with mean = 5 and standard deviation = 1.

20 + 3*NORMAL generates normally distributed random numbers with mean = 20 and standard deviation = 3.

NORMAL(20, 3) generates the same distribution as the one above.

NORMAL(5) generates normally distributed random numbers with mean = 5 and standard deviation = 1.

Examples of Test Data Distributions

Group

Random Functions

Related functions

EXPRND, POISSON, RANDOM


NOT - Negation

Syntax

NOT A

In

A - Logical value, True or False.

Result

True if A is False, and False otherwise.

Example

The following is true: NOT 1 = 0; and NOT 0 = 1.

Note

A related way of expressing NOT A is: 1 - A.

Related functions

FALSE, TRUE, AND, OR, XOR

Group

Logical Functions


NPV - Net Present Value

Syntax

NPV (Payment, InterestRate)

In

Payment - Input variable.

InterestRate - Rate per time unit.

Result

The Net Present Value

Groups

Financial Functions , History Functions

Related functions

FV, PMT, PV

See also

Using the Finance demo model


OR - Logical Or

Syntax

A OR B

In

A, B - Logical value, True or False.

Result

True if at least one of A or B is True, and False otherwise.

Note

The OR operator may also be used in defining constraints, as in the example below:

A(i) | i < 2 OR i > 5

A related way of expressing A OR B is: A + B - A * B.

Group

Built-in Functions , Logical Functions

Related functions

XOR, AND, NOT, BOOL, TRUE, FALSE

See also

Using Built-in functions


OTHERWISE - Default Guard Operator

Syntax

A OTHERWISE

In

A - Any expression.

Result

A for all indices that are not part of (previous) guards for this expression.

Note

OTHERWISE is equivalent to WHEN DEFAULT. See note for DEFAULT.

Group

Built-in Functions

Related functions

| - Guard Operator , WHEN, DEFAULT

See also

Using Built-in functions


PAUSEIF - Conditional Pause

Syntax

PAUSEIF(Condition)

In

Condition - When this argument becomes True, the simulation is paused. The simulation can be restarted (for example by using the pause-button) even if Condition is still True.

Result

The value of Condition.

Group

Control Functions

Related functions

PAUSEWHILE, STOPIF, STOPRUNIF

See also

Using the PAUSEIF function


PAUSEWHILE - Continuing Pause

Syntax

PAUSEWHILE(Condition)

In

Condition - When this argument is True, the simulation is paused. The simulation cannot be restarted (for example by using the pause-button) unless the Condition is False.

Result

The value of Condition.

Group

Control Functions

Related functions

PAUSEIF, STOPIF, STOPRUNIF

See also

Using the PAUSEWHILE function


PCT - Convert Number to Percent

Syntax

PCT (X)

In

X - Any number.

Result

X * 100

Groups

Conversion Functions , Mathematical Functions

Related functions

%


PI - Trigonometric Constant Pi

Syntax

PI

Result

Value of Pi, i.e., 3.141592654...

Group

Trigonometric Functions

Related functions

DEGTORAD, GRADTORAD, RADTODEG, RADTOGRAD


PLAYERNUMBER - Get player number

Syntax

PLAYERNUMBER

Result

The player number of the current player.

Group

Miscellaneous Functions

Related functions

GETPLAYERS, GETSIMPLAYERS, GETTOTPLAYERS


PMT - Periodic Payment

Syntax

PMT (Rate, Periods, PresentValue, FutureValue)

In

Rate - Discount rate per period.

Periods - Number of periods.

PresentValue - Present value.

FutureValue - Future value.

Group

Financial Functions

Result

Periodic payment (see Introduction to Financial Functions ).

See also

Using the Finance demo model


POISSON - Poisson Distribution

Syntax

POISSON ([Mean=1[, Seed]])

In

Mean - Mean value of distribution (optional parameter with default equal to 1). The Mean value always refers to the actual timestep set in the Simulation setup dialogbox.

Seed - Initialization of random number generator (optional start-up parameter with random default value).

Result

Generates a series of random numbers according to the Poisson distribution, with a mean of Mean.

Note

The Mean value always refers to the actual timestep defined in the Simulation setup dialogbox, NOT to the associated time unit. Thus, if the timestep is doubled, the Mean value must be multiplied by 2, to maintain the behavior of the Poisson function with respect to the time unit. Alternatively, if the Mean value passed to the poisson function is always multiplied by the timestep, it will refer to the associated time unit.

Group

Random Functions

Related functions

EXPRND, NORMAL, RANDOM


POLTOCAR - Convert complex number or array from Polar to Cartesian form

Syntax

POLTOCAR(A([...,] 2))

In

A - Complex number or array of complex numbers in Polar format.

Result

A in Cartesian format.

Examples

POLTOCAR([3, 3.141592]) = [-3, 0]

CARTOPOL(POLTOCAR(A)) = A

Groups

Complex Functions , Conversion Functions

Related functions

CARTOPOL, ANGLEC, ABSC


POLY - Polynomial

Syntax

POLY (X, A0 [, A1, ..., An])

In

X - Any number.

A0...An - Any number (polynomial coefficients).

Result

The polynomial function of X, as defined by the expression:

Group

Mathematical Functions


PROD - Product of Expressions Over Indices

Syntax

PROD(Dim1, Dim2, ..., DimN; Expression)

In

Dim1, Dim2, ...,DimN - Definition of dimensions to be "summed over". Each dimension is defined as an optional index variable followed by an equal sign and a range. Several dimensions may be defined, separated by commas.

Expression - Any expression, possibly referring to indices of Dim1, Dim2, ...,DimN.

Result

The product of the values of Expression over the dimensions Dim1, Dim2, ...,DimN.

Note

The PROD function does not follow the normal syntax of a function, as dimensions may be defined (as for array variables). Also note the semicolon (;) separating the dimensions and the expression.

The relationship between a conventional mathematical notation and the PROD function is illustrated below:

Examples

The expression PROD(i=1..3; A(i) is the same as the following:

A(1) * A(2) * A(3)

The following expressions are always true:

PROD(1..3; 2) = 8

PROD(i=1..5; INDEX(i)) = 5!

PROD(i=1..5; INDEX(i)) = 120

Group

Array Functions


PRODC - Product of complex numbers, vectors or arrays

Syntax

PRODC(A([[M,] N,] 2), B([[M,] N,] 2))

In

A, B - Complex numbers, vectors or matrices in Cartesian format.

Result

The product of A and B.

Group

Complex Functions

Related functions

MATRIXPROD, PRODRC, PRODCR


PRODCR - Product of complex and real numbers, vectors or arrays

Syntax

PRODCR(A([[M,] N,] 2), B([[M,] N]))

In

A - Complex number, vector or matrix in Cartesian format.

B - Real number, vector or matrix.

Result

The product of A and B.

Example

PRODCR([3, 4], 5) = [15, 20]

Group

Complex Functions

Related functions

PRODC, PRODRC


PRODRC - Product of real and complex numbers, vectors or arrays

Syntax

PRODRC(A([[M,] N]), B([[M,] N,] 2))

In

A - Real number, vector or matrix.

B - Complex number, vector or matrix in Cartesian format.

Result

The product of A and B.

Example

PRODRC(2, [3, 4]) = [6, 8]

Group

Complex Functions

Related functions

PRODC , PRODCR


PULSE - Periodic Pulse

Syntax

PULSE (Volume, First, Interval)

In

Volume - Pulse volume (computational parameter).

First - Time of first pulse, measured in the time unit of the simulation.

Interval - Time interval between pulses, measured in the time unit of the simulation.

Result

Volume/TIMESTEP or 0, depending on the current TIME and the values of First and Interval. A pulse occurs at the time First, and every time Interval thereafter.

Note

The function depends on TIME and TIMESTEP.

The relationship between PULSE and PULSEIF is the following:

PULSE(V, F, I) = PULSEIF(TIMECYCLE(F, I), V)

Example

The expression PULSE(10, 4, 2) produces the following graph when simulated with a time step of 0.1:

Demo

Inventory Oscillations

Group

Time Related Functions

Related functions

PULSEIF, TIME


PULSEIF - Conditional Pulse

Syntax

PULSEIF (Condition, Volume)

In

Condition - Condition True or False determining if pulse is going to occur.

Volume - Pulse volume (computational parameter).

Note

The function depends on TIMESTEP.

Result

Zero if Condition is False and Volume/TIMESTEP otherwise.

Group

Conditional Functions

Related functions

PULSE, TRUE, FALSE, TIMEIS, TIMECYCLE


PV - Present Value

Syntax

PV (Rate, Periods, Payment, FutureValue)

In

Rate - Rate per period.

Periods - Number of periods.

Payment - Periodic payment.

FutureValue - Future value (optional parameter with default equal to zero).

Result

Present value (see Introduction to Financial Functions ).

Group

Financial Functions

Related functions

FV, NPV, PMT

See also

Using the Finance demo model


RADTODEG - Convert Radians to Degrees

Syntax

RADTODEG (Angle)

In

Angle - Angle in radians.

Result

The equivalent of Angle measured in degrees, as defined by the equation:

RADTODEG(A) = A*180/PI

Group

Conversion Functions

Related functions

DEGTORAD, PI , RADTOGRAD


QUEUE - Queue with multiple clients and servers

Syntax

QUEUE (Input(Clients) [, QMax=100 [, QInit[(K [, 2])]=0 [, Ready(Servers)=TRUE [, QLen [, QWait]]]]])

In

Input - Scalar or vector with client requests for services. Each element of Input holds the amount of work requested by the corresponding client from a server.

QMax - Maximum capacity of queue in terms of number of client requests (optional start-up parameter with default equal to 100).

QInit - When QInit is a scalar, the queue is initially empty (optional start-up parameter with default equal to zero).

QInit(K) - When QInit is a vector, the queue is initialized with K elements with arrival times set to zero and service time of element i set to QInit(i).

QInit(K, 2) - When QInit is a K x 2 matrix, the queue is initialized with K elements with arrival time of element i set to QInit(i, 1) and service time of element i set to QInit(i, 2).

Ready - Scalar or vector with logical values determining which servers are available for serving clients (optional parameter with default equal to TRUE).

Out

QLen - Actual length of queue (optional output parameter).

QWait - Waiting time of most recent output from queue (optional output parameter).

Result

Scalar or vector with one element per server determining the work flow into each server. If Ready(i) is FALSE, Result(i) will be zero.

Note that requests will not be added together when returned by the QUEUE function. As an example, three requests of sizes 0.1, 0.4 and 0.3 will not be returned as one request of size 0.8.

Note

Non-zero elements of Input are appended to an internal list of pending requests. For each Ready server, an element is picked from the front of the queue and assigned to the corresponding element of the result vector. If the queue becomes empty, zero is assigned to the remaining elements of the Result vector.

Demo

QUEUE1.SIM

Example

The diagram below illustrates a system with one client and one server:

The equations are given below:

aux	BeginService = QUEUE(RequestService, 100, 0, SeverReady, QLen, QWait)

aux	DoService = MIN(WorkLeftThisRequest/TIMESTEP + BeginService, 1)

const	QLen = 0

const	QWait = 0

aux	RequestService = POISSON(1/5 * TIMESTEP) / TIMESTEP * RANDOM(1, 10)

aux	SeverReady = WorkLeftThisRequest <= TIMESTEP

init	SumWorkPending = 0

flow	SumWorkPending = -dt*BeginService +dt*RequestService

init	WorkLeftThisRequest = 0

flow	WorkLeftThisRequest = -dt*DoService +dt*BeginService

•	Here a client request arrives at the average every fifth time unit, with demand for a service time in the range from 1 to 10. (See RequestService)

•	When the server is ready, the QUEUE function removes a client request from the queue and returns the service time requested by the client. (See BeginService)

•	The server performs a maximum of one unit of service every time unit. (See DoService)

•	The server is ready for a new request if it has nothing left to do on the current request, or if it will complete the current request within the current time step. (See SeverReady)

•	SumWorkPending is not necessary for the model to work.

•	QLen and QWait are output parameters. Note that the values will be updated by the QUEUE function with a delay of one time step.

Another Example

Queue with Multiple Clients and Servers

Group

History Functions

Related functions

All Delay Functions , SHIFTLCNT, SHIFTCIF, SHIFTLIF


RADTOGRAD - Convert Radians to Gradients

Syntax

RADTOGRAD (Angle)

In

Angle - Angle in radians.

Result

The equivalent of Angle measured in degrees, as defined by the equation:

RADTOGRAD(A) = A*200/PI

Group

Conversion Functions

Related functions

GRADTORAD, PI , RADTODEG


RAMP - Linear Function

Syntax

RAMP (Slope, First)

In

Slope - Slope of the function.

First - Time to start ramp.

Result

0 if TIME < First, and (Slope * TIME - First) otherwise, as defined by the following equation:

RAMP(S, F) = IF(TIME < F, 0, (TIME-F)*S)

Demo

Inventory Oscillations

Group

Time Related Functions


RANDOM - Uniform Distribution

Syntax

RANDOM ([Min=0[, Max=Min+1[, Seed]]])

In

Min - Minimum value to be returned (optional parameter with default equal to 0).

Max - Maximum value to be returned (optional parameter with default equal to Min+1).

Seed - Initialization of random number generator (optional start-up parameter with random default value).

Result

Uniformly distributed random number between Min and Max.

Examples

5 + RANDOM returns uniformly distributed random numbers between 5 and 6. This may also be expressed as:

RANDOM(5).

20 + 3*RANDOM returns uniformly distributed random numbers between 20 and 23. This can also be expressed as:

RANDOM(20, 23)

More Examples

Examples of Test Data Distributions

Group

Random Functions

Related functions

EXPRND, NORMAL, POISSON


REALC - Real part of complex number

Syntax

REALC(A([...,] 2))

In

A - Complex number or array of complex numbers in Cartesian format.

Result

The real part of A.

Examples

REALC([1, 2]) = 1

REALC([[1, 2], [3, 4]]) = [1, 3]

REALC(A) = A(1) 'Where A is a complex number'

Group

Complex Functions

Related functions

ABSC, ANGLEC, IMAGC


ROUND - Round Number to Nearest Integer

Syntax

ROUND (X)

In

X - Any number.

Result

X rounded to the nearest integer, according to the following formula:

ROUND(X) = IF(X>=0, FLOOR(X+0.5), CEIL(X-0.5))

Group

Conversion Functions

Related functions

CEIL, FLOOR, INT, FRAC


RUN - Run Number

Syntax

RUN

Result

One during the first run, two during the second run, etc.

Note

The function depends on run number.

A simulation will normally contain only one run. Using the Simulate Run Setup dialog box, however, several runs may be specified. Powersim will then automatically start a new simulation when the previous run is finished. This will continue until the desired number of runs are simulated. This feature may be used, for example, when performing sensitivity tests. The RUN function may be used to choose different test data for successive runs.

Examples

Examples of Test Data Distributions

Group

Miscellaneous Functions

Related functions

RUNCOUNT, TIME, STARTTIME, STOPTIME, TIMESTEP, ATSTART


RUNCOUNT - Number of Runs

Syntax

RUNCOUNT

Result

Number of runs, as defined in the Run Setup dialog box.

Examples

Examples of Test Data Distributions

Group

Miscellaneous Functions

Related functions

RUN


SAMPLE - Periodic Sample

Syntax

SAMPLE (Input, First, Interval[, Initial=0])

In

Input - Any numeric expression to be sampled (computational parameter).

First - First sampling time measured in the time unit of the simulation.

Interval - Sampling interval measured in the time unit of the simulation.

Initial - Value returned by SAMPLE until the first sampling time (optional start-up parameter with default equal to zero).

Result

SAMPLE is periodically set equal to Input and retains this value until the next sampling time. The first sample is taken at time First, and new samples are taken every Interval time units thereafter. SAMPLE returns the value of Initial until the first sample time.

Note

The function depends on TIME and on previous values of its first parameter.

Groups

History Functions , Time Related Functions

Related functions

SAMPLEIF, INIT, EULER, TIME

See also

Using the SAMPLE function


SAMPLEIF - Conditional Sample

Syntax

SAMPLEIF (Condition, Input[, Initial=0])

In

Condition - Conditional value True or False, which determines whether a sample is to be taken.

Input - Any numeric expression to be sampled (computational parameter).

Initial - Value to be returned by SAMPLEIF until the first time Condition is True (optional start-up parameter with default equal to zero).

Result

The value of Input at the most recent sampling time. Before the first sampling time, the value of Initial is returned.

Note

The function depends on previous values of its second parameter.

The relationship between SAMPLE and SAMPLEIF is the following:

SAMPLE(X,I,F,X0) = SAMPLEIF(TIMECYCLE(F,I),X,X0)

Group

History Functions , Conditional Functions

Related functions

SAMPLE, INIT, EULER, TIMEIS, TIMECYCLE

See also

Using the SAMPLEIF function


SCANEQ - Scan Vector for Equal Element

Syntax

SCANEQ(Vector(...), X [, SearchForLast=FALSE])

In

Vector - Vector to be scanned.

X - Any number.

SearchForLast - If True, scans from end of Vector, otherwise scans from beginning (optional parameter with default equal to False).

Result

The position (starting from 1) of the first (or last) element in Vector that is equal to X. If X is not an element of Vector, 0.0 is returned.

Group

Array Functions

Related functions

SCANNEQ, SCANLT, SCANLTEQ, SCANGT, SCANGTEQ


SCANGT - Scan Vector for Greater Element

Syntax

SCANGT(Vector(...), X [, SearchForLast=FALSE])

In

Vector - Vector to be scanned.

X - Any number.

SearchForLast - If True, scans from end of Vector, otherwise scans from beginning (optional parameter with default equal to False).

Result

The position (starting from 1) of the first (or last) element in Vector that is greater than X. If all elements of Vector are less than or equal to X, 0.0 is returned.

Group

Array Functions

Related functions

SCANEQ, SCANNEQ, SCANLT, SCANLTEQ, SCANGTEQ


SCANGTEQ - Scan Vector for Greater or Equal Element

Syntax

SCANGTEQ(Vector(...), X [, SearchForLast=FALSE])

In

Vector - Vector to be scanned.

X - Any number.

SearchForLast - If True, scans from end of Vector, otherwise scans from beginning (optional parameter with default equal to False).

Result

The position (starting from 1) of the first (or last) element in Vector that is greater than or equal to X. If all elements of Vector are less than X, 0.0 is returned.

Group

Array Functions

Related functions

SCANEQ, SCANNEQ, SCANLT, SCANLTEQ, SCANGT


SCANLT - Scan Vector for Smaller Element

Syntax

SCANLT(Vector(...), X [, SearchForLast=FALSE])

In

Vector - Vector to be scanned.

X - Any number.

SearchForLast - If True, scans from end of Vector, otherwise scans from beginning (optional parameter with default equal to False).

Result

The position (starting from 1) of the first (or last) element in Vector that is less than X. If all elements of Vector are greater than or equal to X, 0.0 is returned.

Group

Array Functions

Related functions

SCANEQ, SCANNEQ, SCANLTEQ, SCANGT, SCANGTEQ


SCANLTEQ - Scan Vector for Smaller or Equal Element

Syntax

SCANLTEQ(Vector(...), X [, SearchForLast=FALSE])

In

Vector - Vector to be scanned.

X - Any number.

SearchForLast - If True, scans from end of Vector, otherwise scans from beginning (optional parameter with default equal to False).

Result

The position (starting from 1) of the first (or last) element in Vector that is less than or equal to X. If all elements of Vector are greater than X, 0.0 is returned.

Group

Array Functions

Related functions

SCANEQ, SCANNEQ, SCANLT, SCANGT, SCANGTEQ


SCANNEQ - Scan Vector for Unequal Element

Syntax

SCANNEQ(Vector(...), X [, SearchForLast=FALSE])

In

Vector - Vector to be scanned.

X - Any number.

SearchForLast - If True, scans from end of Vector, otherwise scans from beginning (optional parameter with default equal to False).

Result

The position (starting from 1) of the first (or last) element in Vector that is not equal to X. If all elements of Vector are equal to X, 0.0 is returned.

Group

Array Functions

Related functions

SCANEQ, SCANLT, SCANLTEQ, SCANGT, SCANGTEQ


SECONDSTHISRUN - Seconds since start of current run

Syntax

SECONDSTHISRUN

Result

Number of seconds since current simulation run was started.

Group

Time Related Functions

Related functions

SECONDSTHISSTEP


SECONDSTHISSTEP - Seconds used simulating current time step

Syntax

SECONDSTHISSTEP

Result

Number of seconds used simulating this time step.

Group

Time Related Functions

Related functions

SECONDSTHISRUN


SELECTDECISION - Select decision value

Syntax

SELECTDECISION(Player, Decided, Assumed, Simulated, Dummy)

In

Player - Index into player dimension

Decided - Value decided by player

Assumed - Value assumed by fist player for this player

Simulated - Simulated decision variable for this player

Dummy - Decision value used for non-participating player

Result

One of the values Decided, Assumed, Simulated, or Dummy, depending on the value of Player, the current mode of the game (strategic or operational), the number of players, and the number of simulated players.

Group

Miscellaneous Functions

Example

aux 	Price(p=PlayerRange) = SELECTDECISION(INDEX(p), Decided(p), Assumed(p), Simulated(p), 0)


SHIFTCIF - Conditional Circular Shift of Vector Elements

Syntax

SHIFTCIF (Condition, Vector(N))

In

Condition - Conditional value True or False, which determines whether a shift is going to be performed.

Vector - Any level or constant vector variable.

Out

Vector - Unchanged or shifted, depending on the value of Condition. If shifted, the elements are changed in the following way:

vector[N] = vector[N-1]

...

vector[3] = vector[2]

vector[2] = vector[1]

vector[1] = vector[N]

This means that all elements are copied to the next position, except for the last element, which is copied to the first position, as illustrated below:

Result

The last element of Vector, i.e., Vector(N).

Note

The function has side-effects on the second parameter.

Groups

Array Functions , Conditional Functions

Related functions

SHIFTLIF , SHIFTLCNT - Linear Shift of Vector Elements

See also

Using the SHIFTCIF function


SHIFTLCNT - Linear Shift of Vector Elements

Syntax

SHIFTLCNT(Cnt, V(N) [, Input=0])

In

Cnt - Shift vector V this many positions to the right (a negative value means left shift),

V - Vector with N elements,

Input - Value to be shifted into emptied elements (optional input parameter),

Out

V - Unchanged or shifted, depending on Cnt.

Result

The sum of the elements shifted out of V.

Note

The function has side-effects on the second parameter.

This function handles shifts in both directions, and also fractional shifts, i.e., values of Count that are not whole numbers (integers).

SHIFTLCNT(1, V, 0) is equivalent to SHIFTLIF(TRUE, V).

For a constant DelayTime

SHIFTLCNT(ShiftCnt, DelayState, Input)

is equivalent to

DELAYPPL(Input, DelayTime, 0)

where ShifCnt = ELEMCOUNT(DelayState) / DelayTime * TIMESTEP and DelayState is a vector with all elements set to zero initially.

Group

Array Functions

Related functions

SHIFTLIF, SHIFTCIF


SHIFTLIF - Conditional Linear Shift of Vector Elements

Syntax

SHIFTLIF (Condition, Vector(N))

In

Condition - Conditional value True or False, which determines whether a shift is going to be performed.

Vector - Any level or constant vector variable.

Out

Vector - Unchanged or shifted, depending on the value of Condition. If shifted, the elements are changed in the following way:

vector[N] = vector[N-1]

...

vector[3] = vector[2]

vector[2] = vector[1]

vector[1] = 0

This means that all elements are copied to the next position, except for the last element, which is discarded. The first element is set to zero.

Result

The last element of Vector, i.e., Vector(N).

Note

The function has side-effects on the second parameter.

Example

A periodic shift may be achieved using TIMECYCLE when specifying the Condition parameter, for example, like this:

SHIFTCIF(TIMECYCLE(T, I), V)

Groups

Array Functions , Conditional Functions

Related functions

SHIFTCIF , SHIFTLCNT - Linear Shift of Vector Elements

See also

Using the SHIFTLIF function


SIGN - Sign of Number

Syntax

SIGN (X)

In

X - Any number.

Result

+1 if X is positive, -1 if X is negative, and 0 otherwise.

Example

The following is true:

SIGN(X) = IF(X < 0, -1, IF(X > 0, 1, 0))

Groups

Conversion Functions , Mathematical Functions


SIN - Sine

Syntax

SIN (Angle)

In

Angle - angle in radians.

Result

The sine of Angle.

Group

Trigonometric Functions

Related functions

COS, TAN, ARCSIN, SINH, DEGTORAD, GRADTORAD, PI


SINH - Hyperbolic Sine

Syntax

SINH (Value)

In

Value.

Result

The hyperbolic sine of input value.

Group

Trigonometric Functions

Related functions

COSH, TANH, SIN, DEGTORAD, GRADTORAD, PI


SINWAVE - Periodic Sine Wave

Syntax

SINWAVE (Amplitude, Period)

In

Amplitude - Amplitude of the wave.

Period - Period of the wave.

Result

A time-dependent sine wave, defined by the equation:

SINWAVE(A, P) = A * SIN(TIME*2*PI/P)

Example

The expression SINWAVE(2, 4) produces the graph below.

Note

The function depends on TIME.

Demo

Inventory Oscillations

Groups

Time Related Functions , Trigonometric Functions

Related functions

SIN, TIME, COSWAVE


SOUND - Output Sound

Syntax

SOUND (Input )

In

Input - Sound to be played. Value is rounded to the nearest integer, and used to choose a sound from the following table:

Input	Sound
-1	Beep using the computer speaker
0	No sound
1	SystemAsterisk.
2	SystemExclamation
3	SystemHand
4	SystemQuestion
5	SystemDefault
Numbers outside the above range are treated as -1.

Result

The value of Input.

Note

Input values 1 through 5 choose a sound according to the [sounds] section of WIN.INI.

Group

Miscellaneous Functions


SPROD - Scalar Vector Product

Syntax

SPROD (A(N), B(N))

In

A, B - Vector expressions with equal number of elements.

Result

The scalar product of A and B, as defined by the following Powersim expression:

SUM(i=1..N; A(i) * B(i))

Groups

Array Functions , Mathematical Functions

Related functions

ARRPROD, MATRIXPROD, PRODC, PRODCR, PRODRC, VECTPROD3D


SQRT - Square Root

Syntax

SQRT (X)

In

X - Any non-negative number.

Result

The square root of X.

Example

The relationship between SQRT and ^ is:

SQRT(X) = X ^ 0.5

Group

Mathematical Functions


STARTTIME - Start Time of Simulation

Syntax

STARTTIME

Result

The start time of the simulation, as defined in the Simulation Setup dialog box.

Group

Time Related Functions

Related functions

STOPTIME, TIME, TIMESTEP, ATSTART


STDDEV - Standard Deviation

Syntax

STDDEV (X1, X2, ...Xn)

In

X1, X2, ...Xn - Any number.

Result

The standard deviation of the arguments, as defined by:

Group

Statistical Functions

Related functions

ARRSTDDEV


STEP - Step Function

Syntax

STEP (Height, StepTime)

In

Height - Numeric expression determining step height.

StepTime - Numeric expression determining time of step.

Result

Zero if TIME is less than StepTime, and Height otherwise.

Example

The function STEP(2, 5) produces the graph below.

Note

The function depends on TIME.

Demo

Inventory Oscillations

Group

Time Related Functions

Related functions

RAMP, PULSE


STOPIF - Stop Simulation

Syntax

STOPIF(Condition)

In

Condition - When this argument becomes True, the simulation and all remaining runs are stopped (The number of runs is defined in the Simulate Run Setup dialog box).

Result

The value of Condition.

Group

Control Functions

Related functions

PAUSEIF, PAUSEWHILE, STOPRUNIF


STOPRUNIF - Stop Current Run

Syntax

STOPRUNIF(Condition)

In

Condition - When this argument becomes True, the current simulation run is stopped and the next run is started, if any (The number of runs is defined in the Simulate Run Setup dialog box).

Result

The value of Condition.

Group

Control Functions

Related functions

PAUSEIF, PAUSEWHILE, STOPIF


STOPTIME - Stop Time of Simulation

Syntax

STOPTIME

Result

The stop time of the simulation, as defined in the Simulation Setup dialog box.

Group

Time Related Functions

Related functions

STARTTIME, TIME, TIMESTEP, ATSTART


STRATEGICMODE - Test if game is in strategic mode

Syntax

STRATEGICMODE

Result

True if the model is running in the strategic mode, and False if the model runs in operational mode. The strategic mode is entered when the user presses Try Decisions in the Game Control panel, while pressing Accept Decisions enters the operational mode.

Group

Miscellaneous Functions

Related functions

SELECTDECISION


SUM - Sum of Expressions Over Indices

Syntax

SUM (Dim1, Dim2, ...,DimN ; Expression)

In

Dim1, Dim2, ...,DimN - Definition of dimensions to be "summed over". Each dimension is defined as an optional index variable followed by an equal sign and a range. Several dimensions may be defined, separated by commas.

Expression - Any expression, possibly referring to indices of Dim1, Dim2, ...,DimN.

Result

The sum of the values of Expression over the dimensions Dim1, Dim2, ...,DimN.

Note

The SUM function does not follow the normal syntax of a function, as dimensions may be defined (as for array variables). Also note the semicolon (;) separating the dimensions and the expression.

The relationship between a conventional mathematical notation and the SUM function is illustrated below:

Examples

The expression SUM(i=1..3; A(i)) is the same as the following:

A(1) + A(2) + A(3)

The following expressions are also true:

SUM(1..3; 2) = 6

SUM(i=3..9; INDEX(i)) = 42

Group

Built-in Functions

Related functions

ADD, ADDCR, ADDRC, ARRSUM

See also

Using Built-in functions


TAN - Tangent

Syntax

TAN (Angle)

In

Angle - Angle in radians.

Result

The tangent of Angle.

Group

Trigonometric Functions

Related functions

COS, SIN ARCTAN, TANH, DEGTORAD, GRADTORAD, PI


TANH - Hyperbolic Tangent

Syntax

TANH (Value)

In

Value.

Result

The hyperbolic tangent of input value.

Group

Trigonometric Functions

Related functions

COSH, SINH, TAN, DEGTORAD, GRADTORAD, PI


TIME - Current Time of Simulation

Syntax

TIME

Result

The current time of the simulation, starting at the value of STARTTIME, and incremented by TIMESTEP for each step of the simulation.

Note

The function depends on TIME (obviously).

Group

Time Related Functions

Related functions

STARTTIME, STOPTIME, TIMESTEP, ATSTART


TIMECYCLE - Test for Cyclic Time or Time Interval

Syntax

TIMECYCLE (First, Interval[, Duration=TIMESTEP])

In

First - First time to check for.

Interval - Time between intervals to check for.

Duration - Length of interval (optional parameter with default equal to zero).

Result

True if current simulation time is within an interval from First + k * Interval to First + k * Interval + Duration, where k is a non-negative integer.

Note

The function depends on TIME and TIMESTEP.

When testing against TIME the size of the time step is taken into account.

Group

Time Related Functions

Related functions

TIMEIS, TIME, TRUE, FALSE


TIMEIS - Test for Given Time or Time Interval

Syntax

TIMEIS (PointInTime[, Duration=0])

In

PointInTime - Numeric expression determining time to be tested for.

Duration - Duration of time interval to test for (optional parameter with default value equal to zero).

Result

True if current time lies in the interval PointInTime to PointInTime+Duration.

Note

The function depends on TIME and TIMESTEP.

The expression TIME=T does not always give the same result as TIMEIS(T) because the TIMEIS function takes into account the size of the time step.

Group

Time Related Functions

Related functions

TIMECYCLE, TIME, TRUE, FALSE, ATSTART


TIMESTEP - Time Step of Simulation

Syntax

TIMESTEP

Result

The time step of the simulation, as defined in the Simulation Setup dialog box.

Group

Time Related Functions

Related functions

TIME, STARTTIME, STOPTIME, PULSE, PULSEIF


TRANSPOSE - Transpose Matrix

Syntax

TRANSPOSE (A(M,N))

In

A - Two-dimensional array expression.

Result

Two-dimensional N x M array (matrix) where the rows and columns of M are exchanged.

Equations

The transposed matrix TA of a matrix A may be found like this:

aux	A(M, N) = ...

aux	TA(i=1..N, j=1..M) = A(j, i)

Groups

Array Functions , Mathematical Functions

Related functions

MATRIXPROD, TRANSPOSEC


TRANSPOSEC - Transposed matrix of complex numbers

Syntax

TRANSPOSEC(A([[M,] N,] 2))

In

A - Complex number, vector or matrix in Cartesian format.

Result

A transposed, i.e., a matrix R([N, [M,]] 2) where R(i, j, 1..2) = A(j, i, 1..2)

Note

If A has less than three dimensions, A is returned unchanged.

Group

Complex Functions

Related functions

TRANSPOSE


TREND - Trend Extrapolation

Syntax

TREND (Input, AveragingTime[, Initial=0])

In

Input - Numeric expression to be examined over time.

AveragingTime - Averaging time.

Initial - Initial value of the TREND function (optional start-up parameter that defaults to zero).

Result

The first order exponential average change rate of Input, using the given AveragingTime. The value is expressed as the relative change in Input per time unit.

Diagram

The function may be modeled like this:

	init AverageOfInput = ... aux AveragingTime = ... aux Input = ... flow AverageOfInput = +dt*(ChangeInInput) aux ChangeInInput = (Input-AverageOfInput) / AveragingTime aux TrendInInput = ChangeInInput / AverageOfInput
Notes

•	The function builds on the structure of the information delay function (see DELAYINF).

•	The function depends on previous values of its first parameter.

Group

History Functions


TRUE - Logical True

Syntax

TRUE

Result

The value one.

Note

When used in a condition, any value which rounds to something different from zero is regarded to be true.

Group

Logical Functions

Related functions

FALSE, BOOL


VECTLEN - Vector Length

Syntax

VECTLEN (A(N))

In

A - Any vector expression.

Result

The length of a vector, i.e., the square root of the sums of the squares of the absolute values of the elements, as defined by the Powersim expression:

SQRT(SUM(i=1..N; A(i)^2))

Groups

Array Functions , Mathematical Functions

Related functions

ABS, ABSC, ELEMCOUNT, HYPOT


VECTOR - Create Vector

Syntax

VECTOR(Elem1, Elem2, ..., ElemN)

In

Elem1, Elem2, ..., ElemN - Vector elements. The elements may either be scalars or arrays with equal dimensions.

Result

Array with elements Elem1, Elem2, ..., ElemN . The resulting array will have one more dimension than each of the elements Elemi .

Group

Array Functions

Related functions

LOOKUP


VECTPROD3D - 3D Vector Cross Product

Syntax

VECTPROD3D (A(3), B(3))

In

A, B - Vector expressions with three elements.

Result

A vector with three elements, representing the cross product of A and B.

Groups

Array Functions , Mathematical Functions

Related functions

ARRPROD, MATRIXPROD, PRODC, PRODCR, PRODRC, SPROD


WHEN - Guard Operator

Syntax

A WHEN B

In

A - Any expression.

B - Any constraint, for example, an expression involving index variables, range references, and literal integers.

Result

A if B is true, and undefined otherwise.

Note

Alternative name of the guard operator (|).

Group

Built-in Functions

Related functions

; - Constraint operator , | - Guard Operator , BUT

See also

Using Built-in functions


XOR - Exclusive Logical Or

Syntax

A XOR B

In

A, B - Logical value, True or False.

Result

True if one, and only one, of A and B is True, and False otherwise. In other words:

(A AND NOT B) OR (NOT A AND B)

or simply:

BOOL(A) <> BOOL(B)

Note

When using <> and = on logical values, it is a good practice to use BOOL on the values first. This ensures that True values are set to one. The example below illustrates this point, as the two expressions do not produce the same result:

3 = 4 -- is false

BOOL(3) = BOOL(4) -- is true

A related way of expressing A XOR B is: A + B - 2 * A * B.

Group

Logical Functions

Related functions

XOR, AND, NOT, BOOL, TRUE, FALSE


How to use Powersim Constructor

The following topics give you step-by-step directions and examples to help you learn Powersim Constructor and introduce you to the field of dynamic simulation.

  Introduction

  Building and Simulating Models

  Using the Diagram Editor

  Using Arrays

  Using Powersim Objects

  Connecting to other Applications

  Using Powersim Functions

  Creating Multi-User Simulation Games

  Frequently Asked Questions

  Methodological Issues


How to use Powersim_EXPANDED
How to use Powersim Constructor

The following topics give you step-by-step directions and examples to help you learn Powersim Constructor and introduce you to the field of dynamic simulation.

  Introduction

  Building and Simulating Models

  Flow Diagram Modeling

  Simulating

  Using the Diagram Editor

  User Environment

  Views

  Editing Models

  Manipulating Diagram Components

  Defining and using number formats

  Context Sensitive Help

  Using Arrays

  How to Use Arrays

  When to Use Arrays

  Advanced Use of Arrays

  Creating an Array Version of the Capital Model

  Using Powersim Objects

  Using Dynamic Objects

  Using Static Objects

  Using Transfer Objects

  Connecting to other Applications

  Using DDE

  Using the Powersim API

  Using Powersim Functions

  Overview of Functions and Demo models

  Array Functions

  Built-in Functions

  Complex Functions

  Miscellaneous Functions

  Financial Functions

  History Functions

  Conditional Functions

  Control Functions

  Creating Multi-User Simulation Games

  Frequently Asked Questions

Methodological Issues


Introduction to Powersim
About Powersim Constructor 2.5

A short introduction to some fundamentals of the software package.

History of new features and changes

  System Requirements

  Powersim Variants

  Copyright Information, etc.

  Acknowledgments

  Powersim Support Services

  A history of new features and changes


Sample Models

Your Powersim package contains a number of sample simulation models. They are divided into two categories:

•	Application samples, which are examples of how Powersim models can be used to solve real problems. They are found in Powersim\Samples\Applicat.

•	User's Guide samples, which are models referenced in the manuals and on-line help. They are found in Powersim\Samples\UserGuid.

See also

  Using Application Samples

  Using User's Guide Samples


Using Application Samples

To open an application sample from Powersim

1	Open Powersim by choosing the Powersim icon [image] .

2	Select the open icon [image] from the commandbar. The Open dialog box appears.

3	Open the Samples\Applicat directory.

4	Select a model from the File Name list and click OK.

To open a model or its documentation directly from this help program

Click on a red file name in the list to open a model or click on a descriptive text to open a model's help file:

Model	Problem area
FINANCE.SIM	Fixed interest rate loan
INVENTOR.SIM	Oscillations in inventory
MORALE.SIM	Morale and its impact on financial performance
POPULATN.SIM	Urban population
PRODUCT.SIM	Product life cycle
PROJMGMT.SIM	Project management, human resources
STOCKMKT.SIM	Stock market game; deciding whether to buy or sell shares of a single stock
WAVEFUN.SIM	Model for studying general properties of waves
The application samples found on the Powersim disks should help you get some ideas on how simulators can be applied within your area of interest. Along with each model comes a help file containing a short documentation of the model.

To open the help file of an application sample

1	First open the model document itself (see above).

2	From the Help menu in Powersim, choose Current Document ... (if that item is available).

3	A help file for the current application model should now open.

Note If the menu item Help Current Document ... is disabled it means that there exists no help file for the model that is currently opn.

See also

Sample Models


Using User's Guide Samples

The user's guide samples are best used together with the manuals and on-line help. Whenever a description or example in the documentation refers to a specific model, you can open this model in Powersim and try it out.

To open a user's guide sample from Powersim

1	Open Powersim by choosing the Powersim icon [image] .

2	Select the open icon [image] from the commandbar. The Open dialog box appears.

3	Open the Samples\User's Guide directory.

4	Select a model from the File Name list and click OK.


System Requirements

The following equipment is required to run Powersim:

•	IBM compatible PC with 80386 processor or greater

•	Windows 3.1x, 'NT or '95

•	4-8 Mb RAM or more

•	Hard Disk with minimum 10-20 Mb free space

•	Mouse


Powersim Variants and Add-Ons
Powersim Variants

Powersim is available in four variants:

•	Standard: The authoring version for building and running simulation models, containing the most widely used features

•	Professional: The full simulator development package, containing all advanced features

•	Run-Time: A simplified package for running ready-made models and customized simulators

•	Demo: A demonstration version for evaluation purposes only (see Powersim Demo)


Powersim Demo

Powersim Demo is the demonstration version of Powersim. It is legal for evaluation purposes only. It may not be used for any educational, scientific, or commercial purposes.

Powersim Demo has certain limitations, deliberately put into the program to prevent illegal use:

•	Powersim Demo may not be used to save models that contain more than 25 variables or 75 array elements.

•	You may not copy more than 25 variables from any model.

•	A regular copy area operation (using the right mouse button) may not be performed on models with more than 25 variables, since copying an area actually puts the entire model on the clipboard (OLE). Pictures may still be copied from an area by using Shift+Ctrl+C (see also: Copy (Edit menu) ).

Apart from the limitations mentioned above, Powersim Demo has the same functionality as the Powersim Professional package.


Copyright Information, etc.

Information on this document is subject to change without notice and does not represent a commitment on the part of Powersim Corporation. The software described in this document is furnished under a license agreement. The software may be used or copied only in accordance with the terms of the agreement. It is against the law to copy the software on any medium except as specifically allowed in the license agreement. The purchaser may make one copy of the software for backup purposes. No part of this manual may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or information recording and retrieval systems, for any purpose other than the purchaser's personal use, without the express written permission of Powersim Corporation.

© Copyright Powersim Corporation, 1993-1996. All rights reserved.

Powersim® is a registered trademark and The Essential Tool for Creating Business Simulators is a trademark of Powersim Corporation.

Hewlett-Packard and HP are registered trademarks of Hewlett-Packard Company.

IBM is a registered trademark of International Business Machines Corporation.

Lotus and 1-2-3 are registered trademarks of Lotus Development Corporation.

MS-DOS, Microsoft Excel, and Visual C++ are registered trademarks and Windows is a trademark of Microsoft Corporation.

Professional Dynamo is a trademark of Pugh-Roberts Associates, Inc.

Stella and ithink are trademarks of High Performance Systems, Inc.


Acknowledgments

Powersim was designed and developed by:

•	Arne Kråkenes, Arne-Helge Byrknes, Bjørn Arild Wangenstein Baugstø, Magne Myrtveit, and Tormod Lunestad

In addition, the following persons have worked on documentation, demo models, and additional material for the Powersim Constructor package:

•	Atle Geitung, Daniel Angelakis, David Bridgeland, Helge Bauge, Hilde Martinussen, Håkon Vatnøy, Jennifer Cover, Jon Bruvoll, Jon-Inge Paulsen, Knut Vavik, Kristian Øpstad, Lucy Keller, Olav Svennevik, Ottar Henanger, Per Ivar Kjærgaard, Raymond Capece, Rolf Hjelmtveit, Shannon Louise Brooks, Steinar Moen, Terje Rørmark, Trond Leikvoll, and Umar Imrana Ahmed

A large number of users have contributed to the success of Powersim by providing test reports and constructive input during the software design and implementation phases. We thank you all!

We also want to thank our dealers for feedback and various kinds of assistance on the Powersim documentation and promotion materials.


Using the Auto Pause Facility

Sometimes you wish to pause a simulation run at a specific point in time in order to change a parameter or inspect simulation results at that point. Powersim offers an easy way of doing this: Auto Pause.

To automatically pause a simulation

1	Choose Run Setup from the Simulate menu.

2	Type a number, let's say 5, into the Every <n> Time Units text box.

3	Click OK.

When the simulation reaches time 5, Powersim will now automatically switch pause on. The Pause button on the commandbar (if present) will be set to a pushed state and the Pause entry on the Simulate menu will become checked. When you switch pause off again, the simulation will run for another auto pause interval. In this way you may run a simulation in desired "time portions" until the stop time is reached.


Adjusting Parameters

In simulating mode you can use the pointer tool to adjust parameters of the model by using the buttons of slider/bar or gauge objects that control the parameters.


Using the Diagram Editor

  User Environment

  Overview

  Commandbar Buttons

  Toolbar Buttons

  Pushing a Toolbar Button

  Views

  Using Diagram View

  Using Equations View

  Displaying a Model in Both Views Simultaneously

  Editing Models

  Creating a new model component

  Creating a new flow object

  Creating a corner of a flow arrow

  Establishing a Link

  Divided Links

  Defining variables

  Confirming the definition of a variable

  Defining Unit of Measure

  Manipulating Diagram Components

  Direct manipulation of objects

  Creating Areas

  Opening the Definition Editor

  Moving Objects

  Adjusting Objects

  Using the Grid

  Adding Variables to Dynamic Objects using Drag-and-Drop

  Displaying Information About a Variable in the Statusbar

  Creating a new transfer-, static-, or dynamic object

  Selecting and Deselecting Objects

  Changing the sorting order of variables lists

  Black and white printing of a colored model inside another document

  Defining and using number formats

  Setting the default number format

  Defining and setting individual number formats

  Where does Powersim keep user defined numeric formats?

  Context Sensitive Help

  Opening Dialog Box Help

  Opening Function Help

  Opening Error Help


User Environment

Powersim's application window displays the menus and provides the workspace for any document used within the application.

  Overview

  Commandbar Buttons

  Toolbar Buttons

  Pushing a Toolbar Button


Overview

Note	Click in the figure above to display a description of the different components of the application window


Commandbar Buttons

File and editing commands

New	Open	Save	Undo	Cut	Copy	Paste
Zoom and model formatting

Zoom out	Zoom in	Zoom 100%	Zoom to fit	Straig- hten	Rotate Name	Move Valve
Simulation control and options

Run	Run Step	Pause on/off	Stop	Options


Toolbar Buttons

Model object tools

Level	Auxiliary	Cons- tant	Flow- with- rate	Flow	Link	Delayed Link
Editing tools

Camera	Eraser	Pointer
Transfer object tools

Chain	DDE	Archive	Network Game
Static object tools

Text	Frame	Picture	Line
Dynamic object tools

Number	Slider/ Bar	Time Table	Time Graph	Scatter Graph	Button	Array Graph	Gauge	Multimedia	Command button


Pushing a Toolbar Button

When you push a button in the toolbar, or make a corresponding choice in the Tools menu, the cursor will change to a symbol for the selected tool when you move the mouse into the workspace. The new cursor signals that pushing the left mouse button somewhere in the diagram will create a new instance of the entity associated with the tool.


Views

Powersim provides two ways to view your document on the screen: diagram view and equations view. This option is set via the two menu entries Diagram and Equations, which act like a pair of radio buttons. This means that only one of them is chosen at a time. A dot next to a command in the View menu indicates the active window's current view.

  Using Diagram View

  Using Equations View

  Displaying a Model in Both Views Simultaneously


Using Diagram View

A window in diagram view displays a model's structure using the flow diagram symbols. It also displays dynamic, static and transfer objects according to the settings in the Diagram View options box. These settings determine which object categories are shown and which are hidden. Diagram view is the default selection for new documents.


Using Equations View

The purpose of the equations view is to provide you an equation based overview of a model. The ability to copy the equations and paste them into other applications, such as word processors, makes this view useful for documenting models. An equations view window shows a text based representation of the current model's equation structure. The non-model categories of Powersim objects, such as time graph, picture, etc., have no textual representation and are therefore always hidden in equations view.

Windows in equations view are read-only, meaning that you cannot add or remove variables, flows or links while in the view. You can, however, open the Define Variable dialog box and redefine variables while in equations view.


Displaying a Model in Both Views Simultaneously

To display a model in both views simultaneously

1	Open the model in diagram view

2	Choose Window New Window

3	Choose Window Tile

4	Activate the second diagram window

5	Switch on View Equations

All model equations will now be listed in the new window. If there are both diagram windows and equations windows open for the same document, the equations windows are automatically updated when changes are made in a diagram window.


Editing Models

  Creating a new model component

  Creating a new flow object

  Creating a corner of a flow arrow

  Establishing a Link

  Divided Links

  Defining variables

  Confirming the definition of a variable

  Defining Unit of Measure


Creating a new model component

To create a new model component

1	Select the desired tool by clicking in the toolbar or making a selection in the Tools menu.

2	Click in the diagram to create and position the new variable, link, or flow.


Creating a new flow object
Creating a new flow

To create a new flow

1	Press the left mouse button with the flow cursor in the position where you want the flow to start. If the flow is to run out from a level, press the button with the cursor pointing in the center of the level.

2	With the mouse button still pressed, drag the flow arrow to its target point and release the button. If the flow is to run into a level, release the button with the cursor pointing inside the level (the target level changes color when you are inside).


Creating a corner of a flow arrow

To create a corner of a flow arrow

1	While dragging a flow with the left mouse button pressed, move the arrowhead to the position where you want to place the corner.

2	Click the right mouse button, or hit Insert, without releasing the left button.

3	Continue dragging the flow in a new direction.


Deleting a corner on a flow arrow
Deleting a corner of a flow arrow

To delete a corner of a flow arrow

1	While dragging a flow with the left mouse button pressed, move the arrowhead close to the corner you want to delete.

2	Click the right mouse button, or hit Delete without releasing the left button.


Establishing a Link

To establish a link from one variable to another

1	Select the link tool

2	Push the left mouse button with the cursor inside From_Var

3	With the button still pressed, move the cursor into To_Var

4	Release the button

Link between two variables


Divided Links

Links may be divided into many branches (see figure below).

To share one link between several target variables

1	Drag the link to the position where you want to put the "division point".

2	Release the left mouse button while pressing Shift or click the right mouse button with the left mouse button still pressed.

3	New links may be dragged from the division point to each of the target variables.


Defining variables

After creating a variable and connecting its input links, you are ready to define it. Defining a variable normally means entering an initial value (levels), an expression (auxiliaries), or a literal value (constants), in the Definition text box of the Define Variable dialog box. Listed below are examples of variable definitions:

Variable type	Definition	Definition type
Level	2000	initial value
Auxiliary	Population * Birth_Fraction	expression
Constant	0.05	literal value


Confirming the definition of a variable

When you have completed the definition of a variable in the Define Variable dialog box, you should confirm it.

To confirm a definition do one of the following

•	Push the Set button.

•	Push the OK button. This closes the dialog box as well.

•	Select another variable from the Variable list. You will then be asked to confirm the changes made to the current variable.


Defining Unit of Measure

To define a unit expression for the current variable, do one of the following

•	Make a selection among the predefined expressions in the Unit of Measure list in the Define Variable dialog box, or

•	Enter the unit expression into the Unit of Measure list header.

To define new units

1	Close the Define Variable dialog box.

2	Select Define Unit from the Edit menu.


Manipulating Diagram Components

  Direct manipulation of objects

  Direct text editing

  Inputting values while editing on a model

  Avoiding undesired direct object manipulation

  Creating Areas

  Opening the Definition Editor

  Moving Objects

  Adjusting Objects

  Using the Grid

  Adding Variables to Dynamic Objects using Drag-and-Drop

  Displaying Information About a Variable in the Statusbar

  Creating a new transfer-, static-, or dynamic object

  Selecting and Deselecting Objects

  Changing the sorting order of variables lists

  Black and white printing of a colored model inside another document


Direct manipulation of objects

Based on the user interface design principle of direct manipulation, Powersim now allows you to perform some frequent editing operations directly in the diagram, without having to open a dialog box. Examples include typing in the title of a dynamic object and setting initial values of number, bar, button, and array graph objects.

  Direct text editing

  Inputting values while editing on a model

  Avoiding undesired direct object manipulation


Direct text editing

As an example, let us define a text object displaying the text "Market Sector".

To define a text object displaying a text

1	Choose the Text object from the toolbar or the Tools menu.

2	Deposit the object in the diagram using the mouse.

3	Click inside the text of the text object, which must be selected (indicated by handles) [image].

4	A frame will be drawn around the text. You can now enter the new text directly into the object. Type "Market Sector" [image].

5	Hit Return to end text entry. (You can click Esc to cancel editing.) Windows 95 users can also click outside the text frame to end the edit operation. To force a new line inside the text frame, hit Ctrl + Return.

As you type into a direct text entry frame, the frame will expand to enclose the text you enter. You can start a new line by pressing Return. When clicking outside the text frame, the object containing the text will be reformatted. If the text should disappear in full or in part, you may have entered a text that is too big for the object. Try enlarging the object by dragging one of its sizing handles.

For text objects it is possible to switch on Adjust object size to fit text. This is useful if you want the text frame to enclose the text exactly, or if you do not want the text to have a frame at all.

Note	Not all texts can be edited directly, for example the tick marks along the axis of a time graph.

To check if a text can be edited directly

1	Select the object containing the text.

2	Move the mouse cursor above the text.

3	If the cursor turns into a caret ( [image]), the text can be edited directly by pushing the left mouse button and typing on the keyboard.

See also

Avoiding undesired direct object manipulation


Inputting values while editing on a model

Value input is normally done during simulation by dragging sliders, pressing buttons, moving the control points of an array graph, etc. Some parameters can be set also when the model is in edit mode. One such parameter is the Play parameter, which you find in the Control "model". Below we'll see how you can start a simulation by pressing on a button in the diagram.

To define a button that will start the simulation when pressed

1	Choose the button object from the toolbar or the Tools menu.

2	Create a button object in the diagram by clicking inside the diagram window with the mouse.

3	Double-click on the button object to open the Define Button dialog box [image].

4	Choose Control in the Models list.

5	Choose Control.Play in the Variables list.

6	Press Add to copy Control.Play to the Parameters list.

7	Choose Control.Play in the Parameters list.

8	Choose None in the On Press combo box.

9	Choose None in the On Repeat combo box.

10	Choose Toggle in the On Release combo box. This will toggle the value of Control.Play whenever the button is released. To toggle means to exchange the values zero and one.

11	Type Start in the Text field of the Button group.

12	Choose 2-stats in the Possible States combo box.

13	Press OK.

The diagram should now look like this.

To start the simulation by pressing a button in the diagram

1	Create a button as described in the previous section.

2	Make sure the button object is selected.

3	Press inside the button labeled Start.

If the button object is not selected when you click on Start, the object will become selected. The next time you click, the button will be activated. In this case the simulation will start.

It the edit access is switched off, it will not be possible to select objects; as they cannot be edited anyway. In the runtime version of Powersim models will never have edit access. Pressing a button in a model with edit access off, will activate the button even if the object is not selected.

See also

Avoiding undesired direct object manipulation


Avoiding undesired direct object manipulation

Clicking inside certain areas of an object can start a direct editing operation. Assume that we want to open the Define Button dialog box by double-clicking on the Start button described in the above example. If the button object is already selected, a click inside Start will activate the button, and start the simulation; which is not what we wanted this time.

One possibility is to double-click outside the area covered by the push button Start, as displayed below:

Mouse actions on the object border goes to the object, while mouse actions inside Start goes to the push button, as long as the object is selected.

This works fine if you have a good grip on your mouse, and the button object is defined with a frame. What would you do if the object looked like this?

This object has no border, so all mouse actions inside the object go to the Start button

Here we have used the Background button of Define Button, and set the border style to None.

One thing you can do, is to use a menu command instead of a mouse action to open the Define Button dialog box. With the Start button selected you can give the Edit Define Object command, or just press the RETURN key to open the Define Button dialog box.

You can also take advantage of the fact that direct manipulation of object components does not take place on objects that are not selected (i.e., displayed without sizing handles). If an object is selected, you can click in the diagram outside the object to deselect the object.

Mouse commands to an unselected object go to the object, and not to object sub components, like individual push buttons inside a button object, for example.

Now you can double click anywhere inside the object to open the definition box. If you want to move the object, you can point the mouse cursor anywhere inside an unselected object and drag the object to a new position. You can click anywhere inside an unselected object to select it. (For text and picture objects you must hit the border or the text, or you can drag a selection frame around the object.)


Creating Areas

To copy parts of diagrams as embedded objects, linked objects, bitmaps or pictures (for example, for using them as figures in word processor documents) you must first create an area.

To create an area

1	Select the pointer tool

2	Drag a rectangle using the right mouse button

A dotted rectangle indicates an area. The area remains until you select an object or click on the diagram background.

Note	Creating an area will not deselect selected objects. As a result, an area may contain objects that are selected. Further, the copy command will still operate on the area. Consequently, if you wish to copy the objects themselves, and not just an image of the objects, you should not use an area.

Note 	Areas cannot be pasted back into a diagram. An area can be pasted into a picture object, or into applications that allow pasting of embedded objects, linked objects, bitmaps, or metafiles.


Opening the Definition Editor

To bring up an object's Define dialog box

•	Double-click on the object with the left mouse button, or

•	Select the object and choose Edit Define Object

Note	Links and flows, do not have their own definition editor. Variables (levels, auxiliaries, and constants) share the same definition editor, namely the Define Variable dialog box.


Moving Objects

To move selected objects in a diagram

1	Point at the selection with the mouse pointer

2	Press the left button when the cursor is a pointing hand

3	Keep the button pressed

4	Move the selection to the target position

5	Release the button


Adjusting Objects

In editing mode you can use the pointer tool to adjust the Bézier curves of links and lines, or adjust the extent of flow pipes.

To adjust a link, a line, or a flow object

1	Select the object that you want to adjust

2	Press the left mouse button in one of the filled handles of the selected object

3	Move the handle to the desired angle or position

4	Release the button.


Using the Grid

Some users find it easier to position and adjust objects when the grid option is switched on.

To turn on the grid

1	Choose Format Options.

2	Choose Diagram Editing.

3	Check Snap to Grid.

4	Choose a grid unit, for example, Points.

5	Enter a number, for example 5, for horizontal and vertical grid.

6	If you want to keep this as your default grid setting, press Use as Default.

7	Press OK.


Adding Variables to Dynamic Objects using Drag-and-Drop
Adding Variables to Dynamic or Transfer Objects using Drag-and-Drop

Variables can be added to a dynamic object's parameter list by dragging them into the object symbol using the pointer.

To add variables to a dynamic or transfer object

1	Select the desired variables using the pointer tool and keep the left mouse button pressed

2	With the left mouse button still pressed, move the cursor into the target object

3	Release the left mouse button. The selected variables are added to the object's parameter list, if possible.

Note	Pressing Shift or Ctrl while releasing the left mouse button will replace the contents of the object's parameter list with the selected variables.


Displaying Information About a Variable in the Statusbar

To display information about a variable in the statusbar

1	Point inside a variable

2	Press the right mouse button

In editing mode the statusbar will display the variable's definition. In simulating mode the statusbar will display the variable's value.


Creating a new transfer-, static-, or dynamic object

To create a new nonmodel object

1	Select the desired object tool

2	Move the cursor to the desired position in the diagram and do one of the following:

•	Click the left mouse button, or

•	Press the left mouse button and drag the object out to desired size


Selecting and Deselecting Objects

When Powersim is in editing mode, you can use the mouse pointer to select or deselect objects in the diagram. This can be done in several ways:

•	Clicking with the left mouse button inside an object selects the object and deselects other selected objects.

•	Clicking with the left mouse button on the diagram background removes all selections.

•	Clicking with the left mouse button inside an object while pressing Shift toggles the selection state of that object on/off, but does not deselect other selected objects.

•	Dragging with the left mouse button around objects, selects the objects inside the rectangular area and deselects other selected objects.

•	Dragging with the left mouse button around objects while pressing Shift, toggles the selection state of objects inside the rectangular area, but does not deselect other selected objects.

In simulating mode the pointer can be used to manipulate input objects or to adjust the cell width of tables.


Changing the sorting order of variables lists

To change the sorting order of the variable list, used in the Define Variables dialog box and in the dialog boxes for defining dynamic objects, open the General Options dialog box and change the setting of Variable List Sorting.


Black and white printing of a colored model inside another document

When printing directly from Powersim to a black and white printer, text and outlines is always printed as white, while interiors are prnted as white. This always gives you a legible output. If you copy part of a diagram to a document in another application, for example in a word processor, you can paste the diagram either as a bitmap or as a picture.

If you paste a model as a bitmap, colors will be output as gray scale when printing the document in black and white.

If you paste as picture, text will be printed as black on a B/W printer, except when the text color is set to 100% white in the Powersim model. This means, for example, that yellow text on a red background will print as black text on a very dark background.

Result of printing a model directly from Powersim on a black and white printer:

Object color	Printed color
white text	black
non-white text	black
pattern filled background	white
solid filled background	white
gradient filled background	white
line, any color	black

Result of printing a model bitmap in a document on a black and white printer:

Object color	Printed color
white text	white
non-white text	gray scale
pattern filled background	gray scale pattern
solid filled background	gray scale
gradient filled background	gray scale gradient fill
line, any color	gray scale

Result of printing a model picture in a document on a black and white printer:

Object color	Printed color
white text	white
non-white text	black
pattern filled background	black and white pattern
solid filled background	gray scale
gradient filled background	gray scale gradient fill
line, any color	gray scale

Below are examples of a yellow text on a red background printed in black and white:

Printed from Powersim	Printed as bitmap	Printed as picture


Defining and using number formats

Several dynamic objects can display values as numbers. The number object displays a single value; the time table object displays rows or columns with numbers representing time series with data; the time graph, scatter graph, array graph, and slider/bar have axis with numbers representing scale and tick labels.

  Setting the default number format

  Defining and setting individual number formats

  Where does Powersim keep user defined numeric formats?

See also

  Number Formatting


Setting the default number format

The settings of the General category of the Format Options dialog box determines how numbers will be displayed as a default, i.e., when now explicit number formatting has been set. You can choose between the following formats:

1,234.5	Comma is thousand separator. Period is decimal separator.
1.234,5	Period is thousand separator. Comma is decimal separator.
1234.5	No thousand separator. Period is decimal separator.
1234,5	No thousand separator. Comma is decimal separator.
From Control Panel	The national settings for decimal separator and thousand separator will be used. These settings are taken from the Control Panel.


Defining and setting individual number formats

Let us, as an example, make a number box displaying TIME during simulation. Start out by defining a number object displaying the value of the Control parameter Time, like this:

To make a number box displaying TIME during simulation

1	Choose the Number tool from the toolbar or the Tolls menu.

2	Click inside the diagram window to create a number object.

3	Double-click on the number object to open the Define Number dialog box [image].

4	Choose Control in the Model combo box.

5	Choose Control.Time in the Parameter combo box.

6	Uncheck any check marks in the Allow Input group.

7	Press OK.

We will now set the simulation time to go from year 1995 to 2000.

To set the simulation time to go from year 1995 to 2000

1	Choose the Simulate Simulation Setup command to open the Simulation Setup dialog box displayed below.

2	Enter 1995 as Start Time and 2000 as Stop time.

3	Press OK

To test the result

1	Press the Run button to start a simulation.

2	Observe how the number object displays the simulation time. It should look something like this when the simulation is done.

We can make this output much more precise by adding the time unit (here: year) to the displayed number. This can, of course, be done by adding "year" to the label in front of the number box, or as a separate text to the right of the number box. The solution we will investigate here, however, is to define a custom number format for outputting year numbers.

To define a custom number format for outputting year numbers

1	Double-click on the number object to open Define Number again.

2	Click on the Format button and then on the Number entry in the pop-up menu that appears [image].

3	Type Year 0 in the Type field of the Format Number dialog box.

4	Observe in the Sample group at the bottom of the dialog box, how numbers will be displayed in the given format. You can type in another value in the Sample box to see how different values are formatted.

5	Click OK to close the Format Number dialog box.

6	Click OK to close the Define Number dialog box.

The resulting display should look like the following:

Note	The above procedure can be used to define the format of any value that is displayed as a number in a dynamic Powersim objects. Just look for the Format button inside the various dialog boxes.

Hint	It can be a good idea to include the unit of measure in the number format when displaying numbers. This makes it much easier for the model user to know what a number stands for.

See the Powersim Reference Guide for a detailed description of how number formats are defined.


Where does Powersim keep user defined numeric formats?

When you enter a new number format in the Format Number dialog box, that format will be displayed in the list of available formats the next time you open that dialog box; even if Powersim has been shut down and reopened in the meantime. This is possible since Powersim stores number formats in the POWERSIM.INI file.

The list of available formats can be reset to the default by pressing the Reset button of the Format Number dialog box.


Context Sensitive Help

  Opening Dialog Box Help

  Opening Function Help

  Opening Error Help


Opening Dialog Box Help

To open Help on an active dialog box

•	Press F1 on your keyboard, or

•	Hit the dialog box's Help button (if present).


Opening Function Help

To open Help on a particular function

1	Select a function in the Functions list or in the Definition box of the Define Variable dialog box

2	Press the F1 key.


Opening Error Help

When you get error messages while defining variables, a direct jump into a Help topic explaining the error is only a F1 keypress away.

To open help on a compiler error message

1	Click Set or OK to confirm a definition in the Define Variable dialog box

2	If an error message dialog box appears, press the F1 key

See also

Error Explanations


Using Arrays

An extremely powerful feature of Powersim is the ability to define indexed variables, or arrays. By defining a variable as an array, a group of related values may be represented as one variable. Arrays may be one-dimensional, also called vectors, or multi-dimensional, also called matrices. Arrays make the flow diagram smaller and more presentable, while reducing the amount of work necessary to create and maintain a model.

  How to Use Arrays

  Using Arrays to Represent a Group of Values

  Using Arrays as Matrices

  Index Variables and Constraints

  Array Dimensions and Ranges

  When to Use Arrays

  Replicated Structures

  State Transitions

  State Information

  Object Attributes

  History of Values

  Advanced Use of Arrays

  Array Level with Scalar Flow

  Scalar Level with Array Flow

  Flow Editing

  Using Index Variables and Constraints

  Passing Arrays to Functions

  Creating an Array Version of the Capital Model


How to Use Arrays

  Using Arrays to Represent a Group of Values

  Using Arrays as Matrices

  Index Variables and Constraints

  Array Dimensions and Ranges


Using Arrays to Represent a Group of Values

By defining a variable as an array, a group of related values may be represented as one variable. To demonstrate the power of arrays, imagine a model of a population that divides the population into three levels: young, adult, and old. Using scalar variables, the three different levels would be represented by showing them explicitly as depicted below.

Population groups using scalars

On the other hand, these different groups could be represented by using only one level, Population, with three elements.

To represent three population groups in one variable

1	Create a new level variable and name it Population.

2	Double-click on it to open the Define Variable dialog box.

3	Enter "1..3" in the Dimensions list box. This specification means that the variable has one dimension with elements numbered from 1 to 3.

4	Now lets input some actual numbers into the array. Type "[30, 50, 20]" in the Definition list box.

5	Click OK to close the Define Variable dialog box.

Powersim shows that a variable is an array by using a double frame when drawing the variable in the diagram as shown below.

Array indication in the diagram


Using Arrays as Matrices

The power of arrays can be further demonstrated by extending this example. Although Population was divided into three groups, it is sometimes necessary to divide groups even further. In our example, we have further broken each of the three groups into two groups, or six groups total. For instance, to represent Young1 (0-12), Young2 (13-17), Adult1 (18-29), Adult2 (30-64), Old1 (65-79), and Old2 (80+). By using scalars these groups would be divided into six different levels, but only one level is necessary when using the array capability of Powersim.

To represent a matrix of population groups in one variable

1	Create a new level variable and name it Population2.

2	Double-click on it to open the Define Variable dialog box.

3	Enter "1..3, 1..2" in the Dimensions list box.

4	Type "[[17, 13], [20, 30], [14, 6]]" in the Definition list box.

5	Click OK to close the Define Variable dialog box.


Index Variables and Constraints

It is common that the first or the last element of a dimension needs special treatment. This may be illustrated by extending our example with the three population groups. If we are going to simulate the aging of people, this involves transfer of people from one age group to another. In the scalar case, this means that we will have to add a flow from Young to Adult, and one from Adult to Old.

Aging using scalar levels

The rates BecomeAdult and BecomeOld may be defined in terms of the duration of the Young and Adult stages of a person's life; say 20 and 40 years, respectively. The expression defining BecomeAdult then becomes:

Young / 20

Similarly BecomeOld is defined as:

Adult / 40

When putting the same logic into the array variant of the model, we must first note that the last age group should be treated carefully, as no one ever leaves it because of getting too old.

The first age group must also be considered carefully, as people do not enter it because they grow too old to be counted in a younger group.

We therefore concentrate on the middle group when trying to generalize the aging process in a model with a fixed number of variables, independent of the number of age groups we choose to work with.

Isolating the general part of the aging model

Here we have put a frame around the part of the model that involves the import and export of people in the Adult group. By generalizing a bit, we may look upon the Adult group as a special case of any age group. We may then construct a model of a general group, as is done in the next figure.

Generalized aging structure

By putting all the age groups into one variable, Population, and also making the rates into arrays, our model becomes:

Aging structure using array variables

Note that since all age groups are contained in the Population, both the EnterAgeGroup and the LeaveAgeGroup rate depend on Population.

It is also natural to add a constant array, Duration, which defines the duration of each age period.

Final structure of aging model (demo: AGEARRAY.SIM)

The definition of Duration becomes:

Variable	Dimensions	Definition
Duration	1..3	[20, 40, 0]
Here the definition is a literal array with three elements; 20, 40, and 0. The last element is not used, as people never leave the final age group because of aging to a group of even older people.

We may now define the rates EnterAgeGroup and LeaveAgeGroup. The former is going to express the transport into an age group because of aging out of the previous group. For all groups, except the first, this may be expressed in the following way:

Population(Group-1) / Duration(Group-1)

Here the subscript (Group-1) is used to denote the previous element of an array, i.e., the previous age group.

For the first group, however, there is no previous group. We therefore need to introduce an alternative definition of the transport of people into the first group. This is done by introducing the notion of constraints:

0 | Group = 1 ; Population(Group-1) / Duration(Group-1) | Group > 1

In this expression several new elements are introduced. First, an index variable, Group, is used to separate element number one from the other elements.

Second, the expression is split into two parts by a constraint operator, the semicolon (;). The two parts are:

0 | Group = 1

and

Population(Group-1) / Duration(Group-1) | Group > 1

The third thing to notice is the vertical bar (|), which is used to put a guard on an expression. The expression following the bar determines a condition which is used by the constraint operator (;) to choose between alternative expressions. This means that whenever the index variable, Group, is greater than one, the value of Population(Group-1)/Duration(Group-1) will be used. When Group equals one, however, the other alternative will be used, for example, the value zero.

The expression above can be read like this: "0 when Group =1 but Population(Group-1)/Duration(Group-1) when Group > 1". Indeed, if you don't like the short operators (| and ;), you can write the expression as follows:

0 WHEN Group = 1 BUT

Population(Group-1) / Duration(Group-1) WHEN Group > 1

Index variables must be defined in Dimensions of the Define Variable dialog box. In our example the dimensions of EnterAgeGroup become:

Group = 1..3

Correspondingly, the rate LeaveAgeGroup may be defined. This time, however, it is the last group that needs special treatment. The next table shows the final definitions of the variables of our example. (A shorter index variable, G, is used in order to reduce the length of the definitions.)

Variable	Dimensions	Definition
EnterAgeGroup	G=1..3	0 | G = 1; Population(G-1) / Duration(G-1) | G > 1
LeaveAgeGroup	G=1..3	Population(G) / Duration(G) | G < 3; 0 | G = 3
Duration	1..3	[20, 40, 0]


Array Dimensions and Ranges

As you have seen, arrays are defined by specifying one or more dimensions. Each dimension is defined as a range of values. We have already seen ranges that are numeric subranges, for example, 1..3. It is also possible to define enumeration ranges, for example, Child, Adult, Old, and enumeration subranges, for example, Adult..Old.

A range may be given a name by defining it in the Define Range dialog box. This is done by choosing Define Range from the Edit menu. If we, for example, define the range PopGroup as a numerical subrange from 1 to 3, the dimensions of Population, EnterAgeGroup, LeaveAgeGroup, and Duration may be defined as PopGroup instead of 1..3.

In defining dimensions, we may use already defined ranges, or new (unnamed) ranges may be defined and used directly (as we have already seen in the case of the range 1..3, above). In the latter case we may use elements of already defined enumeration ranges in defining enumeration subranges, or integer numbers in defining numeric subranges.

As an example, we may define Duration without the last element (which is not used, anyway). This may be done in several ways. First, we may define a new range, say PopGroup2, which does not contain the group of old people. This may be done in the Define Range dialog box by making a subrange of PopGroup, with Child as the first element and Adult as the last one. (Here we assume that PopGroup is defined as Child, Adult, Old.)

With this range defined, one may define the dimensions of Duration to be PopGroup2 instead of PopGroup.

As an alternative, the dimensions of Duration may be defined to be a subrange of all elements of PopGroup, except the last. This may be done in two basically different ways. The first is to define a new, unnamed subrange from Child to Adult. The other approach is more general, as it is not referring to elements of the base range. Instead the definition below is used:

dim	Duration = FIRST(PopGroup)..LAST(PopGroup)-1

const	Duration = [20, 40]

Here Duration will be dimensioned correctly, even if the range PopGroup should be redefined at a later stage in the modeling process. (PopGroup may even be changed to another range type.)


When to Use Arrays

  Replicated Structures

  State Transitions

  State Information

  Object Attributes

  History of Values


Replicated Structures

Models often contain many identical or almost identical structures - especially large-scale models of realistic systems. If we, as an example, want to make a business simulator involving work force, capital, production, markets, and finance, it is easy to identify several duplicate structures, for example:

•	Different kinds of workers

•	Different kinds of capital, for example buildings and machines

•	Different product lines

•	Different market segments

•	Different accounts payable, for example, marketing expenses, goods, taxes, wages, dividends, debt

If we wanted to make a model of four competing companies, this would involve four similar structures - the main differences being values of parameters (constants) and levels (accumulators). Once a model of one company is developed, more companies may be added just by adding a company dimension to every variable of the model.

There are two important advantages of putting similar structures into arrays:

•	Maintainability - Changes to an array structure immediately takes effect for all elements of the array.

•	Complexity - Models sometimes become significantly smaller when using arrays (see figures below).

a) Separate structures for each type of capital

b) Structure with variables of capital type dimension


State Transitions

When modeling systems involving state transitions, it is common to express this as a sequence of levels with interconnected flows. Some examples are:

•	Training of people, moving people from a less skilled to a more skilled state

•	Aging of people, moving people from one age group to the next

•	Production, moving goods from less finished to more finished states

•	Transport, moving goods from one place to another

•	Capital upgrade or maintenance, moving capital from one state to another

The figure a) below shows a typical model of a production process using scalar variables. In figure b) the same model is presented using vectors. The Production variable has one element less than Goods (observe the exclamation marks on the flows). Note that the structure of the array version will be unchanged, even if the number of production phases should be changed.

State transitions using scalar variables

State transitions using vectors

The structure in the figure b) above may also be used to model a N-th order material delay, by adding separate inflows and outflows. The DELAYMTR function is normally used to express material delays, but if you want to access the contents of the levels implicitly defined by the DELAYMTR function, you can use an explicit structure like the one in the figure a) below.

a) Diagram of material delay structure

level	InTransit(p=RPhases) = 0

+dt*(Input        |p = FIRST(p);0)

+dt*(Progress(p-1)|p > FIRST(p);0)

-dt*(Progress(p)  |p < LAST(p) ;0)

-dt*(Output       |p = LAST(p) ;0)

aux	Input = PULSE(5, 5, 0)

aux	Output = Progress(LAST(RPhases))

aux	Progress(RPhases) = InTransit/ (DelayTime/COUNT(RPhases))

const	DelayTime = 10

b) Equations of material delay structure


State Information

If a system goes through discrete states, it can be modeled using a vector with the same number of elements as there are system states. Each time the system state changes, the elements of the state vector are shifted cyclically, using the SHIFTCIF function.

As an example, think of a process that may be in one of three distinct states; StateA, StateB, and StateC. Assume also that a variable NewState will be set to true whenever the system is going to be switched to the next state. Furthermore, assume that state transitions are cyclic, i.e., that StateA follows StateC.

Diagram of state transition

range	RState = StateA, StateB, StateC

aux	ChangeState = SHIFTCIF(NewState, State)

const	State(RState) = [1,0,0]

aux	NewState = ... "Some boolean expression"

Equations of state transition

Observe how the system states are defined as elements of an enumeration range. Initially the first state of the State vector is true (1), and the others false (0). Whenever NewState is true, the r.h.s. of the ChangeState definition will shift the elements of State one position to the right, changing the state from [1, 0, 0] to [0, 1, 0] the first time, and to [0, 0, 1] the second time, and to [1, 0, 0] the third time, etc.

Testing for a given state may be done using the following expressions:

State(StateA) - will be true whenever the system is in the first state

State(StateB) - will be true whenever the system is in the second state

State(StateC) - will be true whenever the system is in the third state


Object Attributes

A modeler is sometimes interested in keeping track, not only on the number of objects, but also certain object attributes or properties. As an example, you may be working on a production model, where products have attributes like lifetime, functionality, price, etc.

In the figure a) below, the scalar and the array version of the attribute section of a model is presented. In the figure b) below a range RAttribute is defined like this:

range	RAttribute = EPrice, EFunctionality, ELifetime, EInventory

The price of our product will be available as Product(EPrice). The other attributes are accessed correspondingly.

The significance of this solution is that all attributes are moved along when the object (here the product) flows through the system or is accessed via links. Additional attributes can be included without changing the structure of the model.

a) Separate variables for each attribute

b) Attributes aggregated in variable dimension


History of Values

As a final example of how arrays may be useful to the modeler, consider the problem of keeping track of previous values of variables.

Note	The SAMPLEIF function may be used for remembering a value for later use. Related functions are HIVAL and LOVAL, which remember the highest and lowest value of a variable, respectively, up to the current time of the simulation.

Let us assume that we are making an economic model, and that we want to keep track of the income for the recent 12 months.

Structure for remembering values

dim	MonthlyIncome = (i=1..12)

init	MonthlyIncome = 0

flow	MonthlyIncome = +dt*(Income WHEN i=1 BUT 0 OTHERWISE)

aux	NewMonth = TIMECYCLE(-1, 30)

aux	SaveIncome = SHIFTLIF(NewMonth, MonthlyIncome)

aux	Income = ... "Income rate"

Equations for remembering values

This model accumulates Income in the first element of the MonthlyIncome vector, which has 12 elements. The last day of every month, the elements of MonthlyIncome are shifted one position, and the first element is cleared (all this is done by the SHIFTLIF function). The time unit of the simulation is one day.


Creating an Array Version of the Capital Model

The model in figure b) at the bottom of Replicated Structures consists of four array variables with one dimension, which we'll call CapitalType. The elements of the range CapitalType are called CapBuildings and CapMachines. In this way each variable holds a separate value for buildings and for machines. Below  we'll go through the steps involved in building the model structure, defining the CapitalType range, defining each variable as an array, and displaying the results of array elements during a simulation.

To create the array version of the Capital model

1	Build the scalar version of the flow diagram in the figure below.

2	Open the Edit Define Range dialog box.

3	Press the Add button and type in CapitalType as the name of the new range.

4	Select Enumeration in the Range Type box.

5	Type CapBuildings in the Element Name text box and hit return.

6	Type CapMachines in the Element Name text box and hit return.

7	Close the dialog box by using the OK button.

8	Open the Define Variable dialog box by double-clicking on CapitalAcquisition.

9	Type CapitalType in the Dimensions box.

10	Type [0.05, 7] in the Definition field, telling Powersim that we acquire one building every twentieth year (1/20 = 0.05), and 7 machines every year.

11	Press the Set button and select Capital from the Variables box.

12	Select CapitalType in the Dimensions box.

13	Type [1, 3] in the Definition field, telling Powersim that we initially have one building and three machines.

14	Press the Set button and select CapitalUsefulLife from the Variables box.

15	Type [15, 3] in the Definition field, telling Powersim that buildings last for 15 years and machines last for three years.

16	Press the Set button and select CapitalDiscards from the Variables box.

17	Select CapitalType in the Dimensions box.

18	Enter Capital/CapitalUsefulLife in the Definition field.

19	Press OK.

20	Create a Time Graph object and drag the Capital variable into it.

21	Simulate the model.

Note	In this model we end up with 21 machines and 0.75 buildings (i.e., a building that is only 75% functional for our purposes). In a realistic model, the CapitalAcquisition variable would typically be part of a goal seeking loop for adjusting the actual Capital towards a desired value.


Advanced Use of Arrays

Normally, dimensions of rates and levels should match exactly when connected via a flow. This makes models with arrays intuitive and clear, as elements of interconnected rates and levels are paired on an element per element basis. On the other hand, strong requirements on dimension matching sometimes force the modeler to use more variables than necessary. These extra variables may sometimes cause the model to become less intuitive and more difficult to maintain. Extra array variables may also cause speed or memory problems in very large models.

  Array Level with Scalar Flow

  Scalar Level with Array Flow

  Flow Editing

  Using Index Variables and Constraints

  Passing Arrays to Functions


Array Level with Scalar Flow

Below is an example of a scalar rate SR controlling a level AL, which is an array:

Scalar rate controlling array level

If we assume that AL has one dimension with three elements, the above model has the same effect as the following model, where the level AL is split into three scalar levels, SL1, SL2, and SL3, representing the elements of AL:

Scalar rate controlling scalar levels

The model in the figure at the top of this topic looks like this in the equations view (turn on Equations from the View menu):

init	AL(1..3) = ...

flow	AL(1..3) = +dt*(SR)

aux	SR = ...

Note	It should be pointed out that mixing scalars and arrays may cause misinterpretations. The figure below, for example, does not mean that the level LC receives the sum of the outflows from LA. The model states that the inflow of LC is equal to the outflow of every element of LA (not the sum of the outflows of every element of LA). The corresponding equations become:

flow	LA(1..3) = -dt*(RB)

flow	LC = +dt*(RB)

Pitfalls when mixing arrays and scalars


Scalar Level with Array Flow

When an array flow is connected to a scalar level, the default definition of the flow of the level will be the sum of the elements of the flow rate (see next figure).

Connecting array flow to scalar level

The default definition of the flow becomes:

flow	SL = +dt*(ARRSUM(AR))


Flow Editing

Sometimes it is useful to connect rates and levels with rather arbitrary differences in dimensions. Our previous example with aging in a population may serve as a good illustration of this. Actually the model below may lead to the misinterpretation that aging within the population involves people outside of the system (as illustrated by the cloud symbols). The matter would become more clear, if a model like the one below could be used:

Aging using circular flow

Here we clearly see that the aging process only involves people within the population.

Let us try to elaborate the above model by defining the Aging rate. We may, for example, define Aging as the movement of people between one age group and the next. First of all, we observe that the Aging vector needs to hold a number of elements that is one less than the number of age groups.

First, we define the range Age as an enumeration with elements Young, Adult, Old. (Use the Define Range dialog box which is opened from the Edit menu.)

We may now define the dimensions of Population like this:

A=Age

The dimensions of Aging becomes:

A=FIRST(Age)..LAST(Age)-1

This means that there will be an aging of people out of every age group, except the last. The definition of Aging becomes:

Population(A)/Duration(A)

The Duration vector is defined with the same dimensions as Aging, and a definition of: [20, 40].

The biggest problem, however, remains. Even if the aging process is within the population, the flow from one group of the population has to be routed into the next element! This is done by opening the Define Variable dialog box and editing the flow part of the Population level. We observe that Aging is presented both as an inflow and an outflow.

Marking erroneous flows

The above definition of the flows are unfortunately not what we want. First of all, Aging has one element less than Population, which is an error if not handled, for example, by a constraint. This is signaled by the question marks on the flows in the diagram (see the figure above).

Secondly, the above flows are moving people back into the group they came from, which is not what we intend.


Using Index Variables and Constraints

In order to route the flows to the correct elements, we need to use both constraints and index variables, as illustrated in the following definition of the flow of Population:

+dt*(Aging(A-1) WHEN A>FIRST(A) BUT 0)

-dt*(Aging(A) WHEN A<LAST(A) BUT 0)

Once a flow has been changed from its default definition, the corresponding flow arrow will be marked by an exclamation mark, indicating that the flow is constrained and/or indexed. (If the flow definition is incorrect, the flow will be marked by a question mark.)

FInal aging model with marked flow (demo: CIRCFLOW.SIM)

Simulating the model will produce the results to the left (given that the age groups all contain 100 individuals initially):


Passing Arrays to Functions

Some functions expect arguments that are arrays. Examples are ARRSUM and GRAPH. Arrays are passed by specifying a range instead of an element index in one or more positions of the array subscript.

The sum of all the elements of an array may be calculated using the ARRSUM function, as in the following example:

range	Age = Child, Young, Adult, Old

range	Sex = Female, Male

level	Pop(Sex, Age) = ...

aux	TotPop = ARRSUM(Pop(Sex, Age))

In our example, the array subscript might also be omitted, since all the elements of the array are passed to ARRSUM:

aux	TotPop = ARRSUM(Pop)

A partial array may be passed to a function using indices and reduced ranges for some or all of the dimensions. As an example, the size of the male population may be computed like this:

aux	MalePop = ARRSUM(Pop(Male, Age))

An array may be reduced even further when passed to a function. As an example, we may want to calculate the total number of adult and old persons in our population:

aux	GrownUps = ARRSUM(Pop(Sex, Adult..Old))

An asterisk (*) may be used to denote an entire dimension. The size of the female population may, for example, be calculated like this:

aux	FemalePop = ARRSUM(Pop(Female, *))


Connecting to other Applications

  Using DDE

  Using the DDE object

  Writing MS-EXCEL macros accessing Powersim via DDE

  Writing Lotus 1-2-3 macros accessing Powersim via DDE

  Using the Powersim API

  Introduction

  Overview of Powersim API

  Powersim Connections

  Using C/C++

  Using The Powersim Connection OCXs

  Using The Powersim Connection Delphi Component

  Advanced Topics

See also

  Connectivity


Using DDE

  Using the DDE object

  Outputting data to a spreadsheet

  Writing MS-EXCEL macros accessing Powersim via DDE

  Setting values of Powersim variables from Excel

  Getting values of Powersim variables into Excel

  Controlling Powersim from Excel

  Advanced Excel example

  Writing Lotus 1-2-3 macros accessing Powersim via DDE

  Lotus 123 DDE Macro Example 1: POWERSIM_LINK

  Lotus 123 DDE Macro Example 2: POWERSIM_AUTO_LINK

  Lotus 123 DDE Macro Example 3: POWERSIM_EXIST_LINK


Using the DDE object

Although Powersim has various output and input capabilities, it is often helpful to output or input from and to other applications. We realize that the manual input of data from the model or to the model would be both time-consuming and monotonous. As a remedy for this potential problem, Powersim offers the ability to export and import data with other applications. The DDE (Dynamic Data Exchange) is a feature that allows for flexible and powerful transfer of data between applications and is a feature of both Powersim Standard and Professional.

  Outputting data to a spreadsheet


Outputting data to a spreadsheet

One application of the DDE link is to use it to simply output the raw data to an Excel spreadsheet, where it can be manipulated further. This example looks at exporting time series of variables to an Excel spreadsheet.

To output data to an Excel spreadsheet

1	Select the DDE button on the toolbar [image] and place the object anywhere on the screen.

2	To define the DDE object, double-click on it. At this point, you will see the Define Dynamic Data Exchange dialog box.

The Define DDE Dialog Box

3	In the Models box of the Define Dynamic Data Exchange dialog box, select the model whose variable(s) you want to export. The Models list includes the main model and all co-models. Well choose Main.

4	In the Variables box choose the variable(s) you want to export. The Variables list displays all variables names (scalars) and variable elements (arrays) of the selected model. Well pick Cash and AccountsReceivable.

5	In the Transfer box choose between exporting (To Application) or importing (From Application) the data. Well select to export (To Application).

6	In the Orientation box pick the desired orientation of the data. Vertical means that the data is sent to a row, while Horizontal means that the data is stored in a column. For our example, well select Vertical.

7	In the Values group decide on transferring the data as single values or a time series. If you select Single, only one value will be transferred for each variable during the entire simulation. If you choose Series, several values will be transferred for each variable. When you choose Series, another setting will be enabled, i.e., Times. Well pick Series.

8	Use the Times From and To boxes to choose the time associated with the first and last value of each time series. When exporting data, you should normally select Auto for From and To.

9	Use Times Step to pick the interval between successive data points in the time series. If the current simulation contains a large number of time steps, you may want to increase the value of Step from its Auto value to a larger number in order to reduce the number of values in the generated time series. For our example, well use Auto.

10	Use the Service text box to enter the name of the application with which you are exchanging (EXCEL, WINWORD, etc.). Well pick EXCEL.

11	Use the Topic text box to input the name of the specific application file with which you are exchanging. The name of our Excel file is ACCTING.XLS.

12	Use the Item text box to specify the cells where the data is to be placed. The procedure for this is to specify the entire field where the data will be placed by specifying the first cell and last cell. The convention used is to refer to the cells row and column locations and separate them by a colon. For instance, cell E1 would be r5c1, or row 5, column 1. In our example, well use the cells r1c1:r20c2 (A1 to B20).

13	Select OK and run the model. Your output will look similar to the figure below.

Excel file accting.xls


Writing MS-EXCEL macros accessing Powersim via DDE

The Excel 5.0 sheet PSMACROS.XLS contains examples of Powersim macros. The following sections assume that you are familiar with Excel macros and Visual Basic. See also the Excel documentation and help system.

  Setting values of Powersim variables from Excel

  Getting values of Powersim variables into Excel

  Controlling Powersim from Excel

  Advanced Excel example


Setting values of Powersim variables from Excel

The following is an Excel subroutine that may be used by Excel macros to set values of Powersim variables.

Sub SetPSValue(PSDoc$, PSVar$, Value)

Rem Purpose:	Set named Powersim variable of named Powersim document

Rem In:	PSDoc$ - Name of Powersim document

Rem	PSVar$ - Name of Powersim variable

Rem	Value - Value to be assigned to 'PSVar$'

Rem Note:	Powersim must be running in order to set values of model variables

    On Error GoTo Err_Label

    Ch = DDEInitiate("Powersim", PSDoc$)

    DDEPoke Ch, PSVar$, Value

    DDETerminate Ch

    Exit Sub

Err_Label:

    DDETerminate Ch

    MsgBox "Cannot set value of Powersim variable " + PSVar$

End Sub

Note	The DDEPoke routine of Excel expects a cell reference as its third parameter. See example below, where Cells(1,1) is used to refer to cell A1.

The Excel macro below uses SetPSValue to set the value of Room_Temp equal to the contents of Excel cell A1.

Sub SetPS()

    SetPSValue "c:\powersim\mod\COFF_TMP.SIM", "Room_Temp", Cells(1, 1)

End Sub


Getting values of Powersim variables into Excel

The following is an Excel 5.0 function that may be used by Excel macros to get values of Powersim variables.

Function GetPSValue(PSDoc$, PSVar$)

Rem Purpose: Get named Powersim variable from named Powersim document

Rem In:      PSDoc$ - Name of Powersim document

Rem          PSVar$ - Name of Powersim variable

Rem Return:  Value Powersim variable

Rem Note:    Powersim must be running in order to get values model variables

    On Error GoTo Err_Label

    Ch = DDEInitiate("Powersim", PSDoc$)

    returnlist = DDERequest(Ch, PSVar$)

    GetPSValue = returnlist(1)

    DDETerminate Ch

    Exit Function

Err_Label:

    DDETerminate Ch

    MsgBox "Cannot get value of Powersim variable " + PSVar$

    GetPSValue = 0

End Function

Note	The DDERequest function of Excel returns an array. The above function returns the first element of the returned array as the function result.

The Excel macro below uses GetPSValue to set the value of Excel cell A1 equal to the value of the Powersim variable Room_Temp.

Sub GetPS()

   Cells(1, 1) = GetPSValue( "c:\powersim\mod\COFF_TMP.SIM", "Room_Temp")

End Sub


Controlling Powersim from Excel

The following is an Excel 5.0 routine that may be used by Excel macros to open and simulate a Powersim model.

Sub RunPSDoc(PSDoc$)

Rem Purpose:  Exampe of MS-Execl macro controlling Powersim

Rem           The macro opens and runs a Powersim model.

Rem Language: MS-Excel macro

Rem In:       PSDoc$ - Name of Powersim document

    On Error GoTo Err_Label

    Ch = DDEInitiate("Powersim", "System")

    DDEExecute Ch, "[Open(" + Chr$(34) + PSDoc$ + Chr$(34) + ")]"

    DDEExecute Ch, "[Run]"

    DDETerminate Ch

    Exit Sub

Err_Label:

    DDETerminate Ch

    MsgBox "Cannot open and run Powersim model " + PSDoc$

End Sub

Note the use of Chr$(34) to put quotes before and after the document name. As an alternative, you may use double quotes in Excel strings where you want a single quote to appear in the result string. Example:

DDEExecute Ch, "[Open(""" + PSDoc$ + """)]"

The Excel macro below uses RunPSDoc  (defined above) to open and run the demo model COFF_TMP.SIM. Note the use of double back-slashes in path names.

Sub RunPSCoffee()

    RunPSDoc("c:\\powersim\\mod\\COFF_TMP.SIM")

End Sub


Advanced Excel example

Assume that you want to make a model and a spreadsheet that interacts. Below is an Excel 5.0 macro that performs the following:

1	Open Powersim diagram (T.SIM)

2	Simulate model one step

3	Wait until model has paused (the simulation of the step is completed) or the model has stopped (the entire simulation is over). In the latter case go to step 8.

4	Get the value of a Powersim variable (A)

5	Do some calculations in Excel

6	Set the value of a Powersim variable (B) from an Excel cell (A1)

7	Go to step 2

8	Done

The Excel macro looks like this:

Sub InteractPS()

Rem Open Powersim document T.SIM

    Ch = DDEInitiate("Powersim", "t.sim")

Rem Run one step

NextStep:

    DDEExecute Ch, "[RUN.STEP]"

Rem Wait until Powersim pauses (or stops)

    While GetValueOf(Ch, "Control.Pause") <> 1

       If GetValueOf(Ch, "Control.Play") = 0 Then

          GoTo Done

       End If

    Wend

Rem Get value of Powersim variable A

    a = GetValueOf(Ch, "A")

Rem Do calculations (a * 10) and place result in A1

    Cells(1, 1).Value = a * 10

Rem Set value of Powersim variable B

    SetValueOf Ch, "B", Cells(1, 1)

Rem repeat

    GoTo NextStep

Done:

    DDETerminate Ch

End Sub


Writing Lotus 1-2-3 macros accessing Powersim via DDE

The 1-2-3 Release 5 macros below perform the following tasks:

  Lotus 123 DDE Macro Example 1: POWERSIM_LINK

  Lotus 123 DDE Macro Example 2: POWERSIM_AUTO_LINK

  Lotus 123 DDE Macro Example 3: POWERSIM_EXIST_LINK


Lotus 123 DDE Macro Example 1: ESTABLISHING POWERSIM_LINK

The following macro sends commands to another application and retrieves data from that application using the DDE macro commands.

POWERSIM_LINK	{LAUNCH "C:\POWERSIM\POWERSIM"}

{DDE-OPEN "POWERSIM";"SYSTEM"}

{DDE-EXECUTE  "[FileOpen(""C:\POWERSIM\DOC\LOAN.SIM"",1,"""")]"}{ERROR 1}{QUIT}

{DDE-EXECUTE "[FilePrint(1,1,9999,1537)]"}{ERROR 2}{QUIT}

{DDE-CLOSE}

{DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"}{ERROR 3}{QUIT}

{DDE-REQUEST LOANPAYMENT;"PAYMENT"}

{DDE-CLOSE}

ERROR	{DEFINE ERR_CODE}

{IF ERR_CODE=1}{LET MESSAGE;"FileOpen failed"}

{IF ERR_CODE=2}{LET MESSAGE;"FilePrint failed"}

{IF ERR_CODE=3}{LET MESSAGE;"DDE-OPEN failed"}

{DDE-CLOSE}

This macro performs the following tasks:

The macro starts Powersim and then opens and prints the file C:\POWERSIM\DOC\LOAN.SIM. It then transfers data from a variable named PAYMENT in LOAN.SIM to a range named LOANPAYMENT in the current 1-2-3 file.

{LAUNCH "C:\POWERSIM\POWERSIM"} starts a Powersim  session.

{DDE-OPEN "POWERSIM";"SYSTEM"} initiates a conversation with Powersim, with "system" as the topic (Powersim filename and location). One must begin with a system-topic conversation because no Powersim  file is already opened.

{DDE-EXECUTE "[FileOpen(""C:\POWERSIM\DOC\LOAN.SIM"",1,"""")]"} opens the Powersim  file C:\POWERSIM\DOC\LOAN.SIM. The extra quotes around the arguments to the FileOpen statement prevent 1-2-3 from interpreting the quotes as the end of the literal string to pass to Powersim.

{DDE-EXECUTE "[FilePrint(1,1,9999,1537)]"} prints the file. If 1-2-3 cannot open or print the file, the subroutine ERROR displays an error message and terminates the conversation.

{DDE-CLOSE} terminates the system-topic conversation.

{DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"} initiates a conversation with Powersim, with the file C:\POWERSIM\DOC\LOAN.SIM as the topic. If 1-2-3 cannot open the conversation, subroutine ERROR displays an error message and terminates the conversation.

{DDE-REQUEST LOANPAYMENT;"PAYMENT"} transfers data from a variable named PAYMENT in LOAN.SIM to the range named LOANPAYMENT in the current 1-2-3 file.

{DDE-CLOSE} terminates the file-topic conversation.


Lotus 123 DDE Macro Example 2: POWERSIM_AUTO_LINK

The following macro creates an automatically updated link using the DDE macro commands.

POWERSIM_AUTO_LINK	{LAUNCH "C:\POWERSIM\POWERSIM"}

{DDE-OPEN "POWERSIM";"SYSTEM"}

{DDE-EXECUTE "[FileOpen(""C:\POWERSIM\DOC\LOAN.SIM"",1,"""")]"}

{DDE-CLOSE}

{DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"}

{REQUEST}

{DDE-ADVISE REQUEST;"PAYMENT"}

REQUEST {DDE-REQUEST LOANPAYMENT;"PAYMENT"}

{IF LOANPAYMENT>2000}{LET MESSAGE;"Payment exceeds limit"}{BREAKLINK}{QUIT}

BREAKLINK {DDE-UNADVISE "PAYMENT"}

{DDE-CLOSE}

This macro performs the following tasks:

The macro starts Powersim, opens the file C:\POWERSIM\DOC\LOAN.SIM, and transfers data from a variable named PAYMENT in LOAN.SIM to a range named LOANPAYMENT in the current 1-2-3 file. It then updates the data in the range LOANPAYMENT whenever the data in PAYMENT changes. If the amount in PAYMENT exceeds 2000, the macro displays a message and breaks the link.

{LAUNCH "C:\POWERSIM\POWERSIM"} starts a Powersim  session.

{DDE-OPEN "POWERSIM";"SYSTEM"} initiates a conversation with Powersim, with "system" as the topic.

{DDE-EXECUTE "[FileOpen(""C:\POWERSIM\DOC\LOAN.SIM"",1,"""")]"} opens the Powersim  file

C:\POWERSIM\DOC\LOAN.SIM.

{DDE-CLOSE} terminates the system-topic conversation.

{DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"} initiates a conversation with Powersim, with the file C:\POWERSIM\DOC\LOAN.SIM as the topic.

{REQUEST} calls the subroutine REQUEST, which transfers data from Powersim  into 1-2-3.

{DDE-ADVISE REQUEST;"PAYMENT"} branches to the subroutine REQUEST each time the data in PAYMENT changes.

{DDE-REQUEST LOANPAYMENT;"PAYMENT"} transfers data from a variable named PAYMENT in LOAN.SIM to the range named LOANPAYMENT in the current 1-2-3 file.

{IF LOANPAYMENT>2000} tests the contents of LOANPAYMENT. If the cell contains a value greater than 2000, the macro continues to the next instruction following {IF} in the same cell; in this case the instructions display a message, call the subroutine {BREAKLINK}, which ends the {DDE-ADVISE} command and terminates the conversation, and quit the macro.


Lotus 123 DDE Macro Example 3: POWERSIM_EXIST_LINK

The following macro creates an automatically updated link more efficiently; it launches Powersim only if it is not already active and opens a file only if it is not already open.

POWERSIM_EXIST_LINK	{OPEN_FILE}

{DDE-REQUEST LOANPAYMENT;"PAYMENT"}

{DDE-ADVISE ;"PAYMENT";;LOANPAYMENT}

OPEN_FILE {DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"}{OPEN_SYS}

OPEN_SYS {DDE-OPEN "POWERSIM","SYSTEM"}{BRANCH OPEN_LAUNCH}

{DDE-EXECUTE "[FileOpen(""C:\POWERSIM\DOC\LOAN.SIM"",1,"""")]"}{ERROR}

{DDE-CLOSE}

{DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"}

OPEN_LAUNCH {LAUNCH "C:\POWERSIM\POWERSIM"}

{OPEN_SYS}

This macro performs the following tasks:

The macro creates an automatically updated link from a variable named PAYMENT in LOAN.SIM to the range named LOANPAYMENT in the current 1-2-3 file. The macro starts Powersim only if it is not already running, and opens LOAN.SIM only if it is not already open.

{OPEN_FILE} calls subroutine OPEN_FILE, which initiates a conversation with Powersim with the file C:\POWERSIM\DOC\LOAN.SIM as the topic.

{DDE-REQUEST LOANPAYMENT;"PAYMENT"} transfers data from a variable named PAYMENT in LOAN.SIM to the range named LOANPAYMENT in the current 1-2-3 file.

{DDE-ADVISE ;"PAYMENT";;LOANPAYMENT} transfers the data in PAYMENT to LOANPAYMENT each time the data in PAYMENT changes.

{DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"}{OPEN_SYS} initiates a conversation with Powersim, with the file C:\POWERSIM\DOC\LOAN.SIM as the topic, or calls the subroutine OPEN_SYS if the {DDE-OPEN} command fails.

{DDE-OPEN "POWERSIM","SYSTEM"}{BRANCH OPEN_LAUNCH} initiates a conversation with Powersim, with "system" as the topic, or branches to the subroutine OPEN_LAUNCH if the {DDE-OPEN} command fails.

{DDE-EXECUTE "[FileOpen(""C:\POWERSIM\DOC\LOAN.SIM"",1,"""")]"}{ERROR} opens the Powersim file C:\POWERSIM\DOC\LOAN.SIM, or calls the subroutine ERROR if the {DDE-EXECUTE} command fails.

{DDE-CLOSE} terminates the system-topic conversation.

{DDE-OPEN "POWERSIM";"C:\POWERSIM\DOC\LOAN.SIM"} initiates a file-topic conversation.

{LAUNCH "C:\POWERSIM\POWERSIM"} starts Powersim.

{OPEN_SYS} calls subroutine OPEN_SYS. benefited


Initializing variables when a simulation starts

  Overview

  Initializing by equation

  Loading values from a file

  Loading values from an application using DDE

  Loading values from a co-model using Chain

  Keeping values between simulations

  Initializing parameters before the simulation starts

  Initializing values from the network simulation object


Overview

•	Model variables can be initialized in several ways.

•	An initial value must always be given when defining a variable. This value can be overridden by some of the initializations listed below in this list.

•	Initial values of levels and constants can be loaded from a file when the simulation starts.

•	Initial values of levels and constants can be taken from another application using Dynamic Data Exchange (DDE).

•	Initial values can be taken from a co-model using the chain object.

•	Initial values can be carried over from the previous simulation, i.e., the final values of one simulation can be used as initial values for the next.

•	Initial values can be set by the user before the simulation starts.

•	Initial values can be set by the network simulation object.


Initializing by equation

All variables must be defined before a simulation can start. When the simulation starts, every variable is initialized by computing the expression defining the initial value of the variable. The expression defining a variable is entered using the Define Variable dialog box (see).

Initial values of levels and constants can be modified by one of the other initialization mechanisms, described below.


Loading values from a file

The Archive object can be used to load data from a file into model variables. You can either load the initial values of selected variables, or you can load a time series describing the development of a value over time, as the simulation proceeds. As an example, we will create a model where an interest rate is taken from a data file called INTEREST.TXT, holding assumed interest rate for a period from 1996 to 2000.

How to create a variable that can receive input from a file

First, we create a new model and define one variable called Interest, like this:

1	Use the File New command or click on the new file icon [image] to create a new file.

2	Choose the constant tool [image] from the toolbar or from the Tools menu.

3	Deposit a new constant in the diagram by pointing and clicking.

4	Type Interest as the name of the constant and press Return.

5	Press Return again to open the Define Variable dialog box. (You can also double click on the constant to open the definition dialog).

5	Enter an expression, say 3%, as the definition of Interest.

6	Press OK.

How to create a file with data to be imported into Powersim

Next, we create a text file INTEREST.TXT that will hold the data to be imported.

1	Start NOTEPAD or some other text editor that can save files as plain text.

2	Type in the following:

3	Save the file as INTEREST.TXT and close NOTEPAD.

How to make the connection between variables and data stored in a file

We can now go back to Powersim and link the INTEREST.TXT file to the Interest variable.

1	If not already active, reactivate Powersim and the model containing our Interest variable.

2	Choose the archive tool [image] from the toolbar or from the Tools menu.

3	Deposit a new archive object in the diagram by clicking inside the diagram window.

4	Drag and drop the Interest variable into the newly created archive object.

5	Open the Define Archive dialog box by double clicking on the archive object.

6	Observe that Interest is listed in the Parameters list because of the drag-and-drop operation that we did in step four.

7	Choose From File in the Transfer combo box, as we want data to be loaded from INTEREST.TXT.

8	Let the Orientation stay at Vertical, as data are stored in columns.

9	Choose 1234.56 as Numerical Format, as we have used a period as decimal separator in the file INTEREST.TXT. We used no thousand separator.

10	Click on Browse to select INTERST.TXT into the File text box. You can also type in the name directly. You may have to specify the full path, if the file is not stored in the current directory.

11	Check on Headers and Time Values in the Include group, since our data contains headers (TIME and INTEREST) and a column with time values (the first column).

12	In the From Source group you can check on Transfer Times if you want the simulation to synchronize the values in the time column with the simulation time. If you check Parameter Names, the names of the parameters to import will be loaded from the file. This is not necessary in our case, as we have already told the archive object to load the values into the Interest variable.

13	Check that your settings work by pressing Update. If you get an error message, revisit the above steps and make sure that all settings are correct.

14	Press OK to close the Define Archive dialog box.

How to set the simulation time to match the imported data set

Before we run the simulation, simulation time should be set to start at 1996 and stop at 2000.

1	Choose Simulate Simulation Setup from the menus.

2	Type 1996 as Start Time and 2000 as Stop Time.

3	Press OK.

Running a simulation that takes data from a file

You can now run the simulation by pressing the run button [image].

To verify that Interest gets its values from the INTEREST.TXT file, we can create a time table object displaying the values of Interest during simulation.

1	Choose the Time Table tool [image] by clicking in the toolbar or choosing it in the Tools menu.

2	Deposit a new time table object in the diagram by clicking in the diagram with the mouse.

3	Drag and drop the Interest variable into the time table.

4	Run the simulation again.

The resulting display should now look something like this:

Note	The above model can be found as the file INI_FILE.SIM that comes with Powersim.


Loading values from an application using DDE

The Dynamic Data Exchange (DDE) object can be used to get data from another application, for example a spreadsheet. You can either load the initial values of selected variables, or you can load a time series describing the development of a value over time, as the simulation proceeds. As an example, we will create a model where the initial inventories of three products are loaded from an Excel spreadsheet named PRODINV.XLS.

How to create a variable that can receive input from an application

First, we create a new model and define one array variable called Inventory with three elements, like this:

1	Use the File New command or click on the new file icon [image] to create a new file.

2	Choose the level tool [image] from the toolbar or from the Tools menu.

3	Deposit a new level in the diagram by pointing and clicking.

4	Type Inventory as the name of the level and press Return.

5	Press Return again to open the Define Variable dialog box. (You can also double click on the level to open the definition dialog).

6	Enter 1..3 as the Dimensions of the Inventory. This will reserve three array elements for holding inventories of three products; product number 1, 2 and 3.

Enter [0,0,0] as the Definition of the Initial value of Inventory.

7	Press OK.

How to prepare a spreadsheet for import by Powersim

Next, we create a text file PRODINV.XLS that will hold the data to be imported. This requires that you have Microsoft Excel installed on your computer. If you have another spreadsheet program, you can try to adapt the description below to that. You can also use some word processors to achieve a similar result as described below.

1	Start EXCEL.

2	Type in the following:

Make sure not to type spaces inside the column headings. (If you do, you should not include Headers in the transfer. See step 13).

3	Save the file as PRODINV.XLS. You need not close EXCEL.

How to make the connection between variables and another application

We can now go back to Powersim and link a cell range of PRODINV.XLS to the Inventory variable.

1	If not already active, reactivate Powersim and the model containing our Inventory variable. (You can use Alt+Tab to bring Powersim into focus again.)

2	Choose the DDE tool [image] from the toolbar or from the Tools menu.

3	Deposit a new DDE object in the diagram by clicking inside the diagram window.

4	Drag and drop the Inventory variable into the newly created DDE object.

5	Open the Define Dynamic Data Exchange dialog box by double clicking on the DDE object.

6	Observe that the elements of Inventory are listed in the Parameters list because of the drag-and-drop operation that we did in step four.

7	Choose From Application in the Transfer combo box, as we want data to be imported from Excel.

8	Let the Orientation stay at Vertical, as data are stored in columns.

9	Let the Numerical Format stay at Control Panel, as Excel will deliver data in that format.

10	Type Excel in the Service field.

11	Type PRODINV.XLS in the Topic field.

12	Type R1C1:R2C3 in the Item field. If you create a bookmark for the cell range in Excel, you can use the name of the bookmark when referring to the Item.

13	Check on Headers the Include group, since our data contains headers (Product_1, Product_2, Product_3). If you uncheck Headers, you must also reduce the cell range in the Topic field from R1C1:R2C3 to R2C1:R2C3.

14	If you check Parameter Names, the names of the parameters to import will be loaded from the file. This is not necessary in our case, as we have already told the DDE object to load the values into the Inventory variable. If you want to take parameter names from the imported data set, the Headers row (column if orientation is Horizontal) must contain the exact names of the parameters to import.

15	Check that your settings work by pressing Update. If you get an error message, revisit the above steps and make sure that all settings are correct. If this doesn't work, try starting Excel before you click on Update.

16	Press OK to close the DDE dialog box.

Running a simulation that takes data from Excel

You can now run the simulation by pressing the run button [image] .

To verify that the elements of Inventory gets their values from Excel, we can create an array graph object displaying the values of Inventory during simulation.

1	Choose the Array Graph tool [image] by clicking in the toolbar or choosing it in the Tools menu.

2	Deposit a new array graph object in the diagram by clicking in the diagram with the mouse.

3	Drag and drop the Inventory variable into the array graph.

4	Run the simulation again.

The resulting display should now look something like this:

Note	The above model can be found as the file INI_APP.SIM that comes with Powersim.


Loading values from a co-model using Chain

You can run many models concurrently by adding co-models to a model, which becomes  the main model. This is a useful way of breaking a large model into smaller parts. Another use is to have one model monitor the operation of other models. Co-models are also handy when making an interface on top of a model. A forth use is when a system has several sub systems with equal structure. In that case we can use the same model several times in the list of co-models of a given main model.

In all the above examples, there is a need to transfer data between models. This can, of course, be done using DDE with the Automatic setting switched on, Powersim as the Service, a Powersim model as the Topic, and the name of a Powersim variable as the Item. See Loading values from an application using DDE . In this chapter, however, we will demonstrate how the Chain object can be used to link variables in different co-models together.

As an example, let us make a model COMPANY.SIM that includes information about a company and its product. One important attribute of a product, is its Price. In a realistic example, there would probably be a Demand variable that would be effected by Price. In this exercise, however, we concentrate on the way Chain works, and therefore leave Price alone as the only variable in our COMPANY.SIM model. We will create a main model with COMPANY.SIM listed two times as co-model, and put a slider bar in the main model for controlling the price if each company's product. We will also create a vector with two elements in the main model, and Chain the two company's Price variables to individual elements of the vector. The figure below illustrates the structure of the system we are going to make:

How to create a co-model

A co-model is an ordinary model. Below we create a model COMPANY.SIM that will serve as a co-model later in the example.

1	Use the File New command or click on the new file icon [image] to create a new file.

2	Choose the constant tool [image] from the toolbar or from the Tools menu.

3	Deposit a new constant in the diagram by pointing and clicking.

4	Type Price as the name of the constant and press Return.

5	Press Return again to open the Define Variable dialog box. (You can also double click on the constant to open the definition dialog).

6	Enter 0 as the Definition of Price.

7	Press OK.

8	Use the File Save command or press the save button [image] to save your model. Type COMPANY.SIM as the file name of the model.

How to create a main model

1	Use the File New command or click on the new file icon [image] to create a new file.

2	Choose the constant tool [image] from the toolbar or from the Tools menu.

3	Deposit a new constant in the diagram by pointing and clicking.

4	Type PriceArray as the name of the constant and press Return.

5	Press Return again to open the Define Variable dialog box. (You can also double click on the constant to open the definition dialog).

6	Enter 1..2 as the Dimensions of PriceArray, as we will operate with prices of two products (one from each company co-model).

7	Enter 0 as the Definition of PriceArray.

8	Press OK.

9	Use the File Save command or press the save button [image] to save your model. Type INI_CHAI.SIM as the file name of the model.

Adding co-models to a main model

We now want to add COMPANY.SIM two times as co-model to INI_CHAI.SIM.

1	With INI_CHAI.SIM as the current model, open the Simulation Setup dialog box from the Simulate menu.

2	Click on the Co-models button to open up the bottom part of the dialog, which deals with Parallel Simulation.

3	Use the Add button to add COMPANY.SIM to the Model list.

4	Click on the new model and use the Rename button to change the name to Company_One.

5	Repeat steps 3 and 4 again, this time renaming the model to Company_Two. The resulting dialog box should look like this:

6	Press OK to close Simulation Setup.

7	Save your model by pressing on the save file button [image].

Chaining variables together

We will now chain the Price variable of Company_One to the first element of PriceArray, and the Price variable of Company_Two to the second elements of the array.

1	Choose the Chain tool [image] from the toolbar or the Tools menu.

2	Deposit a new chain object in the main model (INI_CHAI.SIM)

3	Double click on the chain object.

4	Fill Source with Company_One as the Model and Price as the Parameter.

5	Fill Destination with Main as the Model and PriceArray(1) as parameter.

6	Press OK to close Define Chain.

7	Repeat steps 1 through 6, but this time you choose Company_Two as Source Model and PriceArray(2) as Destination Parameter.

8	Save your model again; in case of electricity failure.

Testing how Chain works

We are now ready to do some testing of our main model (INI_CHAI.SIM) and its two co-models (two instances of COMPANY.SIM). But first, we have to create some input and output objects for setting the Price variables of the co-models and observing the elements of PriceArray.

1	Use the slider/bar tool [image] to create a slider/bar object.

2	Double click on the newly created slider/bar.

3	Choose Company_One in the Models list and add Company_One.Price to the Variables list, and press Add to move Company_One.Price to the Parameters list.

4	Do the same with Compay_Two.Price.

5	Choose Main in the Models list and add PriceArray(1) and PriceArray(2) to the Parameters list.

6	Select PriceArray(1) and PriceArray(2) in the Parameters list, and uncheck both check marks in the Allow Input group.

7	Press OK.

8	Position and size the slider/bar object so the contained bars fit well inside the object. If you like, you can turn off axis and tick marks by means of the Axis button inside Define Slider/Bar. This has been done for the example model INI_CHAI.SIM that comes with Powersim.

9	Press the Run Step button [image] or choose Run Step from the Simulate menu.

10	Drag the slide bars and observe how the elements of PriceArray are changed indirectly. When you change the value of Company_One.Price, for example, the new value is transferred by the Chain object to the array element PriceArray(1).

Note	The described model can be found as the file INI_APP.SIM that comes with Powersim. This file also contains a simple example of how the multimedia object can be used to give a message to the user.


Keeping values between simulations

Some dynamic object have a setting called Keep Value or Keep Values. When checked, the final value of a parameter will be remembered when a simulation ends. The next time you start a simulation, this value will be used to initialize the parameter.

This feature is useful, for example, if you have a model with many parameters, and you want to do a number of simulations with the objective to find a "good" set of parameters for the model. Without the Keep Value feature, you have to set all parameters each time you start a new simulation. Often you want to keep most parameter values from the previous run, and only change a few to see how that will effect the results of the simulation.

Below is an example where a two parameters, Interest and Deposit, are used to control how a bank account develops. The parameters are set by entering numbers into two number objects. The result is displayed in a time graph. We keep the value of Interest and Deposit between runs.

Example of how to build a model that will keep values between runs

1	Use the File New command or click on the new file icon [image] to create a new file.

2	Build the diagram below.

The model should have the following equations:

3	Choose the Number tool [image] from the toolbar or the Tools menu.

4	Deposit a new number object in the model.

5	Drag the variable Interest over the number object and release the mouse button.

6	Double click on the number object.

7	Switch on the Keep Value check mark.

8	Press OK to close Define Number.

9	Repeat steps 3 through 8, but this time you drop the Deposit variable into the number object.

10	Choose the Time Graph tool [image] from the toolbar or the Tools menu.

11	Deposit a new time graph object in the model.

12	Drag the Account variable into the time graph object and release the mouse button.

13	Save your model.

To set, use and modify kept values

Before we run the above model, we should set some initial values for Interest and Deposit. Since we have checked on Keep Value, the number objects will accept input even before the simulation starts.

1	Select the number object displaying Interest, if it is not already selected. (You select the object by clicking on it).

2	Press inside the number box to the right of Interest. A dialog box for entering a number will pop up.

3	Type in an interest rate, say 0.04.

4	Press OK.

5	Repeat steps 1 through 4, this time setting the value of Deposit, for example to 100.

6	Start the simulation by pressing the Run button [image] Error! Not a valid filename. in the toolbar.

7	Observe how the Account develops in the time graph object.

8	Run the simulation again, and verify that Interest and Deposit are kept unchanged.

9	Now press Run Step [image] Error! Not a valid filename., which will simulate one step and pause the simulation.

10	Modify Interest to 0.03.

11	Press the Pause button to continue simulation.

12	Run the simulation again, and verify that Interest is still 0.03.

This exercise demonstrates how values can be carried over from one simulation to another. Several other objects that the number object has the Keep Value setting, for example the slider/bar, button and array graph objects.

The described model can be found as the file INI_KEEP.SIM that comes with Powersim.

To clear kept values

If you want Powersim to "forget" the values that are kept in various dynamic object, you can use the Clear Results command which is located in the Simulate menu.


Initializing parameters before the simulation starts

Normally values can be set only during simulation. There are, however, a few exceptions, which you find in the list of Control parameters. You can, for example, set the Control.Pause parameter on or off at any time, regardless of the simulation state. Try, for example, to create a button object with Control.Pause as parameter. As another example, you can set Control.Play to something else than zero while in edit mode to start the simulation.

For normal object parameters, however, no value can be set unless the simulation is running. But, as described in the previous section, objects with the Keep Value option are capable of receiving input also when the model is not running. Values entered between simulations (or before the first simulation) will be used to initialize the model when a new simulation start. See Keeping values between simulations  for a step-by-step instruction how to create a model with objects that can be edited before a simulation starts.

As an alternative to using Keep Values, you can pause the simulation immediately after it has started and edit parameter values before you uncheck the pause. Follow the steps below:

To pause the simulation immediately after it has started

There are many ways to achieve this.

Method A: Run + Pause

The highest challenge is to hit Run and then hit Pause as soon as possible afterwards.

1	Press run.

2	Press pause.

Below we'll give you some less athletic options.

Method B: Pause + Run

1	Press the pause button.

2	Press run.

The simulation will now go into pause immediately after it has started. Changes to variables in this state will influence the initial state of the model.

Method C: Run Step

1	Press Run Step.

The Run Step command will simulate one step before it pauses the simulation. Changes to variables in this state will not influence the initial state of the model. Instead the current state is modified, with consequences for this step and the rest of the simulation.

There are also some automatic ways of pausing the simulation. You can for example use the PAUSEIF function or the PAUSEWHILE function, as described below.

Method D: Function PAUSEIF

1	Create a variable, say Pause_At_Start, and define it to PAUSEIF(TIMEIS(STARTTIME))

A model containing such a variable will pause during the initialization step. Now you can enter values of parameters, and uncheck the pause to continue.

Note that PAUSEWHILE(TIMEIS(STARTTIME)) will cause the simulation to get blocked in pause mode at the initialization step. There is no way that you can get the simulation to proceed.

Method E: Function PAUSEWHILE

Sometimes we want to pause the simulation whenever a given condition is met. As an example, we can create a model that will not run before the user has entered a number greater than 100 for a given parameter. If we name the parameter Limit, then we can do the following:

1	Create a variable, say Pause_On_Low, and define it to PAUSEWHILE(Limit < 100)

A model containing a variable like this one, will pause whenever Limit gets lower than 100. If the Limit is increased to a value greater than or equal to 100, the model will continue to run once you uncheck the Pause button.

Method F: Pause while presenting multimedia

You can also use the multimedia object to pause a simulation. Below is an example where a message box is presented when the simulation starts. The simulation continues when the user presses OK.

1	Create a multimedia object in the model.

2	Double click on the object to open the Define Multimedia dialog box.

3	Type Introduction in the Name field.

4	Choose Message Box in the Type combo box.

5	Choose Control in the Model combo box.

6	Choose Control.Play in the Parameter combo box.

7	Choose > as the Operator and type 0 in the Value field. This means that the message box will be displayed when the simulation starts.

8	Check on Pause while Presenting. This will cause the simulation to be paused while the message box is displayed.

9	Press Append to create the message box presentation.

10	Type a message in the Text field. Press Ctrl+Return to make a line break in the text.

11	Type a text in the Window Title field.

12	Choose OK in the Buttons combo box.

13	Choose Information in the Icon combo box.

14	Press OK two times to close the open dialog boxes.

15	Save your model.

16	Press the run button [image] to start the simulation. A message box will appear. When you press OK, the message box disappears, and the simulation continues.

Note	The described model can be found as the file INI_MED.SIM that comes with Powersim.


Initializing values from the network simulation object

When creating a network simulation, if can be of interest to vary parameters of the game from time to time, without having to modify the model itself. Therefore the network object has been designed with an Initialization of Game section, found in the Edit Game File dialog box. Below we will create a minimum game setup, to illustrate this feature.

1	Create a new model.

2	Create a network game object [image] inside the model.

3	Create two constants, Decision and Parameter, and define both equal to 0.

4	Double click on the network object and type INI_NET.PSN as the name of the player file.

5	Click on the Edit File button.

6	Select the first (and only) entry in the list inside the Edit Player File dialog box, and press Edit.

7	Type INI_NET.PSS in the Name field and 1 in the Player field.

8	Press Edit File to open the Edit Game File dialog box.

9	Type a name for the game.

10	Press the Add button of the Player/Decision Parameter group.

11	Choose 1 in the Player combo box and Decision in the Decision Parameter combo box.

12	Press OK.

13	Type INI_NET%d.TXT in the Decision Files Mask field.

14	Now we've come to the core of this example; the initialization of parameters. Click the Add button inside the Initialization of Game group.

15	Choose Parameter in the combo box, and type in an initial value of 3, for example.

16	Press OK in each open dialog box.

17	Create a slider/bar object and drag-and-drop the constant Decision into it.

18	Save your model.

19	You can now start the model.

20	Observe that the constant Parameter, which is defined equal to zero, gets the value 3 once the model starts. The value is taken from the network game object, and in particular from the file INI_NET.PSS, which we created in steps 7 through 16 above.

Note	The described model can be found as the file INI_NET.SIM that comes with Powersim.


Modeling Language

The following topics give a formal definition of Powersim's simulation language. They are first of foremost meant for the technically and mathematically oriented users.

See

  Variable Definitions

  Auxiliaries

  Constants

  Levels

  Unit of Measure

  Ranges

  Dimensions

  Expressions and Factors

  Constrained Expressions

  Arrays and Subscripts

  Literals

  Complete Powersim Syntax

  Relationship to other Modeling Languages

  Mathematics

  DYNAMO

  STELLA and ithink


Variable Definitions

Variables are defined in the Define Variable dialog box, which is opened by double-clicking on a variable object in the diagram, or by choosing Define Object from the Edit menu with a variable selected in the diagram. The following components are common to all variable types:

Component	Definition
Variable	variablename
Unit of Measure	unitdefinition
Dimensions	dimensionlist
Documentation	any string of characters
The Dimensions list box is used only if the variable is an array. Definitions of variablename, unitdefinition, and dimensionlist are given later in this section.

See

  Auxiliaries

  Constants

  Levels


Language definition : Auxiliaries
Auxiliaries

Component	Definition
Definition	expression
The expression may refer to index variables defined in the dimensionlist if the variable is an array.


Language definition : Constants
Constants

Component	Definition
Definition	constantexpression
Combining literals and constant functions using the arithmetic operators, will give a constant expression.

Constant functions will return a constant if passed only constant parameters and initialization parameters.

The opposite of constant functions may be called volatile functions, and can be placed in three groups:

•	functions dependent on simulation time

•	functions that use internal levels

•	random functions

Examples of constant expression:

•	INIT(A)

•	5%

•	TIMESTEP

•	STARTTIME

•	RUN

•	SIN(5)*3

Initializing Arrays

A constant is commonly defined as a literals. The literal may refer to index variables defined in the dimensionlist if the variable is an array. Example: [1,2,3](a).

Hint 	All elements of an array constant may be set to the same value by defining it as a scalar. This is illustrated in the following equations view of a constant definition:

const	C(1..3) = 0

An array constant initialized by a literal array is displayed next:

const	ArrConst(1..3) = [1,5,3]

One may also write the following, which is equivalent to the above definition:

const	ArrConst(k=1..3) = [1,5,3](k)


Language definition : Levels
Levels

Component	Definition
Initial	expression
Flow	flowlist
Both expression and flowlist may refer to index variables defined in the dimensionlist if the variable is an array.

Normally, flow lists need not be edited by the modeler, as Powersim automatically creates flow definitions that correspond to the flows that are connected to a level. In the Define Variable dialog box the factor part of a flow is expressed as a parenthesized expression, i.e., (expression). Only the expression may be edited by the user. For arrays, however, it may be necessary to modify the default flow definitions.

The flow list of a level consists of zero or more flows:

flow flow ...

Flow list definition

Each flow starts with a sign, indicating the direction of the flow (+ means into the level, - means out).

+ dt * factor

- dt * factor

Flow definition

Multiplication with dt

The multiplication with dt in a flow is done in order to give the flow equation the same unit of measure as the level variable itself. Multiplication with dt also adjusts the value of the flow to the solution interval of the numerical integration that takes place during a simulation.

Since flows (rates) are time-relative, one has to multiply with the time step in order to obtain a flow which may be added or subtracted from a level.

Example 	The rate Births may be defined as the number of new-borns in a population per year. If the level Population is defined as the number of persons in a population, it will not make sense to add the value of the variable Births directly to Population. By multiplying Births with the time step, dt, one gets (an approximation of) the number of new-borns in the current time step. The resulting value may be added to Population in determining the number of persons the population will contain at the next step in time.

In some cases a level may itself be time-relative, as illustrated in the demo ACCEL.SIM), which displays the relationship between Acceleration, Velocity, and Distance. Therefore, Powersim also allows levels to control flows directly.


Unit of Measure

Units are defined in the Define Unit dialog box, which is opened by choosing Define Unit from the Edit menu. The components of a unit are defined like this:

Component	Definition
Unit (name)	unitname
Definition	unitdefinition
Description	any string of characters
The syntax of a unit definition should follow the rules below.

number

unitname

unitdefinition / unitdefinition

unitdefinition * unitdefinition

unitdefinition ^ integer

( unitdefinition )

Unit definition

Examples:

Unit definition	Description
m	meter
m/s	meter per second
m*m	square meters, m2
m^3	cubic meters, m3
USD/hr	Dollars per hour
knot	Knots (Speed at sea)
Unit definitions are also used in the Unit of Measure box of the Define Variable dialog box, and as part of unit specifications in expressions.

{ unitdefinition }

Unit specification definition

An example of an expression with a unit specification is the following:

10 {m/s} * TimeUsed


Ranges

Ranges are defined in the Define Range dialog box, which is opened by choosing Define Range from the Edit menu. The components of a range are the following:

Component	Definition
Range (name)	rangename
Definition	rangedefinition
A range definition may be either a numeric subrange, an enumeration, or an enumeration subrange, as defined below.

lowerbound .. upperbound

elementname, elementname, ...

elementname .. elementname

Range definition

Where lowerbound and upperbound are integer numbers, and elementname is an element name of an enumeration. Examples of ranges are given below:

Range	Type
1..3	Numeric subrange
North, South, East, West	Enumeration
South..East	Enumeration subrange
the Define Range dialog box enforces the correct syntax of a range definition.

References to defined ranges may be part of expressions and dimensionlists. You may also create anonymous ranges that are numerical or enumeration subranges. A range reference is a range name, an element expression or a lower bound element expression followed by an upper bound element expression:

rangename

elementexpression

elementexpression .. elementexpression

Range reference definitions

An element expression may involve the prefix operators plus and minus (no prefix operator is equivalent to plus).

unsignedelementexpression

+ unsignedelementexpression

- unsignedelementexpression

Element expression definition

Unsigned element expressions can be simple arithmetic expressions as well as parenthesized expressions.

elementreference

elementreference+ unsignedelementexpression

elementreference- unsignedelementexpression

( elementexpression )

Unsigned element expression definition

Besides index names, ranges, and integers, element expressions can contain element operators such as FIRST, LAST and COUNT. This allows you to use an expression like FIRST(Location)..LAST(Location)-1 in the dimensions part of a variable definition. Furthermore, it is possible to have element type conversions (examples follow).

INDEX(elementreference)

rangename(elementreference)

indexname(elementreference)

integer

elementname

FIRST(indexreference)

LAST(indexreference)

COUNT(indexreference)

FIRST(rangename)

LAST(rangename)

COUNT(rangename)

Element reference definition

INDEX(indexreference)

enumrangename(indexreference)

indexname

Index reference definition

After all these definitions, it is time for some examples:

Range reference	Explanation
Area	Named range Area
1..3	Numeric subrange
North..East	Enumeration subrange
-5..-3	Numeric subrange with negative bounds
1..LAST(Location)-1	Numeric subrange 1..10 when Location is a numeric subrange 1..11
1..INDEX(East)	Gives a numeric subrange 1..3, since East is the third element of its range (conversion of an enumeration range element to an integer)
Region(2)..Region(3)	Gives a enumeration subrange South..East (conversion of an integer to an enumeration range element)
1..COUNT(i)+1	If i is previously defined to be from 3 to 5, this gives a range from 1 to 4.


Dimensions

Dimensions are used when defining array variables and when using the SUM function as part of an expression. For multidimensional arrays, several dimensions are given, separated with commas.

dimension, dimension, ...

Dimension list definition

Each dimension must contain a range reference. If the dimension is going to be indexed, the range is preceded by an index variable name followed by an equal sign. We therefore have two ways of specifying a dimension:

rangereference

indexname = rangereference

Dimension definition

Examples of dimension definitions:

Dimensions	Explanation
1..3	Numeric subrange without an index variable
Group=1..3	Numeric subrange indexed by an index variable, Group
A=Area	Named range Area indexed by index variable A
1..10, 1..3	Two dimensions without index variable
A=Age, R=Region	Two dimensions indexed by index variable, A and R


Expressions and Factors

Expressions are used in the Define Variable dialog box when defining variables. Below are some examples:

Expression	Explanation
10	Literal number
-Payment	Minus operator with argument Payment
7%	Per cent operator with argument 7
A + B	Plus operator with operands A and B
MIN(A, B, C)	MIN function with arguments A, B, and C
(A + B) * 3	Grouping using parentheses
[1, 2, 3](I)	Indexing a literal array
In short, an expression may be constructed in one of the following ways:

factor

prefixoperator expression

expression postfixoperator

expression infixoperator expression

lastconstrainedexpression

constrainedexpressionlist lastconstrainedexpression

Expression definition

Unary operators take only one argument, and are either prefix or postfix. Binary operators take two arguments.

Factors are the remaining building blocks for expressions, and may be constructed in one of the following ways:

literalnumber

literalarray

literalarray subscript

variablename

variablename subscript

functionname

function(expression, expression, ...)

( expression )

INDEX(indexreference)

INDEX(elementreference)

SUM(dimensionlist; expression)

elementoperator(elementreference)

Factor definition

A literalnumber is a literal integer or real value, e.g., 3.14.

A literalarray is used to denote a literal array, e.g., [1, 2, 3].

A subscript is a parenthesized list of an index expression (which may include range references) which is used to select elements from literal arrays or array variables. If a subscript contains a range, the result of the subscribed array will itself be an array (example: A(2, 3..4)).

Variablename denotes a variable name. Functionname denotes the name of a function.

A parameter list is a parenthesized list of arguments. (The terms "argument" and "parameter" are equivalent when used in connection with functions.) Arguments are separated by commas, and each argument must be an expression.

A parenthesized expression is considered a factor.

Finally, we have the SUM and INDEX functions.

Below are some examples of factors:

Factor	Explanation
10	Integer number
2.432	Real number
A	Variable
[1, 2, 3]	Array
Pop(3)	Indexed array variable
[10, 20, 30](I)	Indexed literal array
TIME	Function with no arguments
MIN(A, B, C)	Function with three arguments
(A + 1)	Parenthesized expression
SUM(i=1..3; A(i))	Sum of elements, i.e., A(1)+A(2)+A(3)
The difference between an expression and a factor, is that the parts of a factor are grouped tighter syntactically than the parts of an expression. Expressions are therefore illegal at certain places of a model, since the use of binary operators might otherwise cause ambiguity when parsing the model.


Constrained Expressions

It is very common that certain elements of an array need special treatment. Because Powersim performs strict type and range checking on all array subscript, it is sometimes not possible to define an array using only regular expressions involving, for example, the IF - Arithmetic If  function.

The use of index variables in connection with array variables allows for the special handling of certain elements of the variables involved.

Constrained expressions make it possible to enter alternative definitions for different elements of an array. For example, we may enter one definition for the first element of an array, while the rest of the elements are defined by another expression.

A list of constrained expressions defines a variable in terms of several alternative expressions. The alternative constrained expressions are separated by the constraint operators, semicolon (;) or BUT. The two operators are syntactically equivalent. For the sake of clarity you should choose one and use it in all definitions. Which one you choose, is a matter of style.

constrainedexpression BUT constrainedexpression BUT ...

constrainedexpression ; constrainedexpression ; ...

Constrained expression list definition

Each alternative expression of a constrained expression list is accomplished by a constraint, specifying the index range(s) for which that expression is going to be used.

expression constraint

Constrained expression definition

A constraint consists of one or more list of guards, preceded by the guard operators, vertical bar (|) or WHEN. The two operators are syntactically equivalent (see comments for the constraint operators above). If there are more than one guard list for a constraint, they are separated by OR .

WHEN guardlist

WHEN guardlist OR guardlist OR ...

| guardlist

| guardlist OR guardlist OR ...

Constraint definition

A constraint involving several index variables is expressed as a list of guards separated by AND.

guard

guard AND guard AND ...

Guard list definition

If the logical expression following the guard operator ( | or WHEN) is true, the constraint is said to be true. In a list of constrained expressions only one constraint must be true at the same time. The value of the corresponding expression is used as the value of the entire list of expressions.

Example	A(i+1) | i<LAST(i); A(1) | i = LAST(i)

The above expression will be equal to A(i+1) for i < LAST(i) and equal to A(1) for i = LAST(i). The expression may be read like this: "A(i+1) when i < LAST(i) but A(1) when i = LAST(i)". Indeed, with the alternative operators WHEN and BUT, the above expression can be written like this:

Example	A(i+1) WHEN i<LAST(i) BUT A(1) WHEN i = LAST(i)

The last constrained expression in the list can be somewhat special as seen in the definition below:

constrained expression

expression WHEN DEFAULT

expression | DEFAULT

expression OTHERWISE

expression

Last constrained expression definition

Below is an example where the above definition is used (it is also an example illustrating the use of the OR operator in constraints):

Example	A(i) | i=1 OR i=4; 0 | DEFAULT

Here A(i) will be chosen as the value of the constrained expression list when i is either 1 or 4. Otherwise the expression will be zero. In fact, you can use the new operator OTHERWISE as a substitute for the combination "| DEFAULT" as shown in the example below:

Example	A(i) WHEN i=1 OR i=4 BUT 0 OTHERWISE

The OTHERWISE constraint can be used to cover all index values that do not fall into one of the previous guards in the list of constraints. OTHERWISE is only allowed in the last constraint of a constraint list.

Hint	There is a shorthand method that can be used for the final constraint of a constraint list. If the final constraint has no guard, this serves as a "default" or "otherwise" guard, i.e., that the value of the final expression is used when all preceding guards are false. Below are four expressions with the same meaning:

(Births | A=FIRST(A); 0)

(Births | A=FIRST(A); 0 | DEFAULT)

(Births WHEN A=FIRST(A) BUT 0 OTHERWISE)

(Births | A=FIRST(A); 0 | A>FIRST(A))

An example with a constrained expression containing the AND operator follows:

Example	A(i+1, j-1) | i < 3 AND j > 1; 0 | DEFAULT

The above expression will be equal to A(i+1, j-1) when i < 3 and j > 1. Otherwise it will be zero.

The guards of a guard list must involve different index variables. The constrained expression, for example, below is illegal:

A(i) | i >= 3 AND i <= 9	"Illegal - Index variable constrained twice"

Instead you should write:

A(i) | i = 3..9

The rules for writing guards are the following:

indexreference < elementreference

indexreference <= elementreference

indexreference >= elementreference

indexreference > elementreference

indexreference <> rangereference

indexreference = rangereference

Guard definition

Here element must be a member of the same base range as the index variable, and range must be a subrange of that range. Type conversions and the functions INDEX, FIRST, LAST, and COUNT may be used. Below are some examples:

Region >= North

I=2..3

K=Adult..Old

I < LAST(I)

A > AGE(3)

Note	There is a subtle difference between the IF function and a constrained expression. IF may be used to choose between two expressions, on the basis of a condition. Constrained expressions are used to choose between expressions on the basis of guards.

As an example, the two expressions below may look quite similar with respect to the computed result:

IF(INDEX (i) < 4, A(i+1), A(1))

(A(i+1)|i<4; A(1))

If A is defined as an array with elements 1 through 4, the first expression will produce a range check error in the expression A(i+1) as the expression must be valid for all values of i (we assume i=1..4).

In the last example, indices are checked only for expressions with guards that are true. When i < 4 the subscript (i+1) will be legal for A.


Arrays and Subscripts

Array variables and literals may be subscribed.

( rangeorindexexpression, rangeorindexexpression, ...)

Subscript definition

There must be as many range or index expressions as there are dimensions of the indexed variable. A range or indexexpression can be a range reference, an index expression or an index expression preceded by a sign (+ or -).

Furthermore, an asterisk (*) may be used in referring to an entire dimension.

rangereference

indexexpression

+ indexexpression

- indexexpression

Range or index expression definition

Each index expression  is either an element reference, an index reference or a simple arithmetic expression of index expressions.

indexexpression

+ indexexpression

- indexexpression

indexexpression + indexexpression

indexexpression - indexexpression

elementreference

indexreference

Index expression definition

As you might recall, element references may contain the functions INDEX, FIRST, LAST and COUNT. The FIRST function returns the first element of a range or the lower limit of an index variable. Correspondingly LAST returns the last element or upper limit. COUNT is used to obtain the number of elements in a range and the number of distinct values of an index variable. INDEX converts an index to a number.

Note	Index expressions are subject to strict type checking. This means that it is illegal to index a variable with an index that does not belong to the same base range that is being used to define the corresponding dimension. Range type conversions may be done by using a range name as a function with an index expression as argument. As an example, the index expression Age(2) returns the second element of Age, which must be a range.

Examples of array subscripts:

Subscript	Explanation
A(2)	Integer subscript
A(i)	Index variable
A(i+1)	Index variable plus offset
A(i,j,k)	Multiple index variables
A(North)	Element reference
A(FIRST(Region))	FIRST function used with range
ARRSUM(A(2,*))	Asterisk (*), sum of all elements with 2 as the first index
A(COUNT(i)+1)	COUNT function used with index variable


Literals

A scalar or numeric literal is a direct representation of a value, e.g., the numeric value 10. Correspondingly, array literals are direct representations of array values.

literalnumber

literalarray

Literal definition

Literal numbers are signed decimal numbers, as for example: 13.14, +2, -123, etc. Independently of the language settings of the Windows Control Panel, a period is always used as the decimal separator when typing numbers.

Note	In dialog boxes the International Number Format setting of the Windows Control Panel determines which decimal separator will be used for numbers. The setting may be overridden by the settings of Options General: Numerical Format in Powersim.

Literal arrays are enclosed in brackets ([...]), and array elements are separated by commas (,):

[ literal , literal , ... ]

Literal array definition

This recursive definition allows us to define arrays where the elements are themselves arrays! This is the way multi-dimensional array literals are defined.

Example 	The definitions below (taken from the equations view of a model) define two ranges and a two-dimensional level which is initialized using a literal array:

range	Age = Child, Young, Adult, Old

range	Sex = Female, Male

init	Pop(Sex, Age) = [[7000, 13000, 30000, 20000], [5500, 12700,29000, 19750]]

The elements of the array may be displayed in a table like this:

Pop	Child	Young	Adult	Old
Female	7000	13000	30000	20000
Male	5500	12700	29000	19750
It should be observed that a multi-dimensional variable need not always be initialized using a multi-dimensional expression. The male and the female population may, for example, be initialized to the same values using index variables:

init	Pop(Sex, A=Age) = [7000, 13000, 30000, 20000](A)

If all elements of an array variable are going to be initialized with the same value, a single number may be used to initialize the variable. In the example above, all elements may be set to 7000, using the following statement:

init	Pop(Sex, Age) = 7000


Complete Powersim Syntax

For the technically minded reader, we bring the complete Powersim syntax using BNF notation.

Overview of Powersim Syntax

<statement> = <unitstatement> |
<rangestatement> |
<levelstatement> |
<auxstatement> |
<conststatement> |
<initstatement> |
<flowstatement>

<unitstatement> = 'UNIT' <unitname> '=' <unitdefinition>

<rangestatement> = 'RANGE' <rangename> '=' <rangedefinition>

<levelstatement> =
 'LEVEL' <variablename> [ <dimensionlist> ] '=' <factor> { <flow> }

<auxstatement> = 'AUX' <variablename> [ <dimensionlist> ] '=' <expression>

<conststatement> = 'CONST' <variablename> [ <dimensionlist> ] '=' <constantexpression>

<initstatement> = 'INIT' <variablename> [ <dimensionlist> ] '=' <expression>

<flowstatement> =
'FLOW' <variablename> [ <dimensionlist> ] '=' <flow> { <flow> }

<unitdefinition> = <literalnumber> |
<unitname> |
<unitdefinition> '/' <unitdefinition> |
<unitdefinition> '*' <unitdefinition> |
<unitdefinition> '^' <integer> |
'(' <unitdefinition> ')'

<unitspecification> = '{' <unitdefinition> '}'

<rangedefinition> = <integer> '..' <integer> |
<elementname> { ',' <elementname> } |
<elementname> '..' <elementname>

<rangereference> = <rangename> |
<elementexpression> [ '..' <elementexpression> ]

<elementexpression> = [<sign>] <unsignedelementexpression>

<unsignedelementexpression> = '(' <elementexpression> ')' |
<elementreference> [<sign> <unsignedelementexpression>]

<elementreference> = 'INDEX' '(' <elementreference> ')' |
<rangename> '(' <elementreference> ')' |
<indexname> '(' <elementreference> ')' |
<integer> |
<elementname> |
<elementoperator> '(' <indexreference> ')' |
<elementoperator> '(' <rangename> ')'

<elementoperator> = 'FIRST' |
'LAST' |
'COUNT'

<indexreference> = 'INDEX' '(' <indexreference> ')' |
<enumrangename> '(' <indexreference> ')' |
<indexname>

<dimensionlist> = <dimension> { ',' <dimension> }

<dimension> = [<indexname> '=' ] <rangereference>

<flow> = <sign> 'dt' '*' <factor>

<expression> = <factor> |
<prefixoperator> <expression> |
<expression> <infixoperator> <expression> |
<expression> <postfixoperator> |
{<constrainedexpression> <but>} <lastconstrainedexpression>

<factor> = <literalnumber> |
<literalarray> [ <subscript> ] |
<variablename> [ <subscript> ] |
<functionname> [ '(' [ <expression> { ',' <expression> } ] ')' ] |
'(' <expression> ')' |
'INDEX' '(' <indexreference> ')' |
'INDEX' '(' <elementreference> ')' |
<elementoperator> '(' <elementreference> ')' |
'SUM' '(' <dimensionlist> ';' <expression> ')'

<lastconstrainedexpression> = <constrainedexpression> |
<expression> <when> DEFAULT |
<expression>

<constrainedexpression> = <expression> <constraint>

<constraint> = <when> <guardlist> { 'OR' <guardlist> }

<guardlist> = <guard> { 'AND' <guard> }

<guard> = <indexreference> <indexeoperator> <elementreference> |
<indexreference> <indexroperator> <rangereference>

<when> = 'WHEN' | '|'

<but> = 'BUT' | ';'

<subscript> = '(' <rangeorindexexpression> { ',' <rangeorindexexpression> } ')'

<rangeorindexexpression> = <rangereference> |
'*' |
[<sign>] <indexexpression>

<indexexpression> = <indexexpression> <sign> <indexexpression> |
'(' [ <sign> ] <indexexpression> ')' |
<elementreference> |
<indexreference>

<prefixoperator> = '+' | '-' | 'NOT'

<infixoperator> = '+' | '-' | '*' | '/' | 'MOD' | 'AND' | 'OR' | 'XOR' | '^'

<postfixoperator> = '!' | '%'

<indexeoperator> = '<' | '<=' | '>' | '>='

<indexroperator> = '=' | '<>'

<sign> = '+' | '-'

<literal> = <literalnumber> | <literalarray>

<literalarray> = '[' <literal> ',' <literal> ',' ... ']'

<variablename> = <functionname> = <indexname> = <elementname> = <rangename> = <enumrangename>=<unitname> = identifier, e.g. POP2

<integer> = integer, e.g., -2, -3, 0, 1, 2, 3

<literalnumber> = decimal number, e.g. 123.45

<constantexpression> = <expression> (see Constants in Variable Definitions)


Relationship to Other Modeling Languages

The following topics describe how Powersim's modeling language relate to the languauge of mathematics and two other modeling tools; Dynamo and Stella/ithink.

See

  Mathematics

  DYNAMO

  Statement Types

  Functions

  Population Model Illustrating Differences in Array Syntax

  STELLA and ithink

  Functions

  Level Types


Mathematics

Powersim equations correspond in many ways to ordinary mathematics. Most expressions in Powersim are written exactly as in the mathematics literature. Some differences arise from the fact that Powersim uses a standard character set, which does not include symbols such as Σ, ∫, δ, etc. The table below shows some of the most important differences between standard mathematical notation and Powersim expressions.

	Mathematics	Powersim
Multiplication:	ab	a * b
Indices:		A(i) when i is an index expression or LOOKUP (A, I) when i is a normal expression
Exponentiation:		x^2
Square root:		SQRT (x)
Sum over index:		SUM (i=1..n; X(i)) If X is a vector or an array, ARRSUM(X) may be used.
Integral:		level A = B + C*dt, or aux A = B + integrate (C)
Composite function:		aux f(x) = g(x) | x < 0; h(x) | x = 0; i(x) | x > 0
Vector:	V=(V1, V2, V3)	aux V(1..3) = [v1, v2, v3], or aux V(1..3) = VECTOR(v1, v2, v3)
Matrix:		aux A(1..3, 1..3) = [[a11,a12,a13], [a21,a22,a23], [a31,a32,a33]]
Scalar product or Inner product of vectors:		SPROD (a, b)
Length of vector:		VECTLEN (v)
First derivative:	f'(t)	DERIVN (F)
Second derivative:	f''(t)	DERIVN (F, 2)


Dynamo

The equations view of a Powersim model is in many ways similar to the equations of a Professional Dynamo Plus model. There are, however, several differences.

See

  Statement Types

  Functions

  Population Model Illustrating Differences in Array Syntax


Statement Types (Dynamo vs. Powersim)
Statement Types

One difference between Dynamo and powersim is that there are more types of statements in Dynamo. The following list displays the statement types of Dynamo along with the corresponding statement types of Powersim, where appropriate:

	DYNAMO	Powersim
Auxiliary:	A	AUX
Boolean:	B	Constants, auxiliaries, and levels may all be used as booleans in Powersim
Constant:	C	CONST
Exogenous:	E	Use constant in Powersim, and define as parameter to dynamic object or transfer object
Given initial value:	I	INIT
Re-initial value:	K	Use INIT in Powersim
Level:	L	LEVEL
Computed initial:	N	INIT (used with levels)
Parameter:	P
Rate:	R	Constants, auxiliaries, and levels may all be used as rates in Powersim
Supplementary:	S	Use an auxiliary in Powersim
Specification:	SPEC
Table:	T	Constants, auxiliaries, and levels may all be used as tables in Powersim
Powersim does not use the time-scripts .J, .K, .JK, and .KL as does Dynamo. When converting models from Dynamo to Powersim, just delete the time-scripts.


Functions (Dynamo vs. Powersim)
Functions

The following table contains the functions of Dynamo that are not directly available in Powersim. The column to the right shows the corresponding Powersim functions.

DYNAMO	Powersim
(A)(B)	(A)*(B)
A**B	A^B
CLIP(P, Q, R, S)	IF (R >= S, P, Q)
DELAY1(In, Del)	DELAYMTR(In, Del, 1, 0)
DELAY3(In, Del)	DELAYMTR(In, Del, 3, 0)
DELAYP(In, Del, PPL)	DELAYMTR(In, Del, 3, 0)
DLINF3(In, Del)	DELAYINF(In, Del, 3, 0)
DT	TIMESTEP
FIFGE(P, Q, R, S)	IF (R >= S, P, Q)
LOGN(A)	LN (A)
NOISE()	RANDOM(-0.5, +0.5)
NORMRN(Mean, StdV)	NORMAL(Mean, StdV)
PULSE(H,W,F,I)	IF (TIMECYCLE(F, I, W),H,0)
SAMPLE(X, Interval, X0)	SAMPLE(X, Interval, 0, X0)
SMOOTH(In, Del)	DELAYINF(In, Del, 1, In)
SWITCH(P, Q, R)	IF (R = 0, P, Q)
TABHL(Y, X, XL, XH, Dx)	GRAPH(X, XL, Dx, Y) Powersim uses the number of elements of Y to compute the value of XH, which is explicitly given in DYNAMO.
TABLE(Y, X, XL, XH, Dx)	GRAPH(X, XL, Dx, Y)
TABPL(Y, X, XL, XH, Dx)	GRAPHCURVE(X, XL, Dx, Y) In Powersim the array Y of the GRAPHCURVE function should not include the terminating zeros, as in DYNAMO.
TABXT(Y, X, XL, XH, Dx)	GRAPHLINAS(X, XL, Dx, Y)
The most significant difference between Dynamo and Powersim equations is probably the array syntax.


Population Model Illustrating Differences in Array Syntax

The following example displays the same model using arrays in DYNAMO (Source: Professional DYNAMO Plus Reference Manual, 1986, p. 75.) and Powersim.

FOR AGE=YOUTH,YADLT,MDLAG,OLDST

FOR AGE2=YADLT-OLDST

FOR REGION=NORTH,SOUTH

N POP(AGE,REGION) = IPOP(AGE,REGION)

I IPOP(*, NORTH) = 1000, 950, 900, 400

I IPOP(*, SOUTH) = 800, 750, 700, 1000

L POP.K(YOUTH,REGION) =POP.J(YOUTH,REGION)+DT*(TBRTH.JK(REGION)^

-AGOUT.JK(YOUTH,REGION)-DTH.JK(YOUTH,REGION))

L POP.K(AGE2, REGION) = POP.J(AGE2,REGION)+DT*(AGOUT.JK(AGE2-1,REGION)- AGOUT.JK(AGE2,REGION)- DTH.JK(AGE2,REGION))

R TBRTH.KL(REGION) = BRTHRT(1)*POP.K(YADLT,REGION)^

+ BRTHRT(2)*POP.K(MDLAG,REGION)

P BRTHRT = 12E-3, 5E-3

R AGOUT.KL(AGE, REGION) = POP.K(AGE,REGION) * DTHRT(AGE)

P DTHRT = 1.9E-3, 0.8E-3, 6.6E-3, 65E-3

A TOTPOP.K=SUM(POP.K)

The corresponding Powersim model is listed below:

range	Age = Youth, Yadlt, Mdlag, Oldst

range	Region = North, South

level	Pop(A=Age,R=Region) = IPop

+dt*(TBrth(R) | A=Youth; 0)

+dt*(AgOut(A-1,R) | A>Youth; 0)

-dt*(AgOut)

-dt*(Dth)

aux	AgOut(A=Age,Region) = Pop/Prd(A)

aux	Dth(A=Age,Region) = Pop*DthRt(A)

aux	TBrth(R=Region) = Pop(Yadlt,R)*BrthRt(Yadlt) + Pop(Mdlag,R)*BrthRt(Mdlag)

aux	TotPop = ARRSUM(Pop)

const	BrthRt(Yadlt..Mdlag) = [12E-3, 5E-3]

const	DthRt(Age) = [1.9E-3, 0.8E-3, 6.6E-3, 65E-3]

const	IPop(Age,Region) = [[1000,800], [950,750], [900,700], [400,1000]]

const	Prd(Age) = [12,25,20,1E30]

The Powersim diagram is shown in the figure below:

We see how people are born (TBrth) into the population (Pop), move from age group to age group (AgOut) inside the population, and die (Dth) out of the population.


STELLA and ithink

In a manner similar to STELLA and ithink, Powersim uses a diagram to edit models. Indeed the diagrams of STELLA/ithink and Powersim have a lot in common, as both build on system dynamics accumulator and flow diagrams as defined by Jay W. Forrester around 1960.

See

  Functions

  Level Types


Functions (STELLA/ithink vs. POWERSIM)
Functions

Most STELLA/ithink models are easily converted to Powersim. The following table shows the STELLA/ithink functions along with the corresponding Powersim functions (the functions that are the same in both packages have been omitted).

STELLA/ithink	Powersim
A % B	A MOD B
DELAY(In, Duration, Init)	DELAYPPL(In, Duration, Init)
DT	TIMESTEP
INT(X)	FLOOR(X)
LOG10(X)	LOG(X) or LOG(X, 10)
LOGN(X)	LN - Natural Logarithm (X)
MEAN(X, ...)	AVG(X, ...)
MOD(A, B)	A MOD B
OSTATE(Oven)	Ovens are not built into Powersim, but may be created using explicit modeling.
POISSON(Mean)	POISSON(Mean * TIMESTEP) / TIMESTEP
QELEM(Queue, Element)	Can be modeled using QUEUE function and arrays.
QLEN(Queue)	Queue length is output parameter of QUEUE function.
SMTH1(In, Duration, Init)	DELAYINF(In, Duration, 1, Init)
SMTH3(In, Duration, Init)	DELAYINF(In, Duration, 3, Init)
SMTHN(In, Duration, N, Init)	DELAYINF(In, Duration, N, Init)
SUM(X, Y, Z...)	X+Y+Z+...
SWITCH(A, B)	IF(A > B, 1, 0) or simply (A > B)


Level Types (STELLA/ithink vs. POWERSIM)
Level Types

STELLA/ithink has several kinds of levels (stocks), namely: Reservoirs, Conveyors, Queues, and Ovens. Powersim's levels correspond to Reservoirs. The other stock types may, however, be created using a combination of variables and functions in Powersim.

Conveyor

A conveyor may be modeled using a flow through a level where the output level is a DELAYPPL function (pipeline delay) of the input flow. Demo: CONVEYOR.SIM.

Queue

A queue may be modeled very much like a conveyor. The queue accepts input in one end, and delivers output at the other. Each time step the elements of the queue are shifted one position to the right. The shift may be made conditional, i.e., dependent on the ability to serve output at the start of the queue.

See also

Queue with Multiple Clients And Servers

Oven

Ovens are more complex than conveyors and queues and request more modeling to be represented in Powersim. The diagram below shows one way to make an Oven.

The equations of the above model are given next (note the use of SHIFTCIF to change between discrete states):

level	Oven = 0 -dt*(Empty) +dt*(Fill)

level	Timer = FillTime +dt*(StartTimer) -dt*(TimeGoes)

aux	Empty = IF(State(3), EmptyRate, 0)

aux	Fill = IF(State(1), FillRate, 0)

aux	StartTimer = PULSEIF(StartFilling, FillTime-Timer)+PULSEIF(StartBaking, BakeTime-Timer)

aux	StartBaking = State(1) AND ((Timer <= 0) OR (Capacity <= Oven))

aux	StartEmptying = State(2) AND (Timer <= 0)

aux	StartFilling = State(3) AND (Oven <= 0)

aux	StateTransition = SHIFTCIF(StartBaking OR StartEmptying OR StartFilling, State)

const	State(1..3) = [1,0,0]

const	TimeGoes = 1

const	BakeTime = ...

const	Capacity = ...

const	EmptyRate = ...

const	FillRate = ...

const	FillTime = ...


Menu Commands

This topic provides a detailed description of all commands found in Powersim's menus.

Overview of menus

Menu	Used to
File	Create, open, save, and print documents; and quit Powersim
Edit	Undo, delete, copy, paste, define, scale and search
View	Choose view, customize editor, and zoom diagram
Format	Format the model and open the options panel
Simulate	Set up and control simulation runs
Color	Color selected items
Tools	Select modeling tools and static and dynamic objects
Window	Rearrange windows or activate specified windows
Help	Get help on using Powersim
See also

Choosing a Menu Command


Choosing a Menu Command

Using the Mouse

1	Point to a menu name

2	Click the left mouse button to display the menu

3	Point to a command name

4	Click on the command name with the left mouse button

Using the Keyboard

1	To make the menubar active, press the Alt key

2	To display a menu, press the underlined letter in the menu name

3	To choose a command, press the underlined letter in the command name

Hint	Powersim assigns some commands to shortcut keys so you can choose the commands without displaying a menu. If a command has shortcut keys, the keys appear in the menu next to the command.


File menu

Use this menu to open, save, and print documents or to quit Powersim. To use a document, you must first open and display it on your screen. You can then build and simulate models.

Overview of File menu commands

New - Creates a new document

Open - Opens an existing Powersim document

Close - Closes all windows of the active document

Save - Saves changes made to the active document

Save As - Saves and names the active document

Save All - Saves all open, changed documents

Page Setup - Defines page setup for the current document

Print - Prints the active window according to the parameters you specify

Print Setup - Identifies the printer you want to use and sets options for it

Properties - Displays properties of the active document

Exit - Quits Powersim, prompts you to save any unsaved documents


New

Use this command to create a new Powersim document. Powersim gives the new document a temporary name, such as "Diagram1", until you save it with a unique filename.

To quickly create a new document, click New [image] on the commandbar.


Open

Use this command to open an existing Powersim document.

To quickly open a document, click Open [image] on the commandbar.

Hints

•	When you start Powersim, a blank document opens in a window on the screen (provided that "Create New Document on Startup" is checked in the GeneralGeneral_options>main options dialog box). You can then start modeling. To continue work on a document stored on a disk, you open the document using the Open command.

•	If you have recently worked on a document, you may be able to open it again by choosing it from the bottom of the File menu, where Powersim lists the documents you opened most recently.

•	Powersim allows you to work on several opened documents at the same time. Use the Window menu to move between document windows as you work.

See also

Open dialog box

Protection Password dialog box

Opening a Model Containing Co-models

Opening an Existing Document on Startup


Open dialog box

Dialog box options

File Name

Type or select the name of the file you want to open. This box lists files with the extension you select in the List Files of Type box. If the document you want to open is not listed in the File Name box, do one or more of the following:

•	In the Drives box, select a new drive.

•	In the Directories box, select a new directory.

•	In the List Files of Type box, select the type of document you want to open with its three-character extension.

You can also see a list of all files with a specific extension in a drive or directory. In the File Name box, type an asterisk (*) before a period (.) and the extension. For example, to see all the files with a TXT extension in a directory, type "*.TXT" in the File Name box. To see all the files in a directory, type "*.*".

Directories

Select the directory in which the file you want to open is stored.

Drives

Select the drive in which the file you want to open is stored.

List Files of Type

Select the type of file you want to open. Available file types are listed below:

File type	Lists
Powersim Document (*.SIM)	All files in the current directory with a SIM extension
All files (*.*)	All files in the current directory


Protection Password dialog box

When you try to open a file that is protected by a password, the Protection Password dialog box is first opened, and you are asked to enter the password.

Dialog box options

Enter password for file ...

Type the password in the text box and hit OK. If you choose Cancel or if the password is incorrect, the file will not open.

To set a new password for the document, hit the Password button in the Save As dialog box.


Opening a Main Model Containing Co-models

If one or more co-models can't be found while opening a main model, Powersim launches an additional dialog box (Can Not Find Co-Model File) that lets you specify a new location for the co-model(s) in question. If you save the main model again, the new co-model locations will be saved as well.


Opening an Existing Document on Startup

You can make Powersim automatically open a document on startup by giving the desired document name as a parameter in the command that starts Powersim. In the following command example, Powersim will automatically open the document POP.SIM on startup:

C:\POWERSIM\POWERSIM.EXE POP.SIM

To open a document on startup in Windows 3.1x or Windows NT

1	Open the Program Item Properties dialog box from Windows Program Manager

2	Enter the desired simulator document name as a parameter to the Powersim exe-file in the Command Line text box.

To open a simulator document on startup in Windows 95

1	Open the Taskbar Properties dialog box by selecting Start, Settings, Taskbar

2	Choose the Start Menu Programs tab from the Taskbar Properties dialog box

3	Click the Add button to open the Create Shortcut wizard

4	Enter the desired simulator document name as a parameter to the Powersim exe-file in the Command text box.


Close

Use this command to close all windows containing the active document. If the active document has been changed, a dialog box will appear asking if you want to save your work. If you close a document without saving, you lose all changes made since the last time you saved it. Before closing an unnamed document, Powersim displays the Save As dialog box and suggests that you name and save the document.

Closing Co-models

When the last window of a main model is closed, all windows of its co-models are automatically closed as well. You may close a single co-model window by using the Close command in the window's Control menu. If you try to close the last window of a co-model in this manner, you will be prompted to save changes. See also: Co-models

Close when Editing Embedded Object

When you are editing an embedded Powersim object (see OLE Services Provided by Powersim ), "Close" changes to "Close and Return to <container document>", for example, "Close and Return to CONT.DOC".


Save

To quickly save a document with its existing name, location, and file format, click Save [image] on the commandbar.

When you save a document for the first time

•	Powersim displays the Save As dialog box so you can name your document. If you want to change the name or location of an existing document before you save it, choose the Save As command.

•	If the Save option Prompt for Properties is switched on, Powersim opens the Properties dialog box to let you provide certain kinds of information to help you recall important aspects of the document.

Note	When you open an existing document, Powersim copies it from the disk where it is stored and displays it in one or more document windows. As you work, you are actually making changes to the copy of the document. To keep your latest work safely on the disk, you should frequently save your document. Each time you save a document, it remains open on your screen so you can continue work.

Saving Co-models

Saving a co-model will leave the simulation and scaling information unchanged, since this information is saved in the main model file.

Save when Editing Embedded Object

When you are editing an embedded Powersim object (see OLE Services Provided by Powersim), "Save" changes to "Update". Update forces an update of the Powersim object in the container document. If an area exists (see Creating Areas), the rectangle used for the picture representation of the object is set to this area.


Save As

If you want to save the name or location of an existing document before you save it, choose the Save As command. You can also use this command to change directories.

See also

Save As dialog box

Save As when Editing Embedded Object

Save As for Renaming a Co-model Source File


Save As dialog box

Dialog box options

File Name

Type a new filename to save a document with a different name. Use the current name, or select a name in the list to save a document with an existing filename.

Note	A filename can contain up to eight characters and an extension of up to three characters. If no extension is specified, Powersim adds the extension you specify in the Save File As Type box, normally SIM.

Directories

Select the directory in which you want to store your document.

Drives

Select the drive in which you want to store your document.

Save File as Type

Select the file type of the document to be saved. Available file types are listed below:

File type	Save file in format
Powersim Document	Standard Powersim document
Powersim Equations	Text file containing model equations in order of execution. This type can be useful, for example, for translating your models to other simulation languages.
Password

Click this button to open the Change Protection Password dialog box to specify password protection of your document.


Change Protection Password dialog box

You can protect a document with a password to prevent others from opening it. If you protect a file with a password, you must provide the password each time you open the document. Use the Change Protection Password dialog box to set a protection password for the document.

Dialog box options

Protection Password

Type the new password in the text box. To remove an existing password, leave the text box empty.

Cancel

Click this button to close the dialog box and retain the original password.

OK

Click this button to close the dialog box and open the Confirm Protection Password dialog box. If the text box is empty when you press OK, the current password is removed (provided that you confirm the removal in the Confirm Protection Password dialog box).


Confirm Protection Password dialog box

Dialog box options

Reenter Protection Password

Type the new password again in the text box. To confirm the removal of a password, leave the text box empty.

Cancel

Click this button to cancel the change of the password.

OK

When you hit OK, Powersim checks that you have typed the password in the same way in the Change Protection Password dialog box and the Confirm Protection Password dialog box. If you have not, a message box appears, saying "The password confirmation does not match", and the Change Protection Password dialog box is presented again.


Save As when Editing Embedded Object

When you are editing an embedded Powersim object (see OLE Services Provided by Powersim), "Save As" changes to "Save Copy As". Save Copy As writes a copy of the current object to a file.


Save As for Renaming a Co-model Source File

If you wish to change the name of the source file of a co-model, without having to delete the co-model from the Parallel Simulation list in the Simulation Setup dialog box, do the following:

To rename a co-model source file

1	Open a window of the desired co-model within the main model

2	Make this window active (select it)

3	Choose File Save As and save it under a name


Save All

Use this command to save all open, changed documents. Before saving, Powersim prompts for each unnamed document separately. If you have a new document that has never been saved, Powersim displays the Save As dialog box so you can assign the new document a name before saving it for the first time.

Save All when Editing Embedded Object

When you are editing an embedded Powersim object (see OLE Services Provided by Powersim), "Save All" changes to "Save and Update All". Save and Update All does the same as Save All, except that embedded objects are updated instead of saved.


Page Setup

Use this command to change margins, header and footer, and print size.

Page Setup dialog box

Dialog box options

Margins

Use this group to specify the margin options listed below.

Top

You can set the margin from the top of the page to the top of the diagram.

Bottom

You can set the margin from the bottom of the page to the bottom of the diagram.

Left

You can set the margin from the left edge of the page to the left of the diagram.

Right

You can set the margin from the right edge of the page to the right of the diagram.

Header / Footer

Headers and footers are descriptive texts that print in the top or bottom margin of every page in your document.

In the header or footer text box, you may type the text that you want to appear on each page of your document. You may also insert fields in one of two ways.

•	By pushing Field [image] and selecting among the listed fields in the Field dialog box. (You must first click in either the header or the footer box to activate the Field option.)

•	By typing the appropriate field code directly into the Header or Footer text box.

From Edge

Use this option to display the distance between the Header or the Footer and the top or the bottom of the page, respectively.

Note 	The settings should be coordinated with the Margins settings, found in the same dialog box, to prevent the header/footer from falling outside the top/bottom margins.

The contents of each of the two text boxes is a number followed by the currently chosen measurement unit. To change the measurement unit, choose Format Options and open the General category.

Print Size

The setting of this list determines the printing size to be used. You may choose among the following sizes: 25%, 50%, 100%, 200%, and Fit to One Page. The latter setting ensures that Powersim adjusts everything to print on one page.

Note	The print size affects the page borders and the rulers of the diagram, since both of them are tied to the printer and not to the screen. If the print size is decreased, the distance between page borders on the screen is increased. Correspondingly, the distance between unit tick marks of the rulers is increased. The zooming percentage of the diagram, however, remains unchanged.

Field

Click this button to open the Field dialog box so you can insert fields in the Header or Footer text box.

Opening the Field dialog box from inside the Page Setup dialog box gives you a list of field types relevant for the header and footer in a printout. Available field types are listed in Field Types and Instructions .


Print

Use this command to print your documents.

Print dialog box

Printer

Use this option to display the active printer and printer connection. To specify a printer and its connection, click on the Setup button.

Printer

Use this option to display the active printer and printer connection. To specify a printer and its connection, click on Setup [image].

Print What

The settings here determine the contents of a print-out. Use the list box to select what you want to print (see the table below).

Selection	Result
Diagram	Prints only the diagram. All variables and presentations that are visible in the diagram view will be printed.
Equations	Prints only the equations. The printing corresponds to the information displayed in equation view.
Diagram + Equations	Prints diagram and equations. The diagram is printed first.
Front Page

Check this box to include a front page containing information from the Properties dialog box (title, author, and description).

Empty Pages

Check this box to print empty pages as well as pages with contents.

Print Range

Use this group of options to specify the range of a print-out.

All

Use this option to print the entire document.

Selection

Use this option to print the currently selected part of the diagram.

Window/Area

Use this option to print the current window or diagram area. If no area exists, this option is named Window, meaning that the current window is printed. If an area exists, this option is named Area, meaning that only the contents of that area is printed.

Pages

Use this option to print specific pages, or ranges of pages, by typing the appropriate numbers in the From and To boxes.

From - To

Specify the number of the first and last page you want to print. If you leave a box blank, all remaining pages (or all preceding pages) will be printed. Examples are shown below:

From	To	Print result
1	1	Page 1
3	-	Page 3 to end of document
2	3	Pages 2 and 3
-	5	Beginning of document to page 5
3	1	Pages 3 to 1 in reverse order
Print Quality

Choose the resolution (typically measured in dots per inch; DPI) at which you want to print graphic images. Open the list and choose the resolution you want to use.

Note 	If diagrams print only partially, the reason may be that your printer does not have enough memory. Reduce the Print Quality (for example, from 300 to 150 DPI) and try printing again.

Copies

Type or select the number of copies you want to print.

See also

Troubleshooting Print


Print Setup

Use this command to choose printer, orientation, paper size, source, etc.

Print Setup dialog box

Dialog box options

Printer

Use this group to choose the printer you want to use. Only printers you have installed will appear.

Default Printer

If you select this option, the printer established as the default by the Windows printer setup will be used. If you change the system default printer, all documents that were stored with the default printer setting will automatically print on the new printer.

Specific Printer

Select this option to choose a particular target printer from the drop-down list. This choice is stored with the document so that the document will always print on that printer, even if the system default printer is changed.

Orientation

Portrait

If you choose portrait mode, your document will print vertically on the page.

Landscape

If you choose landscape mode, your document will print horizontally on the page.

Note	If one of the modes is not available for the current combination of printer and paper type, the label and option buttons for that mode are dimmed, and the option button for the available mode is selected.

Paper

Use this group of options to choose the size and source of paper you want to use.

Size

Choose paper size from the drop-down list, which specifies the paper sizes that can be loaded into the printer.

Source

Use this option to select the paper source in the printer.

Options

Use this button to display a dialog box so you can set additional printing options (for example, specify dithering, intensity, etc.) that will be stored with the document. This button is dimmed if no such options are provided by the current printer driver.

Note 	If you have a Hewlett-Packard (HP) compatible printer, you should turn on the option "Print True Type as Graphics". If this option is switched off, text will not print properly.

Note 	If you are using a monochrome screen and a black-and-white printer, text, lines, borders, and shadows will always print as black.


Properties

Use this command to display and set key properties of the current document, such as title, author, statistics, and access rights.

See also

Properties dialog box

Statistics dialog box

Access Rights dialog box


Properties dialog box

Use this dialog box to set key properties of the current document.

Dialog box options

File Name

This field displays the filename of the active document.

Directory

This field displays the location of the file.

Title

This field displays the document title.

Author

This field displays the name of the author. Powersim automatically inserts the name you typed when you installed Powersim. You can use a different name by typing it in the Author box.

Description

You can use this field to enter a description of the model you are running, for example, what problem or phenomenon it describes or what patterns of behavior it depicts.

Statistics

Click on this button to display document statistics, such as the number of variables in the model. Powersim automatically updates the statistics when you open the Statistics dialog box.

Access

Click on this button to set access rights to limit the access to operations on the current document.

Hint	If you are going to use a model as a demo or a game, you may wish to prevent other users from modifying it. Similarly, only the author should be able to alter models in a model library.

The authority to change the access rights may be protected by a password. If a password is present, the Access Password dialog box is opened.


Statistics dialog box (File - Properties)
Statistics dialog box

Use this dialog box to display document statistics, such as the number of variables in the model.

Dialog box options

The following table describes the fields of the dialog box.

Field	Displays
File Name	The file name of the current document.
Directory	The directory in which Powersim stores the active document.
Title	The title of the document entered in the Properties dialog box.
Author	The author of the document entered in the Properties dialog box.
Created	The date and time you created the document.
Last Saved	The last date and time you saved the document.
Last Saved By	The name of the person who last saved the document (the registered user of the Powersim copy that was used to save the document).
Number of Items	The number of entities found in the current document.


Access Password dialog box

Dialog box options

Access Password

Type the password in the text box and hit OK. If you enter the correct password, the Access Rights dialog box is opened.


Access Rights dialog box (File - Properties)
Access Rights dialog box

Dialog box options

Allow For

Use this option to display the access rights for the current document.

Edit

When this box is checked, you may select objects and change a model by adding, changing, or deleting objects. The Edit check box is disabled if the model contains undefined variables or flows.

Save

When this box is checked, you may save a document (using the File Save command). If you try to save a file that has the Save access turned off, the following message will appear: "This file is read only".

Hints

•	You may save a document under another filename using the Save As command, even if the Save option is off.

•	Typically a game will have an access password set by the author, the Edit access set off, and the Save access set on (the game user may save the results of running the game). A library model (for example a generic model) should have the Save access turned off to avoid accidental modifications to the model.

Password

To change the access rights to a document, you must give it a password. You can change the access password for the current document by pressing the Password button. This action will open the Change Access Password dialog box.


Change Access Password dialog box

Dialog box options

Access Password

Type the new password in the text box.

Cancel

Click on this button to close the dialog box and retain the original password .

OK

Click on this button to close the dialog box and open the Confirm Access Password dialog box. If the text box is empty when you press OK, the current password is removed (provided that you confirm the removal in the Confirm Access Password dialog box).


Confirm Access Password dialog box

Dialog box options

Reenter Access Password

Type the new password again in the text box.

Cancel

Click this button to cancel the change of the password.

OK

When you hit OK, Powersim checks that you have typed the password the same way in the Change Access Password dialog box and the Confirm Access Password dialog box. If you have not, a message box appears, saying "The password confirmation does not match", and the Change Access Password dialog box is presented again.


Exit

Use this command to quit Powersim.


Edit menu

Use this menu to edit your document and to search for variables in your model. All commands that change the logic of a simulation model, that is, change the definition of model variables, are found in this menu (except for some of the Simulation Setup dialog box options that may also affect simulation results.)

Overview of Edit menu commands

Undo/Redo - Reverses the most recent action

Cut - Removes the selection and places it on the clipboard

Copy - Copies the selection and places it on the clipboard

Paste - Pastes the clipboard contents into the active diagram if possible

Select All - Selects all visible objects in the active window

Clear - Removes selected objects from the active diagram

Reverse Flow - Reverses the direction of selected flows

Define Object - Defines the selected object

Define Range - Creates or changes array ranges

Define Unit - Creates or changes variable units

Scale - Changes the min and max scaling settings for variables

Rescale Now - Rescales all variables with dynamic scaling

Find - Searches for a variable in the active diagram


Undo/Redo

Use this command to reverse the last editing or formatting action, if possible. The name of the command changes depending on what the last action was. Examples are Undo Create Variable or Undo Move. The Undo command changes to Can't Undo if you cannot reverse your last action. If the last action was an Undo command, the command changes to Redo.

To quickly reverse changes in editing, formatting, and other actions, click Undo [image] on the commandbar.


Cut

Use this command to remove selected text or objects from a document and put them on the clipboard. This command is unavailable if you have no selected objects or text. Cutting text or objects to the clipboard replaces the contents previously stored there.

To quickly remove selected information from the document and place it on the clipboard, click Cut [image] on the commandbar.


Copy

Use this command to copy selected area, objects or text onto the clipboard. This command is unavailable if no objects or area are selected. Copying something to the clipboard replaces the contents previously stored there.

To quickly copy information to the clipboard, click Copy [image] on the commandbar.

Copying an Area

If an area is selected when the Copy command is chosen, an image of this area, and not the current selection, is copied.

See also

Creating Areas

Note	When you copy an area (see OLE Services Provided by Powersim), compound document formats with information for pasting linked and embedded Powersim objects are placed on the clipboard along with a metafile representation of the area.

Hint	To copy an area as a metafile and a bitmap including selection markers (if they exist), hold down the Shift key while choosing Copy. In this case, no compound document formats are placed on the clipboard.

Copying a Selection

Selected objects can be copied to the clipboard in a format that lets you create identical objects by pasting them into a diagram (for example, if you have defined a variable, and want to create another one with the same definition). For a copy operation based on a selection, no compound document formats are placed on the clipboard.

See also

Troubleshooting


Paste

Use this command to insert a copy of the clipboard contents into a document. This command is unavailable if the clipboard contains nothing that can be pasted. Pasted objects are placed in the upper left-hand corner of the window. The paste position is moved a little downward and rightward for each subsequent paste operation.

To quickly insert the Clipboard contents at the insertion point, click Paste [image] on the commandbar.


Select All

Use this command to select all visible objects if the active window is in diagram view, or all visible lines if the active window is in equation view.


Clear

Use this command to remove selected objects.

Note 	If you clear objects accidentally, you can return them to the document by clicking Undo [image] on the toolbar. You must, however, choose Undo before performing any other action.


Reverse Flow

Use this command to change inflows to outflows and vice versa. After the operation, the arrowheads of the selected flows point in the opposite direction, and the flow part of the connected level's mathematical definition is updated so that negative flows become positive and positive flows become negative (+dt*Rate becomes -dt*Rate).

Note 	You must select the flow arrow itself, not the variable that is connected to the flow. Select a flow by clicking with the pointer either in the flow arrow, in the valve symbol, or in the cloud symbol connected to the flow.


Define Object

Use this command to open the definition dialog box that corresponds to the selected object.

Hint	You can also open an object's definition editor by double-clicking on the object or by pressing the Return key when the object is selected.

There are many different object types in Powersim, and they all have their own definition editor. The definition dialog boxes are listed below:

Model objects	Dynamic objects	Static objects	Transfer objects
Define Variabledialogbox_Define_Variable	Define Array GraphDefine_Array_Graph_dialog_box  Define ButtonButton_Object Define GaugeDefine_Gauge_dialog_box  Define Multi Media Define NumberNumber_Object Define Scatter GraphDefine_Scatter_Graph_dialog_box Define Slider/BarDefine_Slider_Bar_dialog_box Define Time GraphDefine_Time_Graph_dialog_box Define Time TableDefine_Time_Table_dialog_box	Define FrameFrame_Object Define LineLine_Object Define PicturePicture_Object Define TextText_Object	Define ArchiveArchive_Object Define ChainChain_Object Define DDEDDE_Object Define Network GameDefine_Network_Game_dialog_box


Define Range

Use this command to define ranges to be used in the definition of arrays.

An example of an array variable defined by means of a range is

level	Population(Area) = InitPop(Area) + dt*NetGrowth(Area)

In this case, Area is a range that can be defined as

range	Area = North, South, East, West

Define Range dialog box

Dialog box options

Range Name

Select the range you want to define. The list contains all ranges known to the current model. The list header shows the current range. When you define and confirm a new range, it will be placed in the Range Name list.

Range Type

Select the type of range you want to use. You can choose among three types:

•	Enumeration

•	Enumeration Subrange

•	Numeric Subrange

Enumeration

An enumeration is an ordered set of text elements, for example North, South, East, West.

Element Name

To define a new element in the current range, type the element name in this text box and hit either the Append button or the Insert button.

Element names used in enumerating ranges must be unique within a simulation model. This means that no element name can be the same as another element, range, function, variable, or unit name.

Append

Click this button to append the current element name to the Elements list.

Insert

Click this button to insert the current element name in the Elements list, before the selected element.

Delete

Click this button to delete the selected element from the Elements list.

Rename

Click this button to open the Rename Range Element dialog box so you can rename a selected element in the Elements list.

Elements

Make a selection in the list of elements to insert, delete, or rename.

Up/Down

Click this button to move the selection in the Elements list up/down.

Enumeration Subrange

An enumeration subrange is a subset of an enumeration. For example

range	Area = North, South, East, West

range	Area2 = North..East

are two range definitions where Area is an enumeration range, and Area2 is a subrange.

Note 	You can use element names of an enumeration range to define the bounds of an enumeration subrange.

Subrange of

Use this field to select the enumeration of which the current range will be an enumeration subrange.

From/To

Use this field to select the lower/upper bounds of the current enumeration subrange.

Numeric Subrange

A numeric subrange is an interval of numbers, for example:

range	Area3 = 1..3

From/To

Type the lower/upper bounds of the current numeric subrange.

OK

Click this button to confirm the current definition and close the dialog box.

Add

Click this button to open the Add Range dialog box so you can add a new range.

Remove

Click this button to remove the current range from the document. If the current range is an enumeration range and subranges of this range exist, a message box appears so you can cancel the operation.

Set

Click this button to confirm the current range definition.

Rename

Click this button to open the Rename Range dialog box so you can rename the current range.

Merge

Click this button to open the Merge Range From File dialog box so you can merge ranges from other documents.


Add Range dialog box

Dialog box options

Name

Type the new range name into the text box and click OK.


Rename Range dialog box

Dialog box options

To

Type the new range name into the text box and click OK.


Rename Range Element dialog box

Dialog box options

To

Type the new element name into the text box and click OK.


Merge Range From File dialog box

Use this dialog box to merge ranges from other model documents.

For dialog box options, see the Open dialog box

Note 	Only well-defined ranges with names that don't conflict with existing names are merged into the current document.


Define Unit

Use this command to define units to be used as part of unit expressions in the Define Variable dialog box.

In the sample model below, Population may be defined with the unit expression "Persons" while Births and Deaths, may both have the unit expression: "Persons/Year". Note that the first expression consists of a single unit name, while the latter consists of two unit names and a mathematical operator.

Before applying a new unit as part of a unit expression in the Define Variable dialog box, you should add it to the list of units in the Define Unit dialog box.

Note	To build consistent models, you should specify a unit of measure for all variables.

Define Unit dialog box

Dialog box options

Unit

Select the unit that you want to define, rename, or delete.

Description

Use this text box to enter a textual documentation of the unit.

Set

Click this button to confirm the current unit definition.

Add

Click this button to open the Add Unit dialog box so you can add a new unit.

Remove

Click this button to remove the current unit from the document.

Rename

Click this button to open the Rename Unit dialog box so you can rename the current range.


Add Unit dialog box

Dialog box options

Name

Type the new unit name into the text box and click OK.


Rename Unit dialog box

Dialog box options

Name

Type the new range name into the text box and click OK.


Scale

Use this command to set scaling options for the variables in your model. You scale a variable by determining what min and max settings are to be used in the graphical presentations of its simulated values. The scaling can be either dynamic or fixed.

Dynamic scaling means that the variable's min/max values are automatically set to the lowest/highest simulated value whenever a simulation run is stopped or paused.

Fixed scaling means that the variable's min or max value is fixed to the value defined in the Scale dialog box. It is not affected by the simulation results.

Scale dialog box

Dialog box options

Models

Select the model for which you want to set the scaling options. The list contains the main model and all connected co-models.

Scaling information is stored in the main model. Changing the scaling settings of a co-model has no effect outside the main model. It will not update the scaling settings of the co-model when the co-model appears as a main model or as a co-model connected to another main model.

Update Dynamic Scale on Pause

If this box is checked, the Edit Rescale Now command is automatically performed whenever a simulation is paused. This option applies to all variables, not only to the selection in the Variables list.

Variables

This field displays the variables and their scaling options. The list contains all variables of the model displayed in the Models list. It has three main columns: Variable, which lists variable names, and Min and Max, which show the variable's current minimum and maximum values.

In addition, the Min and Max columns each have an icon that indicates whether the scaling is dynamic or fixed (see table below).

	Min	Max
Fixed
Dynamic
Multiple Selection

You can assign common scaling settings to several variables by selecting multiple lines in the Variables list. If you make a multiple selection containing different scaling settings, the Dynamic/Fixed radio buttons are deselected and the Min Value and Max Value text boxes become empty if there are different settings among the selected variables. When you enter a value in the Min Value or Max Value text boxes and/or select one of the radio buttons and then hit Set, all the selected variables are assigned the current settings.

All selected variables in a model diagram will be selected in the Variables list when the dialog box is opened.

Min Value, Max Value

These are groups that allow you to enter a new min/max value and choose between dynamic and fixed scaling for the selected variable(s).

Dynamic

All new variables are dynamically scaled by default, with min value = 0 and max value = 1.

Dynamic min/max values are automatically updated whenever a simulation run has terminated. This occurs, for example, when you choose Simulate Stop, when the simulation is stopped by a Control function (such as STOPIF) or a command from an external application (such as the DDE command STOP ), or when the simulation time reaches the stop time, as defined in the Simulation Setup dialog box.

If the Update Dynamic Scale on Pause box is checked, the dynamic scaling is also updated whenever a simulation is paused, i.e., when you choose Simulate Pause or when the simulation is stopped by a Control function (such as the DDE command PAUSE ).

Finally, you may update the dynamic scaling manually by choosing Edit Rescale Now.

When dynamically scaled variables are updated, the min and max values of each variable are set equal to the variable's smallest and largest simulated value during the simulation, and all graphical reports containing rescaled variables are updated.

Fixed

Fixed scaling of a variable's min or max value means that the scaling is fixed to the value in the corresponding text box. It is not affected by the simulation results.

Hint 	It is often useful to fix min values to zero while keeping max values dynamic.

Set To Largest

Pastes the largest max value among the selected variables into the Max Value text box.

Set To Smallest

Click this button to paste the smallest min value among the selected variables into the Min Value text box.

Hint 	The two buttons above come in handy if you want a set of variables to be fixed between the smallest min value and the largest max value.

Set

Click this button to confirm the settings of the current selection.

OK

Click this button to confirm the settings of the current selection and close the dialog box.

Cancel

Click this button to discard the last change and close the dialog box.


Rescale Now

Use this command to rescale all variables that have dynamic scaling, as specified in the Edit Scale dialog box. All auto reports and dynamic objects will then be updated.

Hint	Rescale Now is especially useful when you find yourself in the middle of a simulation run and the variables of your time graph have disappeared outside their current scaling ranges.


Find

Use this command to quickly locate a variable or snapshots of a variable in your model.

Hint	This operation is especially useful when dealing with large models.

Names

Select the variable you want to locate. The focused variable is selected when the dialog box is opened.

Hint	Type a question mark (?) from the keyboard to go straight to the first undefined variable in the list. You can also press a letter key to go to the first item in the list beginning with that letter.

List Categories

Choose between the two different search modes: "All variables" and "Variables with snapshots".

All Variables

In this mode, the Names list contains all the variables in the model. To locate a variable, select it in the Names list and hit Find.

Variables with Snapshots

In this mode, the Names list contains only the variables for which one or more snapshots exist. To locate the snapshots of a variable, select the variable in the Names list and repeatedly hit Find Next.

Hint 	This comes in handy, for example, when you plan to delete a variable but do not remember if snapshots of this variable are used elsewhere in the model. To avoid making the model inconsistent by inadvertently deleting a snapshot, you can inspect a variable's snapshots using the Find dialog box.

Find/Find Next

Use this button to start a search according to the selection in the Names list. If the current category is "All variables", the button is labeled "Find". Clicking the Find button starts a search for the selected variable. When the variable is found, the button will change to "Find Next" if the current variable has snapshots. Clicking the button will then start a search for the next snapshot. When all snapshots are found, the button is disabled.

If the current category is "Variables with snapshots", the button text is "Find Next" from the beginning.

Find in Diagram view

When a variable is found, the diagram is scrolled so that the variable is located inside the diagram window, as near the center as possible. If no simulation is running or pausing and no auto reports are visible in the diagram, the found variable is automatically selected as well.

Find in Equations view

When a variable is found, the list of equations is scrolled to bring the variable, which is automatically selected, inside the window.

After a variable is found, the Find dialog box is still open and is automatically moved downward so it won't cover the selected variable.

Cancel

Click this button to close the dialog box. The selection in the diagram remains unchanged.


View menu

Use this menu to choose Powersim's screen view, customize the editor, choose what object types you want to be shown, and shrink or enlarge the diagram.

Overview of View menu commands

Diagram - Switches to diagram view

Equations - Switches to equations view

Commandbar - Toggles the commandbar on/off

Toolbar - Toggles the toolbar on/off

Statusbar - Toggles the statusbar on/off

Simplified User Interface - Toggles simplified user interface on/off

Show What - Determines what object types appear in diagram view

Pages - Toggles page borders on/off

Rulers - Toggles rulers on/off

Zoom - Enlarges or reduces the contents of the active diagram window


Diagram

Use this command to switch the active window to diagram view from equations view.

See also

Views


Equations

Use this command to switch the active window to equations view from diagram view.

See also

Views


Commandbar

Use this command to display or hide the commandbar. It includes buttons for some of the most common commands in Powersim, including Run, Pause, and Stop. A checkmark appears next to the command name when the commandbar is displayed.


Toolbar

Use this command to display or hide the toolbar. It includes buttons for creating all the different object types in Powersim, such as variables, links, and objects for displaying simulation results. A checkmark appears next to the command name when the toolbar is displayed.


Statusbar

Use this command to display or hide the statusbar. This bar contains various kinds of status information for example, context-sensitive menu help and current simulation time.

The statusbar can appear in two different states:

•	Field Mode

•	Text Line Mode

See also

Displaying Information About a Variable in the Statusbar


Field Mode

Below is an example of the statusbar displayed in field mode.

Statusbar in field mode

The table below lists fixed fields of the statusbar, displayed in field mode.

Field	Displays what
Simulation time	The current value of the Time variable. The variable is also shown as a horizontal bar beneath the text.
Simulation state	The current simulation state. The field has one of three different contents:  1. Empty, if one of the following conditions is true: the model is not runnable, no simulation has been started, or a simulation has reached stop-time. 2. "Simulating" while simulation is running. 3. "Pause" when simulation is being paused.
Zooming	The current zooming magnitude in percentage.
Page number	The page number of the focused diagram object.
Caps Lock on/off	The current caps lock state (CAPS or blank).
Num Lock on/off	The current num lock state (NUM or blank).


Text Line Mode

Below is an example of the statusbar displayed in text line mode.

 Circular connections not allowed. Feedback loops must contain rate to level connections.

Statusbar in text line mode

The text messages given in the statusbar can be divided into the following categories:

•	Forced information, errors, and warnings. Messages force the statusbar to be shown when the conditions that generate the messages occur. This means that the statusbar will be shown and the message displayed even if the statusbar has been switched off.

•	Help information about selected items and/or current actions

•	Menu/button descriptions


Simplified User Interface

Use this command to bring Powersim into or out of simplified mode. When you choose simplified mode, Powersim removes a number of menus, menu commands, commandbar and toolbar buttons, and dialog box controls.

Note	This option lets you adapt Powersim's user interface to your own level of experience. We recommend that all novice users run Powersim in simplified mode.


Show What

Use this command to modify the selection of visible object types in diagram view. It brings up the Diagram View options box, which allows you to switch the visibility of various object types on/off.


Pages

Use this command to display or hide page borders and page numbers in diagram view.


Rulers

Use this command to display or hide rulers in diagram view. The measurement units of the rulers are determined by the setting in the General category of the Options dialog box. The scale of the ruler is determined by the print size setting in File Page Setup.


Zoom

Use this command to choose magnification or reduction for the active diagram window.

You may also use the zoom buttons found in the commandbar:

	Zoom out (reduce)		Zoom to 100%
	Zoom in (enlarge)		Zoom to fit in window
See also

Zoom dialog box

Zooming a window to cover current area only

Troubleshooting


Zoom dialog box

Dialog box options

Zoom (%)

This field has a drop-down list for setting the magnification or reduction of the diagram. The zooming is expressed in terms of percentage of the normal magnification (100%). You may specify any percentage between 6.25 and 400. The upper limit may be reduced in very large diagrams owing to limitations in MS-Windows. If you attempt to select too large a percentage, an error message will appear.

Fit To Window

Click this button to zoom the diagram to fit the current window.


Zooming a window to cover current area only

You may zoom the active window to cover only a selected part of a diagram by first creating an area and then pushing the Zoom in (+) button on the commandbar.

To zoom a window to cover current area only

1	Draw a frame around the desired part of the diagram using the right mouse button.

2	Click Zoom in [image] on the commandbar.


Format menu

Use this menu to move, rearrange, and customize objects, or to open the options panel.

Overview of Format menu commands

Align > - Aligns selected objects vertically or horizontally

Even Spacing > - Evenly spaces a selected group of objects

Same Size > - Gives selected objects the same width or height

Straighten - Straightens selected links

Rotate Name - Moves the names of selected objects counterclockwise

Move Valve - Moves the valve on selected flows if the flow pipes are "bent"

Size - Changes the size of selected variables or tool

Bring to Front - Brings selected objects to the front

Send To Back - Sends selected objects to the back

Bring Forward - Brings selected objects one step closer to the front

Send Backward - Sends selected objects one step toward the back

Options - Changes user options


Align >

Use this command to align selected objects. You can choose to align along either the left/upper, the middle, or the right/bottom line.

When you select Align, a cascaded menu for various alignments appears. The black rectangle symbolizes the anchor object. Among the selected objects, one is focused. That is the anchor object. The alignment is performed relative to the anchor object.


Even Spacing >

Use this command to evenly space a selected group of objects either horizontally or vertically. The spacing is not related to the anchor object, but to the left- and rightmost or the upper- and lowermost objects in the group. You can choose between vertical and horizontal adjustment in the cascaded menu.


Same Size >

Use this command to change the width or height of the selected objects. The objects are resized based on the group's anchor object. You can choose between vertical and horizontal resizing in the cascaded menu.

Note 	This command does not apply to model objects.


Straighten

Use this command to make the selected links straight straight lines, if that is possible.

To quickly straighten the selected links, click Straighten [image] on the commandbar.

Note 	If a link arrow is connected to a flow symbol, the angle between the edge line of the flow valve symbol and the connected variable symbol may prevent the link arrow from being fully straightened.


Rotate Name

Use this command to rotate the text labels of selected variables stepwise, counterclockwise around their respective variable symbols.

To quickly rotate the names of selected variables, click Rotate Name [image] on the commandbar.


Move Valve

Use this command to move the valve symbol on selected flows stepwise, from one part of a bent pipe to another.

To quickly move the valves of selected flows, click Move Valve [image] on the commandbar.


Size

Use this command to change the individual size of the selected variables or the default size of the current model object tool.

See also

Size dialog box

Changing Individual Size of Selected Variables

Changing Default Variable Object Size


Size dialog box

Size (%)

Choose the size you want to enlarge/shrink the selected variables to. You can choose between 75%, 100%, 150%, and 200%.


Changing Individual Size of Selected Variables

Sizing variables individually is useful in many contexts, for example, to emphasize important variables in your model.

To change the individual size of selected variables

1	Select one or more variables in the diagram.

2	Open the Size dialog box by choosing Size from the Format menu.

3	Choose a size from the Size combo box and click OK.


Changing Default Variable Object Size

Each variable object type (level, auxiliary, constant) has its own default size, which is the size that is given to new instances of the object.

To change the default size of a variable object type

1	Select the tool for creating the object type for which you want to change the default size. You do this by clicking on a button in the toolbar or by choosing an entry in the Tools menu.

2	Open the Size dialog box and choose the desired default size. Each new instance of this object type will now be the chosen size.


Bring to Front

Use this command to bring the selected objects to the front of all other objects.

To bring selected objects to the front

1	Select one or more objects to bring to the front.

2	From the Format menu, choose Bring to Front.

See also

Object Stacking Order


Send to Back

Use this command to send the selected objects behind all other objects.

To send selected objects to the back

1	Select one or more objects to send to the back.

2	From the Format menu, choose Send to Back.

See also

Object Stacking Order


Bring Forward

Use this command to bring the selected objects one step closer to the front.

To bring selected objects forward in the stacking order

1	Select one or more objects to bring forward.

2	From the Format menu, choose Bring Forward.

See also

Object Stacking Order


Send Backward

Use this command to send the selected objects one step toward the back.

To send selected objects backward in the stacking order

1	Select one or more objects to send backward.

2	From the Format menu, choose Send Backward.

See also

Object Stacking Order


Object Stacking Order

Each object you create can be stacked on top of other objects so that they overlap. You can change the stacking order by bringing objects forward or backward. If you change the stacking order of several objects at once, the original order of the objects is preserved.

Note 	The "object stacking" commands do not apply to model objects, which are always in front of dynamic, static, and transfer objects.


Options

Use this command to change various categories of Powersim options. The command brings up the Options dialog box.

To quickly open the Format Options dialog box, click Options [image] on the commandbar.


Simulate menu

Use this menu to start, stop, or pause a simulation, and to inspect/specify run and simulation parameters, including time step and integration method.

Overview of Simulate menu commands

Run - Starts a simulation

Run Step - Runs a simulation one step or initializes a new simulation run

Pause - Toggles pause on/off

Stop - Stops a simulation

Clear Results - Clears stored simulation results

Run Setup - Defines run parameters

Simulation Setup - Defines simulation parameters (start, stop, time step, etc.)


Run

Use this command to start a new simulation run. The menu entry is disabled while a simulation is running.

To quickly start a simulation, click Run [image] on the commandbar.


Run Step

Use this command to simulate one time step forward from the current (paused) state and then pauses the simulation (again). If a simulation run was not started or initialized when you chose Run Step, a new simulation run is initialized and put in pause mode. In this case, choosing Run Step will not advance the simulation and is therefore equivalent to choosing Pause and Run in sequence. Run Step runs the simulation stepwise independently of the settings in Simulate Run Setup.

To quickly run a simulation one step or initialize a new simulation run, click Run Step [image] on the commandbar.


Pause

Use this command to switch pause mode on or off. When pause is on, a checkmark is displayed on the menu and the pause button on the commandbar is depressed.

To quickly pause or resume a simulation, click Pause [image] on the commandbar.


Stop

The Stop command stops a running simulation.

To quickly stop a simulation, click Stop [image] on the commandbar.


Clear Results

Use this command to clear all simulation results in the current document. This action will restore the contents of all dynamic objects, which will appear as if no simulation had taken place.

Note	Clear Results will also make any auto reports disappear from your diagram.


Run Setup

Use this command to define automatic pause settings, the number of sequential runs, and a possible imposed delay time for each simulation step.

Run Setup dialog box

Dialog box options

Auto Pause

Use this group of radio buttons to specify criteria for automatic pauses in the simulation run. When the conditions for an auto pause are fulfilled, Powersim will automatically switch pause on. The Pause button on the commandbar will then be set to a pushed state and the Pause entry on the Simulate menu will be checked. When you switch pause off, the simulation will run for another auto pause interval. In this way, you may run a simulation in desired "time portions" until the stop time is reached.

Hint	The auto pause feature allows you to adjust model parameters or inspect temporary simulation results in the middle of a simulation run.

Never

If you click this button, the simulation will run continuously from start time to stop time, as specified in the Simulation Setup dialog box.

Every <n> Time Units

If you click this button, the simulation will run for the given number of time units and then pause. (One Time Unit equals 1/TIMESTEP steps.)

Every <n> Time Steps

If you click this button, the simulation will run for the given number of time steps and then pause. (If the specified auto pause time exceeds the stop time, the auto pause will never occur.)

Runs

Type or select the desired number of sequential simulation runs to be carried out. The default value is 1.

If you wish to run several simulation runs in sequence, for example, for performing sensitivity analyses, you may specify a number greater than 1 in this text box. Then you can use the run number, returned by the built-in function RUN, to define parameters that change between each new run.

Delay (ms / time step)

Type or select the number of milliseconds (ms) that you want the simulation to be delayed between each time step. The default value is 0 or maximum simulation speed.

Hint	The ability to reduce the speed of a simulation by imposing delays between time steps can be useful in several situations. For example, if you have small models that normally run very fast, you may want to slow them down so that you can follow the development of their simulations as they proceed. This feature also gives you the opportunity to adapt simulations to real-time conditions.


Simulation Setup

Use this command to specify simulation times, integration method, and time step, and to set up co-models for parallel simulations.

See also

Simulation Setup dialog box

Rename Co-model dialog box

Adjusting Calculation Time of RK4 Variable Step Size


Simulation Setup dialog box

Dialog box options

Model(s)

This field displays the models to which the current settings apply.

Times

Use this group to set time attributes for the current model.

Start Time, Stop Time

Type or select start and stop times for the simulation.

Time Unit

Choose a time unit for the main model.

New time units can be defined in the Define Unit dialog box. To delete or rename an existing time unit, open the Define Unit dialog box, select the desired unit in the Unit list, and push the Delete or the Rename button.

Each model stores its own set of time units together with other units of measure.

Note 	If you use co-models, you can specify a time unit only for the main model. To change the time unit of a co-model, you have to open the co-model document using File Open and change the unit from there. If you select a co-model in the Parallel Simulation list, the Time Unit list is disabled but displays the current time unit of the co-model. If the selection covers models with different time unit definitions, the Time Unit list is empty.

Integration

Use this group to specify integration method, time step, and, if a variable step size method is chosen, error limits.

Method

You can choose an integration method. Available methods are

•	Euler fixed step

•	Runge-Kutta 2. order fixed step

•	Runge-Kutta 3. order fixed step

•	Runge-Kutta 4. order fixed step

•	Runge-Kutta 4. order variable step

See also:

Choosing Integration Method

Time Step

Type or select a time step for the current model.

See also:

Choosing Time Step

AbsError, RelError

Type the absolute and relative integration error limits. These text boxes are disabled unless the current integration method has a variable step size.

For more information about how these parameters influence a simulation, please refer to Simulation.

Set

Click this button to confirm the current settings.

Co-models >>

Click this button to expand or compress the dialog box. When expanded, the dialog box includes the Parallel Simulation group for specifying co-models.

Parallel Simulation

Use this group to set up co-models for parallel simulation. See also Simulation .

The list displays the main model and the co-models to be simulated in parallel. It contains the following columns:

Model

This field displays the name of the connected model.

Time Step

This field displays the time step of the connected model.

Start Time, Stop Time

These fields display the start and stop time of the connected model.

Note 	Co-models are simulated using their local time step, start, and stop settings, which may differ from those of the main model. If there are differences, Powersim will automatically synchronize the simulation so that the co-models still run in parallel with the main model. You will find more about this in Simulation.

Add

Click this button to add a new co-model to the list. It brings up the Add dialog box, which is identical to the Open dialog box. Type or select the desired Powersim document and hit OK to add it to the list.

Remove

Click this button to remove selected entries from the list of co-models.

Rename

Click this button to change the name to be used as a reference to the selected co-model. This name is set to the file name as a default. Pushing the Rename button brings up the Rename Co-model dialog box.

Open

Click this button to open selected co-models in special co-model windows. The text in the caption of these windows indicates that they contain co-models. The main model name and the co-model name, divided by a period, are displayed within brackets (<...>).


Rename Co-model
Rename Co-model dialog box

Dialog box options

From

This field displays the current name of the co-model.

To

Type the new co-model name in the text box and hit OK. The maximum length of the name is 31 characters.


Adjusting Calculation Time of RK4 Variable Step Size

The RK4 integration method with variable step size subdivides the time step that you provide to achieve a predetermined accuracy. The maximum number of internal calculation steps is determined by the VariableStepLimit entry of the SimulationEngine section of POWERSIM.INI. Reducing VariableStepLimit reduces calculation time. However, you should keep it within the interval 1 to 6 (inclusive).

Example:

[SimulationEngine]

VariableStepLimit=3


Color menu

Use this menu to change the color of selected model objects or the background of the active diagram.

Note 	You can use the Color menu only to color model objects and the diagram background. To change colors of dynamic, static, and transfer objects, open the objects' Define dialog box and edit the color from there.

Changing Object Color

To change the color of one or more model objects

1	Select the model objects.

2	Open the Color menu.

3	Select the desired color.

Default Object Type Color

Each model object type has its own default color, which is the color that is given to new instances of the object type. A checkmark in the Color menu indicates the default color of the object type of the selected tool.

For example, if you have selected the level tool, a checkmark on the Color menu indicates the default color of levels. If you create a new level object, this object will get the color that was checked in the menu.

See also

Changing Default Object Type Color

Changing Background Color


Changing Default Object Type Color

To change the default color of an object type

1	Select the tool for creating the object type for which you want to change the default color by clicking on a button in the toolbar or by choosing an entry in the Tools menu.

2	Open the Color menu and choose the desired default color.

The chosen color now becomes the default color of the object type, meaning that all new objects of the particular type get this color. When no objects are selected, a checkmark on the Color menu indicates the default color of the diagram background.


Changing Background Color

To change the background color of the active diagram

1	Make sure no objects are selected.

2	Open the Color menu and choose the desired background color.

Changing the background color of a diagram window does not alter the default background color, which is always white.


Tools menu

Use this menu to select tools for creating new objects or editing the diagram.

When you make a selection in the Tools menu or click a corresponding button in the toolbar, the cursor will change to a symbol for the selected tool when you move the mouse pointer to the diagram window. The new cursor indicates that clicking the left mouse button somewhere in the diagram will create a new instance of the entity associated with the tool.

Temporary or Permanent Tool

If you select a tool by pressing the left mouse button in the toolbar, the cursor changes back to the pointer tool after the new object is created. If you select a tool by pressing the right mouse button, or by pressing the left mouse button while pressing Ctrl on the keyboard, the cursor remains unchanged after the new object is created. In this way you may create several objects of the same type without having to re-select the tool again and again. Click in the diagram with the right mouse button to select back the pointer tool.

Tool Groups

The tools found in the Tools menu can be grouped as follows:

Tools for creating model components

Tools for editing the model

Tools for creating transfer objects

Tools for creating static objects

Tools for creating dynamic objects


Tools for creating model components

Level tool - Creates a new level variable

Auxiliary tool - Selects the tool for creating a new auxiliary variable

Constant tool - Creates a new constant

Flow tool - Creates a new flow

Flow-with-rate tool - Creates a new flow-with-rate

Link tool - Creates a new link

Delayed Link tool - Creates a new delayed link

See also

Creating a new model component


Level tool

Click in the diagram with this tool to create a new level variable.

To quickly select the level tool, click Level [image] on the toolbar.

For more information about level objects see

Model Objects


Auxiliary tool

Click in the diagram with this tool to create a new auxiliary variable.

To quickly select the auxiliary tool, click Auxiliary [image] on the toolbar.

For more information about auxiliary objects see

Model Objects


Constant tool

Clicking in the diagram with this tool creates a new constant.

To quickly select the constant tool, click Constant [image] on the toolbar.

For more information about constant objects see

Model Objects


Flow tool

Drag-and-drop into or out of a level with this tool to create a new flow.

To quickly select the flow tool, click Flow [image] on the toolbar.

Note	When a flow doesn't run into or out of a level, it ends or starts in a cloud. A flow can run from a level to a cloud, from a cloud to another cloud, or from a cloud to a level.

Note	When you drag a flow arrow, you will notice that the arrow is always a straight line. But sometimes "bends", or corners, are required to establish the necessary flow connections. A flow arrow can have a maximum of four corners.

See also

Creating a new flow

Creating a corner of a flow arrow

Deleting a corner on a flow arrow

Working with Flows


Flow-with-rate tool

A flow-with-rate consists of a flow with an auxiliary linked to it. Drag-and-drop into or out of a level with this tool to create a new flow-with-rate.

To quickly select the flow-with-rate tool, click Flow-with-rate [image] on the toolbar.

See also

Creating a new flow


Link tool

Drag-and-drop from one variable to another using this tool creates a new link. Use a link to establish an influence from one variable to another. A link that goes into a level is interpreted as an initialization link, meaning that it creates an influence used to initialize the level.

To quickly select the link tool, click Link [image] on the toolbar.

Note	The link arrow has Bézier curve properties. To make a link a straight line, choose Format Straighten with the link selected.

See also

Establishing a Link

Circular Link Connections

Divided Links


Circular Link Connections

A common logical error when building models is to create circular connections between variables. Such connections are illegal, since there is no logical way to solve an equation in which a variable is defined in terms of itself.

The only exception to this rule is the case in which a flow-to-level connection is part of a loop, as in the figure below. In this case, it is a question not of circularity but of feedback, which appears in most dynamic simulation models.

Note 	You can introduce flow-to-level connections by some of Powersim's standard functions, for example DELAYINF, DELAYMTR, and DELAYPPL. Those functions generate internal, "invisible" flow-to-level connections that allow you to create loops without explicitly creating flow-to-level connections. However, those functions require you to use the delayed link tool (described below) instead of the link tool.

If you attempt to create a circular connection, a warning message will appear in the statusbar.

To see the path of connections that would create circularity, release the mouse button while the cursor is inside the variable that triggered the circularity warning. This action brings up a message box specifying the attempted circular loop.


Delayed Link tool

A delayed link indicates that the influence represented by the link is delayed, meaning that it comprises a flow through one or more levels. Those levels are not present as objects in the diagram but are defined implicitly by functions that are used to define the variable at the head of the delayed link.

You create and edit a delayed link in the same manner as an ordinary link. To quickly select the delayed link tool, click Delayed Link [image] on the toolbar.

Note	You must use a delayed link if the link is going to be an input parameter to a delay function.

The presence of delayed links in a diagram informs you that the variables to which the delayed links provide input are defined by means of a delay function (Auxiliary_2 in the figure to below).

Hint	Delayed links enable you to build feedback loops without explicit flow-to-level connections in the diagram.


Model editing tools
Tools for editing the model

Pointer tool - Selects the pointer for making selections, moving objects etc.

Eraser tool - Selects the tool for deleting an object

Camera tool - Selects the tool for taking a snapshot of a variable


Pointer tool

Use this command to select the pointer tool.

To quickly select the pointer tool, click Pointer [image] on the toolbar.

The pointer is used for performing a series of tasks, including

Selecting and deselecting objects

Creating areas

Opening the definition editor

Moving objects

Adjusting objects

Adjusting parameters

Adding variables to dynamic or transfer objects using drag-and-drop

Displaying information about a variable in the statusbar

See also

Summing up Pointer Functionality

Pointer Cursors

Troubleshooting


Summing up Pointer Functionality

Action	Result editing mode	Result simulating mode
Click on object, left button	Select object. Auto reports disappear	Depends on object type
Click on object, right button	Display variable definition in statusbar	Display variable value in statusbar
Click outside object, left button	Deselect object. Auto reports disappear	None
Shift + Click on object	Toggle selection	Depends on object type
Drag left button	Select several objects	None
Shift + Drag left button	Extend selection	None
Drag right button	Create area	Create area
Drag selection, then release button	Move objects	None
Drag selection into dynamic object, release button	Add variables to dynamic object's parameter list	None
Drag selection into dynamic object, release button while pressing Shift or Ctrl	Replace contents of dynamic object's parameter list with selected variables	None
Drag handle of link, line, or flow	Adjust angle or extent	None
Drag column of time table	Adjust column	None
Drag button of slider/bar	None	Adjust associated parameter


Pointer Cursors

The pointer tool is represented by different cursors, depending on the position of the mouse pointer and the current mode of activity:

When the mouse pointer is not pointing to any object, the cursor is a standard pointer arrow.

When the mouse pointer is pointing to an object, the cursor becomes a pointing hand, which indicates that you are in a position to select, deselect, or move the object you are pointing at.

When you are moving a selection of objects on the diagram surface, the cursor becomes a flat hand, which indicates that the selection will be moved to the new position once the button is released.

When you are moving a set of selected variable objects into a dynamic object, the cursor becomes a dropping hand, which indicates that the selected variables will be added to the dynamic object's list of parameters.

When the mouse pointer is pointing to one of the handles of a link, flow, or line object, the cursor becomes a small arrow, which indicates that you are adjusting the object.

When the mouse pointer is pointing to one of the border handles of a dynamic, transfer, or static object (except for the line object), the cursor becomes a two-way arrow, which indicates that you are adjusting the extent of the object either vertically, horizontally, or diagonally.

When the mouse pointer is pointing to one of the column borders of a time table object, the cursor becomes a two-way arrow with a vertical line in the middle, which indicates that you are adjusting the column width.


Eraser tool

Use this tool to delete an object.

To delete an object using the eraser tool

1	Select the eraser tool.

2	Position the center of the eraser tool over the desired object.

3	Click the left mouse button.

To quickly select the eraser tool, click Eraser [image] on the toolbar.

Note 	If you delete an object accidentally, you can return it to the document with the Undo command on the Edit menu or the Undo button on the toolbar. You must, however, choose Undo before performing any other action.


Camera tool

Use this tool to make a snapshot of a variable. This feature helps avoid "spaghetti models" with many link arrows crossing other symbols, which obscure the model's structure.

To quickly select the camera tool, click Camera [image] on the toolbar.

To create a snapshot

1	Select the Camera tool. The cursor then changes to a camera symbol.

2	Click the left mouse button at the position in the diagram where you want to put the snapshot. This action brings up the Create Snapshot dialog box.

3	Select the variable you want to copy from the Create Snapshot dialog box and click OK.

See also

Create Snapshot dialog box


Create Snapshot dialog box

Dialog box options

Variables

Choose the variable of which you want to create a snapshot. The variable that was focused when you selected the camera tool will be selected by default in the Variables list when the Create Snapshot dialog box opens. To create a snapshot of this variable, simply click OK.

OK

Click this button to create a snapshot of the selected variable. The snapshot will be positioned at the spot where you clicked with the camera cursor.


Tools for creating transfer objects

Chain tool - Selects the tool for creating a new chain object

DDE tool - Selects the tool for creating a new DDE object

Archive tool - Selects the tool for creating a new archive object

Network Game tool - Selects the tool for creating a new network game object


Chain tool

A chain is used to connect models by transferring the values of a source variable in one model to a constant target variable in another model.

To quickly select the chain tool, click Chain [image] on the toolbar.

See also

Creating a new chain object

Chain object

Co-models


DDE tool

DDE objects facilitate flexible and powerful transfer of data between applications.

To quickly select the DDE tool, click DDE [image] on the toolbar.

See also

Creating a new DDE object

DDE object


Archive tool

Archive objects facilitate transfer of parameter values and time series to or from external files.

To quickly select the archive tool, click Archive [image] on the toolbar.

See also

Creating a new archive object

Archive object


Network Game tool

The network game object allows you to create multiuser simulation games that may be run in a network environment.

To quickly select the Network Game tool, click Network Game [image] on the toolbar.

See also

Creating a new network game object

Network game object


Tools for creating static objects

Text tool - Selects the tool for creating a text object

Frame tool - Selects the tool for creating a frame object

Picture tool - Selects the tool for creating a picture object

Line tool - Selects the tool for creating a line object


Text tool

You can use text objects to add textual comments to your diagram, for example, to label different model sectors.

To quickly select the text tool, click Text [image] on the toolbar.

See also

Creating a new text object

Text object


Frame tool

You can use frame objects to add visual frames to your diagram, for example, to divide your model into logical sectors.

To quickly select the frame tool, click Frame [image] on the toolbar.

See also

Creating a new frame object

Frame object


Picture tool

You can use picture objects to add bitmaps to your diagram, for example, to symbolize various aspects of your model.

To quickly select the picture tool, click Picture [image] on the toolbar.

See also

Creating a new picture object

Picture object


Line tool

You can use line objects to add different kinds of lines to your diagram, for example, to draw causal loop diagrams.

To quickly select the line tool, click Line [image] on the toolbar.

See also

Creating a new line object

Line object


Tools for creating dynamic objects

Number tool - Selects the tool for creating a number object

Slider/Bar tool - Selects the tool for creating a slider/bar object

Time Table tool - Selects the tool for creating a time table object

Time Graph tool - Selects the tool for creating a time graph object

Scatter Graph tool - Selects the tool for creating a scatter graph object

Button tool - Selects the tool for creating a button object

Gauge tool - Selects the tool for creating a gauge object

Array Graph tool - Selects the tool for creating an array graph object

Multimedia tool - Selects the tool for creating a multimedia object

Command Button - Selects the tool for creating a command button


Number tool

You can use numbers to display the simulation results of selected variables or to give input to your model via selected parameters.

To quickly select the number tool, click Number [image] on the toolbar.

See also

Creating a new number object

Number object


Slider/Bar tool

You can use slider/bars to display the simulation results of selected variables or to give input to a model via selected parameters.

To quickly select the slider/bar tool, click Slider/Bar [image] on the toolbar.

See also

Creating a new slider/bar object

Slider/bar object


Time Table tool

You can use time tables to display the simulation results of selected variables.

To quickly select the time table tool, click Time Table [image] on the toolbar.

See also

Creating a new time table object

Time table object


Time Graph tool

You can use time graphs to display the simulation results of selected variables.

To quickly select the time graph tool, click Time Graph [image] on the toolbar.

See also

Creating a new time graph object

Time graph object


Scatter Graph tool

You can use scatter graphs to display the simulation results of selected variables by plotting one variable against another.

To quickly select the scatter graph tool, click scatter graph [image] on the toolbar.

See also

Creating a new scatter graph object

Scatter graph object


Button tool

You can use buttons (pushbuttons, checkmarks, or radio buttons) to set variable values, including values of control variables, such as Play and Pause.

To quickly select the button tool, click Button [image] on the toolbar.

See also

Creating a new button object

Button object


Gauge tool

You can use gauges to animate model variables as moving bars or needles.

To quickly select the gauge tool, click Gauge [image] on the toolbar.

See also

Creating a new gauge object

Gauge object


Array Graph tool

You can use array graphs to display an array of values as line graphs or as series of bars.

To quickly select the array graph tool, click Array Graph [image] on the toolbar.

See also

Creating a new array graph object

Array graph object


Multimedia tool

You can use multimedia objects to present video, animation, sound, text, pictures, or message boxes based on the state of a simulation.

To quickly select the multimedia tool, click Multimedia [image] on the toolbar.

See also

Creating a new multimedia object

Multimedia object


Command button tool

You can use command buttons to control your simulation. By using the available DDE commands, you can open, close, and switch between windows, start and stop simulations, and perform different document actions, like saving and loading.

To quickly select the command button tool, click Command Button [image] on the toolbar.

See also

Creating a new command button object

Command button


Window menu

Use this menu to rearrange windows or activate specified windows.

Overview of Window menu commands

New Window - Opens an additional window for the active document

Cascade - Arranges windows in an overlapping pattern

Tile - Arranges windows side by side so that all windows are visible

Arrange Icons - Arranges all icons in rows

Close All - Closes all Powersim windows

<list of windows> - Brings up the selected window


New Window

Use this command to open an additional window with the same contents as the active window. You can then display different parts or views of a document at the same time. If you change the contents in one window, all other windows containing the same document reflect those changes. When you open a new window, it becomes the active window and is displayed on top of all other open windows.


Cascade

Use this command to arrange windows in an overlapping pattern so that the title bar of each window remains visible. Windows without scroll bars are not resized by Cascade or Tile.


Tile

Use this command to arrange windows side by side so that all windows are visible.


Arrange Icons

Use this command to arrange all iconized windows in rows.


Close All

Use this command to close all Powersim windows. This action will close all open documents.


<list of windows>

The names of all available windows and window icons are listed at the bottom of the Window menu. To bring up a window, choose its name from this list.


Help menu

Use this menu to get help on using Powersim.

Overview of Help menu commands

Contents - Displays the opening screen of Help

Getting Started - Displays the Getting Started screen of Help

Current Document:  command - Opens the Help file associated with the current document

About Powersim - Displays version number, copyright notice, and license information

See also

Context Sensitive Help


Contents

Use this command to display the opening screen of Help. From the opening screen, you can jump to step-by-step instructions for using Powersim and various types of reference information.

Once you open Help, you can click the first button on the left in the Help window, labeled Contents, whenever you want to return to the opening screen.


Getting Started

Use this command to open Help. This action will display the first screen of the Quick Tours in Powersim tutorial, which gives you step-by-step descriptions of how to run and build a simulator in Powersim.


Current Document:  command

Use this command to open a Windows Help file with the same file name as the current document. For example, if the current document is WORLD5.SIM, you may open WORLD5.HLP (if present) by choosing this command. If no help file with the same name as the current document is present on the current document's directory, this menu entry is disabled.

This feature enables you to supply each document with its own help file. Such help files will typically contain model descriptions, guidelines for running a simulator, etc.


About Powersim

Use this command to display the version number of your copy of Powersim, the copyright notice, and information about the user license.


Options

This topic provides a detailed description of all user options found in the Options dialog box of Powersim.

Overview of option categories

Auto Reports - Choice of automatic value reports for variables in diagram view

Diagram Editing - Various options for the diagram editor (grid options)

Diagram View - Selection of object types to be shown in diagram view

Equations View - How to display the equations in equation view

General - Various general options, including measurement unit and numerical format settings

Save - Save options, including whether or not to create a backup copy each time you save a document

Window Attributes - Attributes for the active window, for example, sizing frame, scrollbars, and icon to be used in minimized mode

See also

Opening the Options dialog box


Opening the Options dialog box

To open the Options dialog box

•	Click Options [image] on the commandbar

or

•	Select Format Options from the menus


Auto Reports options

Use this option category to choose which report methods to apply to automatically display simulation results for the various variable types in diagram view.

See also

Auto Reports dialog box

What are Auto Reports?


Auto Reports dialog box

Dialog box options

Auto Reports

This group contains check boxes for switching auto reports on/off.

Disable

Check this box if you want to disable auto reports and thereby increase simulation speed.

Animation

Check the Animation boxes to indicate the variable types for which you want animated simulation results displayed.

Numbers

Check the Number boxes for the variable types for which you want numerical simulation results displayed.

Graph

Check the Graph box if you want time graphs to be displayed inside the level symbols during simulation.

Apply To

Use this list to determine the scope of your settings. You can choose among the following:

•	Window

•	Document

•	All Open Docs

If you choose Window, the settings will affect only the current window. If you choose Document, the settings will affect all diagram windows of the current document. If you choose All Open Docs, the settings will affect all diagram windows of all open Powersim documents.

Use As Default

Click this button to make all new Powersim windows use the current setting as the default. The settings are stored in the configuration file POWERSIM.INI.


What are Auto Reports?

Auto reports are presentations of simulation results automatically displayed within or next to variable symbols in a diagram. Powersim offers three auto report methods:

•	Animation

•	Number

•	Graph

Animation and number apply to all three variable types (level, auxiliary, and constant), while graph applies only to available levels.

Animation

Levels are animated as vertical, hollow (non-filled) bars. (Compared to the filled bar animation, the non-filled bar variant of Powersim animation significantly increases the simulation speed.) The extent of the bar is determined by the variable's simulated value relative to its min and max values.

Auxiliaries and constants are animated as gauges, i.e., as needles with their center at the bottom of the variable symbol. A needle in the leftmost position signifies that the variable's value is less than or equal to its minimum value. A needle in the rightmost position signifies that the variables value is greater than or equal to its maximum value. Minimum and maximum values are specified from the Scale dialog box, opened from the Edit menu.

Number

The variable's value is presented as a number, just outside the variable symbol, at the side opposite the variable name.

Graph

The graph is drawn as a simple line graph inside the level rectangle. The line color follows the symbol color.

You may define the use of auto reports in the Auto Reports category of the Options panel. The various reports can be used simultaneously. The auto reports will, if switched on, appear in the diagram symbols as soon as a simulation run is started. They will not disappear until the simulation is stopped and you make a selection in the diagram. Clicking in the diagram background area also makes the auto reports disappear if the simulation is stopped.

A diagram containing auto reports can be copied as a picture by creating an area.

The auto reports are zoomed/resized together with the diagram and the various symbols. The color used to draw the auto reports is the same as the color of the symbol.

Note 	Array variables show auto reports for their first element only.


Diagram Editing options

Use this category to set diagram editing options (grid options).

See also

Diagram Editing dialog box


Diagram Editing dialog box

Dialog box options

Grid

Use the controls in this group to set grid options.

Snap to Grid

Use this check box to switch the grid on/off.

The Snap to Grid option allows objects to be attracted to an invisible grid for precise drawing and alignment. Choosing Snap to Grid does not affect the position of existing objects unless you move them. You wont see the grid when it is on, but any objects that you create, move, or resize will snap to the nearest grid position as determined by the Horizontal and Vertical settings.

Angle

Type or select the size of the angle grid you want to use. The angle applies to link arrows in relation to connected variables. If the grid is on, the angle grid setting determines how many degrees the editor will allow between each possible angle.

Horizontal, Vertical

Type or select the size of the horizontal or vertical grid you want to use.

Grid Unit

Choose the grid unit you want to use.

Use As Default

Click this button to make all new Powersim windows use the current setting as the default. The settings are stored in the configuration file POWERSIM.INI.


Diagram View options

Use this category to determine the visibility of various object types when Powersim is in diagram view.

See also

Diagram View dialog box

Function Indicator Table


Diagram View dialog box

Dialog box options

Model Objects

Use this group to set visibility options for model objects. If None is checked, no model objects will be visible. If All is checked, all model objects will be visible.

Levels, Auxiliaries, Constants, Flows, Links, Init Links

Choose whether or not to display the corresponding object type.

Snapshots

Choose whether or not to display variable snapshots.

Rates

Choose whether or not to display rates. Variables of any type can control flows in Powersim. This means that rate variables might include both auxiliaries, levels, constants, and snapshots of any of these. If Rates is not checked, hiding a particular variable type will also hide all rates of that type. For example, if you wish to view only the flows and levels of a model, keep the Rates box checked and clear Auxiliaries and Constants.

Question Mark (?) in Undefined Var's

Choose whether or not you want a question mark to be displayed in the symbols for undefined variables.

Function Indicators

Choose whether or not you want a function indicator symbol to be displayed in the symbols of auxiliaries that use certain functions in their definitions.

Dynamic Objects

Use this group to set visibility options for dynamic objects.

None

If this box is checked, no dynamic objects will be visible.

All

If this box is checked, all dynamic objects will be visible.

Time Graphs, Time Tables, Numbers, Slider/Bars, etc.

Choose whether or not to display the corresponding object type.

Static Objects

Use this group to set visibility options for static objects.

None

If this box is checked, no static objects will be visible.

All

If this box is checked, all static objects will be visible.

Frames, Texts, Pictures, Lines, etc.

Choose whether or not to display the corresponding object type.

Transfer Objects

Use this group to set visibility options for transfer objects.

None

If this box is checked, no transfer objects will be visible.

All

If this box is checked, all transfer objects will be visible.

Chain, etc.

Choose whether or not to display the corresponding object type.

Apply To

Use this list to determine the scope of your settings. You can choose among the following:

•	Window

•	Document

•	All Open Docs

If you choose Window, the settings will affect only the current window. If you choose Document, the settings will affect all diagram windows of the current document. If you choose All Open Docs, the settings will affect all diagram windows of all open Powersim documents.

Use As Default

Hit this button to make all new Powersim windows use the current setting as the default. The settings are stored in the configuration file POWERSIM.INI.

Note	Object types that are switched off will automatically be switched on in the current window once a new instance of the object type is created. Say that Model Objects Constants is switched off. You create a constant object in the diagram. The visibility of constants will then be switched on again. Init links will automatically be switched on once you create an init link, that is, connect a link arrow to a level symbol.


Function Indicator Table

Symbol	Category	Functions
	Control functions Functions that control simulation runs	PAUSEIF,  PAUSEWHILE, STOPIF, STOPRUNIF
	Side effect functions Functions with side effects	ASSIGN, LIMIT, SHIFTCIF, SHIFTLIF, SOUND
	Level functions Functions that use internally generated levels	DELAYINF, DELAYMTR, DELAYPPL, DERIVN, FORECAST, HIVAL, INIT, INTEGRATE, LOVAL, NPV, SAMPLE, SAMPLEIF, TREND
	Time functions Functions that use the TIME variable or real time (system clock)	ATSTART, COSWAVE, PULSE, PULSEIF, RAMP, SECONDSTHISRUN , SECONDSTHISSTEP , SINWAVE, STEP, TIME, TIMECYCLE, TIMEIS
	Graph functions Table lookup functions	GRAPH, GRAPHCURVE, GRAPHLINAS, GRAPHSTEP
	Stochastic functions Functions that use randomly generated numbers	EXPRND, NORMAL, POISSON, RANDOM
Note 	Function groups and function indicator categories are two different classifications. The Define Variable dialog box contains a list box for selecting among function groups. Functions from several function groups can be members of the same function indicator category.

Note	If a variable uses functions from more than one function indicator category, the symbol shows the function indicator with the highest prioritycontrol functions first, then side effect functions, level functions, time functions, graph functions, and stochastic functions.


Equations View options

Use this category to customize the equation view of the current window. The setting of this category determines what is displayed on your screen when Equations View is checked in the View menu and what is printed if you have included Equations in the Print What list in the Print dialog box.

See also

Equations View dialog box


Equations View dialog box

Dialog box options

Show Variables with

Use this group to indicate what parts of a variable's definition you want to display in the equations view.

Definition

Check this box if you want to display the definition of each variable in your model.

Array Dimensions

Check this box if you want to display the dimension specification of each array variable in your model.

Documentation

Check this box if you want to display the documentation of each variable in your model. The documentation of a variable is the contents of the Documentation text box in the Define Variable dialog box.

Unit of Measure

Check this box if you want to display the unit of measure expression for each variable in your model.

Separate definition switched off

Separate definition switched on

Separate

Use this group to choose whether or not to display separate variable definitions and array dimensions.

Definition

Check this box if you want separate definitions (see figures above).

Array Dimensions

Check this box if you want to display the array dimensions in separate lines.

Show Levels with

Use this group to change the display of level variables.

Init Equation

Check this box if you want the init equations of the levels to be displayed.

Flow Equation

Check this box if you want the flow equations of the levels to be displayed.

Show Simulation Specs

Check this box if you want the simulation specifications (start time, stop time, time step, integration method, and absolute and relative error limits) to be displayed in equations view.

Show Ranges

Check this box if you want the range definitions in your model to be displayed in equations view.

Labels

Choose the display mode (plain text or icons) that you want to display for equations view.

Apply To

Use this list to determine the scope of your settings. You can choose among the following:

•	Window

•	Document

•	All Open Docs

If you choose Window, the settings will affect only the current window. If you choose Document, the settings will affect all diagram windows of the current document. If you choose All Open Docs, the settings will affect all diagram windows of all open Powersim documents.

Use As Default

Click this button to make all new Powersim windows use the current setting as the default. The settings are stored in the configuration file POWERSIM.INI.


General options

Use this category to set some general options.

See also

General dialog box


General dialog box

Dialog box options

Create New Document on Startup

Use this option to indicate whether or not you want a new document to be automatically created when Powersim is started.

Measurement Units

Choose among centimeters, inches, and points as the measurement unit in the diagram editor. (A point is equal to 1/72 inch.)

Numerical Format

This option specifies the numerical format to be used in objects and dialog boxes of Powersim. The list contains all combinations of thousand separators and decimal separators:

•	1.234,22

•	1,234.22

•	1234,22

•	1234.22

•	<From Control Panel>

If you select the last entry, Powersim will use the format specified in the International setting of the Windows Control Panel.

Variable List Sorting

The list contains the following sorting criteria to be used in variable lists:

•	Name

•	Type, Name

•	Type, Use, Name

•	Use, Name

•	Use, Type, Name

Sorting by Name means listing in ascending, alphabetical order by variable name. Sorting by Type means listing variables by type in the following order: Levels, Auxiliaries, Constants. Sorting by Use means that variables used as rates are listed before those that are not used as rates.

User Name

Type the name you want Powersim to use as the author in the Properties dialog box.


Save options

Use this category to set options concerning the saving of Powersim documents.

See also

Save dialog box


Save dialog box

Dialog box options

Save Options

This group to set save options.

Always Create Backup Copy

If this box is checked, Powersim will make a backup copy of the current document, with file extension BAK, each time the document is saved.

Prompt for Properties Dialog Box

If this box is checked, the Properties dialog box is opened automatically after you have confirmed the saving in the Save As dialog box.


Window Attributes options

Use this category to set window attributes for the current window.

Hint	These options are useful for customizing Powersim windows, for example, for gaming purposes.

See also

Window Attributes dialog box


Window Attributes dialog box

Dialog box options

Style

Use this group to set style options for the current window.

Sizing Frame

Use this box to switch the sizing frame for the current window on/off. This box is disabled if the current window is maximized.

Minimize and Maximize Box

Use this box to switch the minimize or maximize for the current window on/off.

Horz. and Vert. Scrollbar

Use these boxes to switch the horizontal or vertical scroll bar for the current window on/off.

Icon File

Type or select the name of the icon file to be used by the window in minimized mode. You may use Browse to select an existing icon file. The file must be stored in icon format, which may be produced by icon editors, such as the one found in AppStudio (part of the Microsoft Visual C++ package).

Locked

Use this box to lock/unlock the icon setting.  If locked, the icon will be locked to the current setting. This implies that the current icon will be used even if the icon file is changed. If unlocked, the icon file is loaded from the named file every time the document is opened.

Default

Click this button to choose the default icon for the current window.

Browse

Click this button to open a dialog box for selecting an icon file. When you hit OK in the dialog box with an icon file selected, the name of the file is inserted into the Icon File text box.

Caption

Type the caption text for the current window.


Metodological Issues

The following topics contain papers written by leading system dynamicists and modellers. They focus on various methodological aspects involving the use of Powersim.

  Introduction

  Powersim as a Tool for System Dynamics Modeling

  Using Powersim to Teach Sustainable Economic Development

  Feeding Your Models with Real Business Data

  Powerful Modeling Using Array Variables


Introduction

Powersim is designed to support a quantitative and experimental approach to management, as described in the system dynamics method. The steps of a system dynamics analysis were first described by Jay W. Forrester in his book "Industrial Dynamics":

1	Identify a problem.

2	Isolate the factors that appear to interact to create the observed symptoms.

3	Trace the cause-and-effect information-feedback loops that link decisions to action to resulting information changes and to new decisions.

4	Formulate acceptable formal decision policies that describe how decisions result from the available information streams.

5	Construct a mathematical model of the decision policies, information sources, and interactions of the system components.

6	Generate the behavior through time of the system as described by the model (usually with a digital computer to execute the lengthy calculations).

7	Compare results against all pertinent available knowledge about the actual system.

8	Revise the model until it is acceptable as a representation of the actual system.

9	Redesign, within the model, the organizational relationships and policies which can be altered in the actual system to find the changes which improve system behavior.

10	Alter the real system in the directions that the model experimentation has shown will lead to improved performance.

Steps 3, 5, 6, 8, and 9 are directly supported by the Powersim software package.


Powersim as a Tool for System Dynamics Modeling

by Professor Pål I. Davidsen

All human beings live in a complex, dynamic reality of natural and social systems. Most systems are not in equilibrium and their states change continuously. In order to understand, adapt to, and control this reality, methods must be developed to capture it in formal models. Powersim is a major contribution to the set of tools that facilitate the study of dynamic systems.

Modeling reality

The mental models of decision makers cannot process the variety and complexity of most of the systems experiencing problems. With the use of computers, however, it is possible to explicitly represent, combine, and formalize these models, and communicate their assumptions to laymen, students, colleagues, and policy designers who will subject them to constructive criticism.

Simulation models, in particular, can be used to investigate the intimate relationship that exists between the structure and behavior of dynamic systems. That is, how problematic behavior arises from the underlying structure of a system and how this structure can be modified to alleviate system's problems.

Method developed at MIT

In the late 1950s, Professor Jay W. Forrester of the Sloan School of Management at the Massachusetts Institute of Technology, developed the system dynamics method for this purpose. Since then, this method has been applied to a wide variety of issues and problems in both the public and private sectors. Large corporations and governmental agencies make use of the insights gained from building system dynamics models in their design of policies and strategies, and in their tactical and operative decision making.

Powersim is a major contribution to the set of tools that facilitate the study of dynamic systems. It is an excellent MS Windows-based software package that makes possible the formulation of simulation models in the graphical notation originally developed by Professor Forrester.

Experimental approach

In order to identify the underlying causes of real problems, realistic models must be developed, analyzed and modified experimentally.

In the past, policy makers have spent a lot of time and effort developing and teaching effective ways to analyze relatively simple models. In particular, they have been concerned with identifying their equilibrium conditions.

Less time and effort have been spent on developing tools that can be used to represent systems in dynamic transition between equilibria never attained.

Within the system dynamics paradigm, emphasis is placed on model conceptualization and on the utilization of a wide spectrum of criteria for model validity that helps ensure that the resulting models correspond to real systems -- structurally as well as behaviorally.

"Better to be almost right than exactly wrong"

The emphasis on realism has two implications. First, it implies that models must reflect the complexity of real systems. Although model simplicity is a virtue, complexity is often a necessity. Second, it implies that optimal solutions in many cases cannot be found in closed form, and that simulation techniques and the experimental identification of realistic solutions must be utilized. As a wise person once noted: "it is better to be almost right than exactly wrong".

Properties of complex systems

Complexity defies human intuition. In particular, there are four kinds of structural properties that humans find cognitively challenging in dynamic systems.

First, there is the origin of dynamic behavior itself - the relationship between flows and levels. Levels accumulate flows and flows cause the levels of levels to change over time. Although simple in principle, humans often find it difficult to distinguish between real levels and flows and to identify the behavioral consequences of flows acting on levels.

Second, there are delays or lags in actual systems. Delays distribute the effects of changes in variables throughout a system over time and often cause information to arrive at its destination in an untimely, and hence harmful, manner. Delays and lags lead humans to discover and give priority to short-run gains and to ignore and postpone actions against future losses. Delayed reactions typically cause systems to over and undershoot and thus to exhibit oscillatory behavior.

Third, there is feedback. Real world systems are usually characterized by circular causality. Their structures contain feedback loops that transmit the dynamic behavior of one attribute to the next until the circle is closed and the signal, in a modified form, is fed back to its origin. Such loops have a tendency to stabilize or to destabilize a system. When humans try to manage a feedback system, their actions are typically amplified or counteracted, depending on which feedback structure are dominating the system at the time.

Finally there are non-linearities. Nonlinearity implies that system attributes influence each other in a non-proportional way and that they interact so that their partial effects, playing out over time, cannot easily be distinguished. Such interactions may cause shifts in the structural dominance of a system over time. That is, substructures that have dominated a system's behavior for some time may, suddenly or gradually, loose their influence while other substructures gain influence. This typically causes a dramatic modification of the system's dynamic behavior.

These characteristics of complex systems tend to mask the relationship between cause and effect, and thus to obscure current problems and hide the means of solving them. Successful solutions are thus often counterintuitive and hard to identify. In addition, there are often uncertainties associated with system, and humans tend to state their perceptions, policies, preferences and attitudes vaguely. As a result, realistic models of systems require the use of both random and fuzzy numbers in simulations.

Supports constructivism

System dynamics supports constructivism. It facilitates the building of microworlds that allow the study of how complex patterns of behavior arise when micro-structures, exhibiting simple behavior patterns in isolation, are connected. Conversely, it facilitates the analysis of the structures underlying complex behavior patterns. Powersim, as a system dynamics tool, is useful for investigating the relationship between micro and macro structure as well as behavior.

Transfer of knowledge

The system dynamics method enables decision makers to use their experience. When people learn from studying one dynamic system they can often transfer their knowledge to other, similar systems. The symbols utilized to create systems dynamics models are quite general. As a result, system dynamics models are often able to generate insights across disciplines. Such generalized models are called generic structures, and their associated behavior is generic as well. The exponential growth or goal seeking behavior arising from simple first order positive and negative feedback loops, the S-shaped pattern created by a shift in dominance between positive and negative loops, and the oscillations typically resulting from lags in negative feedback loops, are simple examples of generic structures and behaviors. Knowledge of such structures and behaviors can be applied to many specific systems, under many specific circumstances.

Powersim is particularly useful at utilizing generic models. These models can be stored in a library from which they can be copied, modified, and incorporated as co-models or integrated (pasted) as sub-models, in a larger "main" model.

The ability of Powersim to describe and solve problems, however, suggests that its real benefit arises from its use in the model building process itself, rather than from its ability to simulate a particular model. As a result, the people who both know the system experiencing the problem, and are charged with implementing model-based results, should participate fully in the modeling process. Their participation increases the likelihood that they will believe the model they helped to create and will implement its results. Powersim's graphical user interface greatly reduces the barriers to the participation of policy makers in the modeling process.

Improving dynamic intuition

Experience tells us that the dynamic intuition of humans is poorly developed. When presented with simple dynamics problems, humans tend not to take feedback, delays, non-linearities, and uncertainties appropriately into account. This is mainly because the training decision makers traditionally receive is inadequate for dynamic thinking. Three conclusions can be drawn from this:

First, students must be trained from an early age to develop a fundamental understanding of complex, dynamic systems. The founder of the field of system dynamics, Professor Forrester, devotes much of his time to the System Dynamics in Education Project at MIT, aimed at developing educational material for students and teachers in American high-schools. Realizing the importance of establishing a dynamic intuition among young people, the Norwegian Ministry of Education have included dynamic modeling as a central part of the new informatics course for Norwegian high schools.

Models are undeniably abstract, and do not always aid in the effective communication of system insight or problem solutions. Recently, however, microworlds or, more specifically, management flight simulators with capturing interfaces, have been developed to create the requisite engagement in complex systems. Although apparently successful, many questions regarding the educational benefits from these simulators remain unanswered.

Although such simulators may serve to trigger an interest in a problem, they typically emphasize behavior at the cost of providing a deeper understanding of the structural origin of that behavior. By making full use of the MS Windows interface, Powersim facilitates the creation of spectacular management flight simulators. In addition, any user of a flight simulator, can gain access to the underlying model structure, and, when necessary, modify that structure.

This illustrates how Powersim aids in both decision making, and policy design that requires a structural understanding and structural modifications to a system.

How are decisions made?

The questions arising from the utilization of microworlds in management training are currently under intense scientific investigation.

How are decisions made in a complex, dynamic environment?

What information is taken into consideration?

How is that information transformed into a decision, and how are decisions being implemented?

What circumstances affect this process?

Which system properties pose the major challenges to the decision maker?

Policy design

These types of questions must be answered in the process of designing appropriate policies. For that purpose, policy makers are exposed to a management flight simulator. Traditionally, these simulators have not allowed the policy maker to experiment with the models underlying their structures (i.e., they have not allowed the policy maker to alter their structures as they would do in real life).

Powersim has been developed so that participants in a management game can simulate off-line while designing their own strategies. Combined with constrained or free access to the underlying model, this allows them to investigate a wide spectrum of research topics in decision and management sciences.

Powersim important for the growth of system dynamics

Managers, scientists, teachers, and students should be highly satisfied with the successful development of Powersim. It will be of major importance to the growth of the field of system dynamics and to the utilization of system dynamics as a policy design method in complex, dynamic environments.

Pål I. Davidsen is a professor in system dynamics at the Department of Information Science at the University of Bergen.


Using Powersim to Teach Sustainable Economic Development

by Dr. Michael J. Radzicki

During the past five years, the daily news has become increasingly filled with stories of economic stagnation and environmental destruction. As a result, student interest has rekindled in an area of economics known as "sustainable economic development." Simply put, sustainable development involves the design of policies that balance economic activity and environmental preservation. It is thus an area that attempts to address a question that has intrigued economists for more than 200 years: How can the needs of the present generation be met without compromising the needs of future generations?

The purpose of this article is to describe how system dynamics and the Powersim software package are being used to teach the economics of sustainable development at the university level. The students involved are undergraduates at Worcester Polytechnic Institute in Worcester, Massachusetts, USA. They typically have no training in either economics or system dynamics prior to their participation in the course in which Powersim is used.

A Quick Overview of the System Dynamics Method

The system dynamics method rests on four fundamental ideas.

The first is that all dynamic behavior in the world occurs when flows are accumulated in levels. A level can be thought of as a bathtub and a flow as a pipe and faucet assembly that fills or drains the tub.

The second fundamental idea is that a systems levels and flows are imbedded in feedback loops. Feedback is the transmission and return of information. In system dynamics modeling, information about a systems levels travels throughout its structure until it reaches its flows. In response to the information, the flows alter the levels and hence close the feedback loops.

Two kinds of feedback loops exist in system dynamics modeling -- positive loops and negative loops. Positive loops generate self-reinforcing behavior and negative loops generate stabilizing or counteracting behavior.

-	An example of a positive loop is the relationship between births and population in a developing country. As the countrys population increases, its number of births will increase and, as more babies are born each year, its original increase in population is reinforced.

-	An example of a negative loop is the relationship between deaths and population in a developing country. As the countrys population increases, more of its people will die and, as more people die each year, the countrys original population increase is counteracted or resisted.

The third fundamental idea in system dynamics modeling is that the feedback loops in any system are often joined together by nonlinear couplings. Essentially this means that information about a systems levels feeds back to affect the levels in nonproportional (and often complicated and unpredictable) ways.

The last fundamental idea in system dynamics modeling is that the dynamic behavior inherent in a systems interacting web of levels, flows, feedback loops, and nonlinear couplings cannot be ascertained by the unaided human mind, nor solved for mathematically, in closed form. As a result, computer simulation is required to reveal the dynamic behavior of complex systems.

The Traditional Approach to Sustainable Economic Development

The very name of the subdiscipline -- sustainable economic development -- conjures up an image of an economic system changing over time in response to (and often in spite of) the efforts of policy makers to control it. Yet, the traditional approach to teaching sustainable development involves forcing students to learn a collection of static (and often incompatible) models that attempt to identify policies that will foster sustained economic activity. When the traditional approach ventures into the arena of dynamic analysis, moreover, it usually does so in a verbal and imprecise manner. Lastly, although the traditional approach occasionally utilizes the concept of feedback, it does so in a somewhat curious manner. More specifically, the traditional approach occasionally identifies positive feedback processes that work to hold back a nations economic development but rarely, if ever, identifies any negative feedback processes. Further, the positive feedback processes that are identified are not referred to as such, but rather as "vicious circles" or processes of "circular and cumulative causation." In sum, the overall problem with the traditional approach to teaching sustainable development is that there is no way for students to integrate the various insights put forth via the static models, data, and positive feedback processes to which they are introduced, and no mechanism for revealing the dynamic behavior inherent in the insights.

Using Powersim to Teach Sustainable Economic Development

At Worcester Polytechnic Institute, sustainable economic development is taught via system dynamics and the Powersim software package. The basic approach is to have students read traditional materials on economic development while simultaneously building a Powersim model of a developing nation. After the students have completed the model, they play a Powersim game based on the model. The students use the game as a "microworld" or "learning laboratory" for gaining insight into the dynamics of the developing nations they have been studying.

The Powersim model and game are based on a system dynamics board game originally created by Dennis Meadows called STRATAGEM-1. One of the "problems" associated with STRATAGEM-1 is that it typically takes four to eight hours to play. For obvious reasons, this makes it somewhat difficult to use in a university classroom setting (although breaking up play over a span of days or weeks is one practical way to address this issue). Meadows chose this design for STRATAGEM-1 because he feels that system dynamics games are best played by teams of individuals, seated around a table discussing game decisions as equals, with the computer and model out of their streams of consciousness.

Although Meadows position on the design of system dynamics games is compelling, as a practical matter, STRATAGEM-1s playing time makes it less attractive to use in an undergraduate development course. To compress playing time and enable STRATAGEM-1 to be played as a homework exercise, therefore, it was translated into a Powersim model and game. During this process, it was discovered that the STRATAGEM-1 model did not address some fundamental issues that are discussed in the traditional development literature. As a result, the STRATAGEM-1 model was expanded to accommodate these issues.

As with all types of gaming, briefing and debriefing sessions are vital if the players are to have a meaningful experience. WPI students are prepared to play the Powersim development game by being asked to build the underlying model, sector by sector, in class, during the course of the term. This process gives the students a detailed knowledge of the model and helps them to see how the relationships discussed in the traditional development literature are represented in the model.

The figure below presents a Powersim level-flow diagram of the simplest version of the demographic sector of the sustainable development model. This is the first model with which the students interact.

By contrast the next figure presents the sixth version of the demographic sector. It is quite clear from this figure that the students are able to progress to a fairly high level of model complexity. The demographic structure presented enables them to keep track of, among other things, the developing nations dependency ratio -- i.e., the ratio of its work force to its very old and very young citizens.

The figure below presents a copy of the playing screen for the sustainable development game. Each of the icons can be opened via double clicking to reveal on-line help, time series plots of various variables in the model economy, or Powersim "slider bars" that enable some of the models parameters to be changed during a pause in the game.

The figure below resents the foreign loan decision slider bar, accessible by double clicking on the appropriate icon in  the game interface.

During play, students can change the amount of money the developing nation borrows from international sources (e.g., the World Bank). The maximum possible loan represents 25% of the current net worth of the country. Other allocation decisions the students can make involve: 1) food -- how much for export, how much for domestic consumption; 2) goods -- how much for export, how much for domestic consumption, how much for investment in each of six types of capital (goods producing, food producing, energy producing, environmental protection, energy efficiency, social services); 3) energy -- how much for export, how much to power each of the nations capital levels, how much to save; and 4) foreign currency -- how much to spend on imports of energy, how much to spend on imports of food, how much to spend on imports of goods, how much to spend on debt retirement, how much to save.

The students step the economy through twenty simulated years. After each two year period, Powersim pauses and allows the allocation of resources to be changed by the slider bars. The students can thus test the consequences of policy options and their knowledge of the interactions in the model. Of course, if they do not like the results, they can simply play again. Indeed, Powersims user friendly interface invites the student to play again.

Conclusions

Powersim has enabled the STRATAGEM-1 game to be recast in a manner that compresses playing time and allows for the expansion and modification of the underlying system dynamics model. Student response to the game has been enthusiastic and student knowledge of the important issues and interrelationships in the area of sustainable development have been enhanced. Current research is being directed toward adding Third World urban-rural migration and a "First World" sector to the underlying system dynamics model. The latter addition will permit two students to play the game simultaneously over a LAN -- one making the decisions for the less developed sector, one making decisions for the more developed sector. This will allow the importance of the linkages between the nations of the world (e.g., environmental, trade, financial) to be powerfully illustrated.

Dr. Michael J. Radzicki is an Associate Professor of Economics at Worcester Polytechnic Institute, Worcester, Massahusetts, USA.


Feeding Your Models with Real Business Data

by Magne Myrtveit

In making models of real world problems or real world processes, the need for transfer of data between model and external files, applications or other devices becomes important. This article illustrates the use of automatic data transfer in model construction and in process control.

In a typical model construction and verification process, real data plays an important role. Once a model is made of the target system, real data is fed into the model, and the model output is compared to the output of the real system. The result of the comparison is used as a basis for refining model structure, model parameters, or both.

The Dynamic Data Exchange (DDE) object and the Archive object of Powersim may be used in a model to import and export data during simulation. This greatly reduces the amount of work involved in checking models against reality. DDE can also be used to set up a data analysis, for example, by launching a spreadsheet or a statistical program. In combination with the multiple runs feature of Powersim, a series of model structures and model parameters can be tested with real data without manual intervention.

In a research project aiming at developing a model of the biological process of fish growing in a fish farm, the above tools have allowed for extensive use of data from fish farms in the process of model construction and verification.

The basic feedback loop of a process control system, involves measurement (import of data), comparison between measured values and desired values, followed by a controlling action (output of data) aiming at closing the gap between actual and desired process state. The data transfer protocols of Powersim make it possible to implement process control systems as Powersim models, and linking the models to the physical process. A range of input/output devices for the Windows operating system supports DDE or Net-DDE, and may therefore be used directly together with Powersim.

Tools for modeling real businesses

A variety of tools are used in describing, measuring, storing, retrieving, transferring, analyzing and presenting business data.

Figure 1: Past, current and projected business data

Databases and spreadsheets are commonly used to store current and past business data. Statistics can be produced based on time series (history) of data. System behavior can be described using time graphs and time tables that may be produced easily using a variety of tools, including word processors, presentation software, spreadsheets, and database front-ends. System structure (relationships, cause and effect) is often described as static maps (organization charts, flow charts, etc.). For simple systems, differential mathematics can be used to describe system structure and infer system behavior. Using statistical methods (models), projections may be made into the future, for example by extrapolation. Even within the field of systems thinking, a variety of tools are used.

Figure 2: Transfer of data to and from simulation model

Simulators represent a valuable extension to the set of business tools. A main use of simulation models is to describe a system (for example a problem, an organization or a process), and to carry out simulations mirroring the behavior of the system. The dynamic nature of simulation models adds a new dimension business modeling.

In verifying a model, recorded history is compared to simulated output from the model. If there is a close match between model behavior and actual history, the model will most likely be a valid description of the real system.

Even valid models can fail significantly in predicting the future of a business. One reason for this is that for most business processes there will be a number of uncertain factors that will influence the system. We therefore have to make assumptions about external factors when making simulations into the future. Fed with different sets of assumptions, a simulation model can produce quite different results. This makes it possible to get answers from the model to what-if questions, and test consequences of assumptions.

A dynamic model is a virtual world

Creating a simulation model can be looked upon as creating a virtual world representing parts of the real world. We can think of modeling as a goal seeking loop where the real world is the goal, the current model is the actual value, and the modeling process is the corrective action.

The balance icon is used to denote a balancing feedback loop.

Figure 3: Balancing loop

Figure 4: Creating a virtual world

If we change the names in Figure 3 a little, we get a picture of the modeling process, as shown in Figure 4.

In determining the gap between Virtual World (model) and Real World we may use qualitative and quantitative measurements.

Qualitative comparisons between model and real world

Qualitative comparisons between model structure and relationships in the real world are of great value in the conceptualization of a problem. The field of systems thinking has developed numerous tools for analyzing a problem and developing a simulation model describing the problem and its behavior. Using causal loop diagramming, for example you may create a high-level map of any dynamic problem. Or you may try to fit your problem into one of the system archetypes that have been identified.

If you choose to use causal loops to describe your problem, studying feedback loops can shed light on important characteristics of the models behavior. And if you use archetypes to describe your problem, the typical behavior of each archetype can be used to make rough statements about basic behavior of your real world problem.

Quantitative comparisons between model and real world

A simulation model can be compared to a hypothesis about a phenomenon. By comparing model behavior to the real world we can determine the validity of our hypothesis. A model that corresponds well to the phenomenon it describes, can be used as a theory (see Figure 5).

In the range between scientifically verified theories and vague statements there is room for a broad variety of models. Based on the intended use of a model, the level of necessary accuracy will vary. As an example, a model for educational purposes can be useful even if it does not give 100% accurate output. In the business world, however, we often encounter situations where even small variations in model output are of importance.

Figure 5: Models describe hypotheses and theories (verified hypotheses)

The final adjustments of a model normally involves parameter tuning. In Figure 6 we have added labels to the arrows from Real World and Virtual World to Gap. One set of data is obtained by gathering statistics about the real world, while another set is produced as output from a simulation run.

Time	1	2	3	4
Actual (A)	5	7	3	4
Simulated (S)	4	5	2	3
Difference (D=A-S)	1	2	1	1
D*D	1	4	1	1
Figure 6: Comparing simulation output to real world measurements

The sets of measured and simulated data can be compared to compute a numerical gap between the real world and the model. The gap can be computed in different ways. A simple solution is to compute the difference between actual and simulated data. Another approach is to compute the sum of the squares of the differences between actual and simulated data. The latter approach may be useful when several variables are compared, or when time series are compared. (The term time series is used when we refer to a set of values for a variable at different times.)

In Figure 7 we have made a table with a hypothetical actual time series [5, 7, 3, 4] and a simulated series [4, 5, 2, 3]. The differences between each element of the actual and the simulated series are computed and squared. By adding together the numbers in the final row we get 7, which is a measurement for the gap between actual and simulated values.

Figure 7: Computing the gap between actual and simulated data

If the actual values are imported into the simulation model, the gap may be computed during simulation, like this:

Powersim diagram	Powersim equations
	aux Actual = ... aux Simulated = ... aux DiffSquared = (Actual-Simulated)^2 init Gap = 0 flow Gap = +dt*DiffSquared
Figure 8: Computing the gap as part of a simulation

The definitions of Actual and Simulated will vary from model to model.

Importing data into the simulation

Values of external factors (observed or assumed) influencing a model are often stored in data files. The same is true for historical business data that we may want to include in our simulation for comparison with simulated vales.

For small data sets it may be OK to type the data into the simulation model, for example as parameters to a table look-up function. In a real business situation, however, we may want to experiment with different data sets, and each set of data may be quite large. This means that typing data into the simulation model becomes inflexible, time consuming, and error prone. We should therefore look for methods of automatic data transfer between a simulation model and the environment.

Powersim includes mechanisms for accessing external data files directly, or indirectly, via communication with applications managing the data (for example spreadsheets).

Figure 9: Data transfer with files and applications

Importing data from files

Powersim can read text files directly into a simulation using the archive object. Setting up a transfer is done by creating an archive object in the model, and connecting a data file to one or more parameters (scalar variables or array elements) of the model.

Text files with data to be imported into Powersim can be created in several ways. You may, for example, use the Windows text editor Notepad or any other application that is able to store files as plain text. Most spreadsheets will allow you to choose Text as output format when storing a spreadsheet using the File Save As command. The same is the case for most word processors.

Powersim can read data either as time series or as single values. As an example, we may enter the time series Actual that was used in the previous chapter, into a text file ACTUAL.TXT. The data can be organized in the file as displayed in Figure 10.

Time	Actual
1	5
2	7
3	3
4	4
Figure 10: Text file holding time series to be imported into Powersim

A tab character is used as column separator. Options to the archive object are used to match the format of the imported data, for example choice between horizontal or vertical orientation, presence of time series row or column, presence of row or column headers, choice of column separator, numerical format.

If we want to import the data in Figure 10 into our simulation model, we define a constant variable Actual to receive the data. We then open the archive object to make a connection between the constant and the text file ACTUAL.TXT. Before simulating, we should define the time horizon for the simulation to be from 1 to 4, as this is the range for which we have data. We can now run the simulation.

In order to verify that the variable Actual takes on the values stored in the text file, we can create a time table object and make Actual a parameter of the time table. The resulting diagram is displayed in Figure 11.

Figure 11: Diagram with constant, archive and time table

Importing data from applications

Figure 12: Spreadsheet with time series

Dynamic Data Exchange (DDE) is the name of a standard protocol for data transfer between MS-Windows based applications. Most industry strength applications  including Powersim, MS-Word, MS-Excel, and Lotus 123  support DDE.

DDE is based on a client server architecture, where a client application can ask a server application for services. Powersims DDE object defines the client end of a DDE link, allowing Powersim models to transfer data to or from a DDE server application.

As an example, let us enter the data in the file ACTUAL.TXT into a spreadsheet as displayed in Figure 12.

In order to obtain data from a DDE server (for example a spreadsheet) we must inform the DDE object about:

Server  the name of the server application, for example Excel

Topic  the name of the document where the data is stored, for example ACTUAL.XLS

Item  the part of the document where the data is located, for example R1C1:R4C2

The DDE object in Powersim is almost identical to the archive object. The main difference is that File in the archive object is replaced by Server, Topic and Name in the DDE object.

Exporting data from the simulation

By changing the transfer to To File for the archive object and To Application for the DDE object, data can be transferred from a simulation to a file or another application, respectively.

It is possible to use several archive and DDE objects in one model, allowing for transfer of data in both directions. As an example, while data is read from one column of a spreadsheet, simulation output can be written back into another column.

The possibility to store simulation results in a file or into documents managed by other applications, opens for storage, transfer, analysis, and presentation of simulation output using applications of your choice.

Closing the circle of continuos improvement

Creating a micro world may serve several objectives, including;

gaining insight into the real world through the modeling process,

training people with management flight simulators based on running simulations,

designing strategies for improving the real world using experimental simulation.

Powersim is designed to support all of the above activities. In Figure 13 we display how a continuous improvement process can be implemented.

Figure 13: Simulation as a basis for continuos improvement

Each of the arrows in Figure 13 involve actions that must be carried out in order to close the loop. Powersims data transfer capabilities are important in importing measurements from the real world into a simulation. Advanced modeling capabilities like arrays and co-models help make realistic models. For creating custom interfaces to micro worlds Powersim contains authoring capabilities, and can also be integrated with custom interface applications using both DDE and Application Programming Interface (API) calls from languages like C, C++ and Visual Basic.

Using DDE to control a process

Figure 14: Connecting a model to the external world

A DDE link can be automatic ("hot") or manual ("cold"). An automatic link will transfer data whenever the source data is altered. This can be used to interact with a model during simulation. It is, for example, possible to set up a DDE connection between Powersim and Excel where a Powersim variable is updated whenever the value of a given cell is changed in the spreadsheet. The opposite connection is also possible, i.e. that a spreadsheet cell is updated continuously during a simulation based on a Powersim variable.

Input/output equipment for lab experiments or process control are often shipped with software components defining a DDE interface to the equipment. Using such interfaces Powersim models can be connected to the physical world.

Example  a virtual fish farm

The fish farming industry is important along the entire cost of Norway. The worlds largest aqua research laboratory is located here, with access to lots of research data and skilled researchers. A project was launched together with the Norwegian environmental authorities to develop a better understanding of the relationship between production, economy and wastes to the environment.

A team was put together with people from two research laboratories, a fish feed producer and myself. It soon turned out that the research communities had access to advanced knowledge in isolated areas such as influence of light, currents, temperature, oxygen feed and feed composition on fish growth. At the same time there was an obvious need for combining the fragmented knowledge into a unified whole. We therefore choose to create a virtual world aquaSIM™ portraying the fish farming system. The resulting model would be verified using existing research data. If necessary new data would be obtained from the research stations and co-operating fish farms. Finally, the model would be presented in two versions; one for research purposes and one for planning purposes.

The model was designed around the use of co-models, where two different interfaces were used; one for the research model and another for the planning version.

A micro world for planners

For pedagogical purposes the planners micro world was designed to visualize differences between alternative production methods. Each production decision was made a parameter to the aquaSIM model. By varying the parameters, different scenarios can be played out.

Figure 15: Structure of the planner's fish farm model

By interacting with slide bars, number objects and buttons in the interface model (main) the planner can set different parameters in the reference model and the alternative fish farm model (the two aquaSIM co-models in the bottom of Figure 15).

Figure 16: Giving input to two simulations (Actual and Reference) from the Main model

By running two alternative scenarios concurrently it becomes easy to compare the two simulations by displaying time series from both models in the same reports. As an example, the feed consumption, growth and pollution can be displayed in time graphs where one color (say gray) is used for the reference model and another color (say red) is used for the alternative. In Figure 17 the growth (weight) of fish is compared. The alternative co-model (labeled Actual) uses a feeding intensity of 80% of the reference co-model.

Figure 17: Comparing growth at different feeding levels

As can be seen from Figure 16 the user may choose between different productions (species of fish), locations (temperature zones) and feed compositions. The effects of these parameters on the model are controlled by parameters. The actual parameters are stored in external files, which are loaded into the simulation at simulation start-up using the archive object, described earlier.

A micro world for researchers

This application was developed in order to gain insight into the fish farming process. One key issue was to validate the model. This was set up along the lines described earlier in this paper. A simulation model was fed with research data and the simulated output compared to the real data (see Figure 6).

Figure 18: Importing model parameters from external files using archive object

A main model was used to create an interface to aquaSIM. The main model would read research data from a spreadsheet, run aquaSIM as a co-model and output simulation results alongside the real data in the spreadsheets.

Figure 19: Structure of research model and connection to real data

Since both the researchers version and the planners micro world uses aquaSIM as the core co-model, any improvement to the research model will automatically be part of the planners version.

The first stage of the aquaSIM project was completed this spring (1995). The researchers give the feedback that they now have a powerful new tool for understanding the complex nature of fish farming. The model building process has uncovered new areas for further investigation. Looking at the initial objective of the project, the simulations show that the most economic way to run a fish farm is also the way that causes the least damage to the environment. This corresponds well with research data, and can be visualized in convincing ways using the aquaSIM Powersim models. The vast amounts of that that was necessary in validating process could not have been used without access to automatic data transfers.


Powerful Modeling Using Array Variables

by Magne Myrtveit

As the field of system dynamics modeling is expanding, there is a continuous need for improvements of the available tools for developing simulation models. Lack of features like array variables often lead modelers to choose third generation languages like C when developing large, realistic models.

This article describes the array variables of the Powersim language. Comparisons are made other notations, including mathematics and DYNAMO. Index variables, array dimensions, subscripts, and functions working on arrays are described.

An important feature of Powersim is that the array notation goes well together with standard accumulator-flow diagrams (AFD) and causal loop diagrams used by system dynamists. This makes the use of array variables almost as easy and intuitive as using scalars.

The transition from single scalar values to multi-element array variables is visualized through examples. Examples include capital stock with machines and buildings, work force with inexperienced and experienced workers, delay structures programmed as arrays, etc.

The array features of Powersim have been used with success in several large-scale projects. Many modeling problems are not practically solvable without using arrays. Even models that are solvable using only scalars, sometimes become much easier to develop, explain and maintain when using arrays. In conclusion, the family of simulation problems that are best solved using a system dynamics tool has been extended a great deal through Powersim's array mechanism.

The array features of Powersim

A dynamic model is a mathematical description of a real of imaginary system. The use of accumulator-flow models makes the power of mathematical integration available in an intuitive and straight forward way, also for non-mathematicians. The use of vectors and matrixes (arrays) are powerful features of mathematics. Several approaches have been made to add array variables to dynamic modeling languages. A major weakness of the early approaches seems to be that the solutions are selected with limited focus on graphical editing of the simulation model as an AFD (Accumulator Flow Diagram).

Our goal has been to provide the power of dimensioned variables (arrays) to Powersims simulation language in a way that both the textual and the graphical representation of models are kept as simple and intuitive as possible.

The inclusion of array variables has implications on three aspects of the simulation tool; 1) the textual simulation language (the equations); 2) the graphical accumulator-flow diagram; and 3) the user interface. Each of these will be discussed below. The following terms will be (informally) defined: array, scalar, literal, range, subrange, enumeration, dimension, subscript, index, constraint, guard.

Scalar variables

Normal variables are called scalar variables, i.e., variables holding single numerical values. As an example, the definition

const	InterestRate = 5%

defines a scalar constant named InterestRate with the single value of 0.05. Scalars are displayed with a single frame in the diagram, as displayed in Figure 20-a.

a) Scalar constant	b) Array constant
Figure 20: Scalar and array constant symbols

Array variables, array elements, vectors, and array literals

An array variable maypossible to define arrays with only one element. hold several distinct values (at the same time). Each distinct value is called an array element. As an example, the definition

const	AvgTemp(1..12) = [1.4, 1.2, 3.1, 5.9, 10.4, 12.8, 15.1, 14.9, 12.1, 8.3, 5.5, 3.2]

defines a vector (one-dimensional array) with 12 elements numbered from 1 through 12, inclusive. Each element holds an average monthly temperaturein Bergen, measured in ºC.

A list of numbers enclosed in square brackets ([]) is used to define a vector literal. In the above example the expression [1.4, 1.2, 3.1, 5.9, 10.4, 12.8, 15.1, 14.9, 12.1, 8.3, 5.5, 3.2] is a vector literal with 12 elementsscalar literal, e.g. 3.14..

The dialog box for defining variables is the same both for scalars and arrays (see Figure 21). For an array, the Dimensions section is used to define each dimension of the variable. In our example, AvgTemp has one dimension, with elements 1 through 12.

Figure 21: Dialog box for defining variables

A dimension must include a range specifying the elements of the dimension. In Figure 21 the text 1..12 in the Dimensions field defines a numerical subrange from 1 to 12, inclusive. Arrays are displayed using double lines in the diagram, as in Figure 20-b. Below the array elements and values of AvgTemp are visualized.

Value	1.4	1.2	3.1	5.9	10.4	12.8	15.1	14.9	12.1	8.3	5.5	3.2
Element	1	2	3	4	5	6	7	8	9	10	11	12
Functions working on arrays

Powersim has several functions that take array arguments. As an example, the average temperature during one year may be computed using the ARRAVG function with AvgTemp as argument, like this:

aux	AvgTempYear = ARRAVG(AvgTemp)

The right hand side of the above equation may also be written either as ARRAVG(AvgTemp(*)) or as ARRAVG(AvgTemp(1..12)).

Array variables like AvgTemp, with one dimension, are also called vectors. Vectors may be used, e.g., as arguments to the GRAPH family of functions. As an example, the expected temperature at a given month may be obtained using the following definition:

aux	ExpectedTemp = GRAPHCURVE(TIME MOD 12, 0, 1, AvgTemp)

Array subscripts for accessing array elements

Individual array elements or ranges of elements may be accessed using array subscripts. As an example, the expression AvgTemp(1) will obtain the average temperature in January, i.e., 1.4ºC. Subscripts may also be used to identify sub-arrays. The expression ARRAVG(AvgTemp(6..8)) will compute the average temperature during the summer months.

Numeric subranges

Sometimes it may be useful to use named sets of elements when defining variable dimensions. One reason may be increased readability. Another, more important, reason is that changes to a named range definition will have effect on all variables that use the range. In the above example we may define the numerical subrange 1..12 as a range with the name RMonth.

range	RMonth = 1..12

This may be done in Powersim by using the Edit Define Range dialog box (see Figure 22).

Figure 22: Defining a range

To define this range

1	Open the Define Range dialog box by selecting Edit Define Range from the menus.

2	Press the Add button of the Define Range dialog box  to make a new range.

3	Type in RMonth as the name of the range.

4	Observe that Numeric Subrange is selected in the Range Type combo box (this is the default setting).

5	Enter 1 in the From text box and 12 in the To text box of the Numeric Subrange group.

6	Press OK to accept the definition of the new range.

Our definition of AvgTemp may now be changed to the following:

const	AvgTemp(RMonth) = [1.4, 1.2, 3.1, 5.9, 10.4, 12.8, 15.1, 14.9, 12.1, 8.3, 5.5, 3.2]

By expanding the Define Variable dialog box (using the More>> button) we see that RMonth is presented in the list of Ranges (lower, left hand corner).

By selecting the entire text of the Dimensions field and double-clicking on RMonth in the Ranges list box, RMonth will be pasted into the Dimensions field of the Define Variable dialog box (see Figure 21).

Enumerated ranges

Elements of a range may be given mnemonic names. As an example, let us redefine the RMonth range as an enumeration of month names. This is done by opening the Define Range dialog box, and changing the Range Type to Enumeration. Element names are entered in the Elements list box by typing in one Element Name at the time and pressing the Append button (see Figure 22). The resulting range looks like this in equations view:

range	RMonth = January, February, March, April, May, June, July, August, September, October, November, December

The temperature in January may now be expressed as AvgTemp(January), and the average temperature in the summer months is ARRAVG(AvgTemp(June..August)).

Enumeration subranges

It is also possible to define sub-ranges based on previously defined ranges. The four seasons may, as an example, be defined as sub-ranges of the RMonth range. This is done by defining a new range and setting Range Type to Enumeration Subrange in the Define Range dialog box (see  Figure 22). By entering a name of RSummer, and selecting June as From and August as To, the following range will be defined:

range	RSummer = June..August

To make the above definition

1	Open the Define Range dialog box by selecting Edit Define Range from the menus.

2	Press the Add button of the Define Range dialog box  to make a new range.

3	Type in RSummer as the name of the range.

4	Select Enumeration Subrange in the Range Type combo box.

5	Select RMonth in the Subrange of combo box.

6	Select the first summer month (June) in the From combo box.

7	Select the last summer month (August) in the To combo box..

8	Press OK to accept the definition of the new range.

Editing vectors graphically using mouse and keyboard

Vectors and the GRAPH family of functions may be edited using the Edit Graph/Vector dialog box, which is opened by clicking the Graph button of the Define Variable dialog box. In Figure 23 the definition of AvgTemp is edited graphically. In the graph window the mouse may be used to draw the graph. The list of vector elements may be edited by making selections in the Coordinates list box and typing in new values in the Y text box, inserting elements using Insert, deleting elements using Delete. Elements may also be copied or pasted via the clipboard using the copy and paste buttons (see the bottom row of the keypad present in the dialog box).

Figure 23: Editing the AvgTemp vector graphically

The average summer temperature was defined above based on the anonymous subrange June..August, like this: ARRAVG(AvgTemp(June..August)). Using the named subrange RSummer the following alternative expression may be used: ARRAVG(AvgTemp(RSummer)).

Index variables

New array variables may be defined based on anonymous ranges, named ranges, and range elements. As an example, a variable AvgSummerTemp may be defined as a vector with three elements; June, July, and August. This may be expressed either as

aux	AvgSummerTemp(m=June..August) = AvgTemp(m)

or as

aux	AvgSummerTemp(m=RSummer) = AvgTemp(m)

Observe the introduction of the index variable m, which is defined in the dimensions section of the variable and used in the subscript of the expression defining the variable. In the above examples the use an index variable is required, as AvgSummerTemp and AvgTemp have different dimensions (see below).

AvgTemp:

1.4	1.2	3.1	5.9	10.4	12.8	15.1	14.9	12.1	8.3	5.5	3.2
January	February	March	April	May	June	July	August	September	October	November	December
AvgSummerTemp:

June	July	August

Using the index variable m we specify which elements of AvgTemp are going to be used when defining AvgSummerTemp. Index names (like Month in the definition above) are local to each variable definition, and hence, the same name may be used in different variable definitions.

Implicit subscripts and indecies

When dimensions match, index variables may be omitted if elements are going to be used on a one-to-one basis. Above weve defined AvgTemp like the following:

const	AvgTemp(RMonth) = [1.4, 1.2, 3.1, 5.9, 10.4, 12.8, 15.1, 14.9, 12.1, 8.3, 5.5, 3.2]

The full form of the above definition is like this:

const	AvgTemp(Month=RMonth) = [1.4, 1.2, 3.1, 5.9, 10.4, 12.8, 15.1, 14.9, 12.1, 8.3, 5.5, 3.2](Month)

Using arrays as parameters to dynamic objects

Array elements may be used in dynamic objects (e.g., time graph, time table, bar), as displayed in Figure 24. Here a Powersim Bar object is used to display the values of the AvgTemp array elements. The labels to the left in the figure may be changed by the modeler. The bars to the right in the figure show the current values of the array elements, and may also be used to change the values using the mouse.

Figure 24: Accessing array elements from dynamic objects

Automatic display of variable values

During simulation the value of a variable may be displayed in the statusbar by pressing the right mouse button while pointing the mouse cursor at a variable. For array variables, the values of array elements will be displayed, separated by comma and enclosed in square brackets (as for array literals). An auto report of an array variable will display the first element of the variable.

Erroneous flows and edited flows

As with scalar variables, a variable definition may become invalid for various reasons (e.g., the use of unknown variables or wrong use of functions). Powersim will then display a question mark inside the variable symbol (see Figure 25-a). With the introduction of arrays, flows may also become invalid. E.g., if a flow and the connected level have different dimensions, the system may be unable to determine how the elements of the flow are going to be paired to the elements of the associated level. It is easy to come up with useful examples where the dimensions of connected flows and levels vary. Powersim therefore allows the modeler to edit the flow definition of levels. This is done by selecting the Flow radio button in the Define Variable dialog box, and editing the contents of the Definition text box. Hollow flow arrows are, by definition, used to represent conserved flows. Powersim will put a warning exclamation mark (!) on a flow if it has been changed from its default definition (see Figure 25-b). If there is an error in a flow definition, Powersim will display a question mark on the flow arrow (see Figure 25-c).

Error in definition	Edited flow	Error in flow
a	b	c
Figure 25: Errors and warnings in the diagram

The problem of validating array subscripts

It has been a major design goal for the array part of the Powersim language to provide full range check on array subscripts at the time of model construction (vs. run-time). This has two major advantages:

1	The model will run more efficiently (no time is used by the processor for range checking)

2	Simulation will never enter a state where array subscripts get out of bound.

As an illustration, let us assume that we have two vectors, A and B, with equal dimensions, and that each element of B is going to be set equal to the element after the corresponding element of A, i.e., B(i) = A(i+1). This will be OK, except for the last index i, were the subscript (i+1) will be out of bounds.

We may attempt to solve the problem by means of an IF function, i.e., B(i) = IF(i < LAST(i), A(i+1), 0). This equation will access A(i+1) only for is in the range FIRST(i) to LAST(i)-1. The only problem is that this solution will, in general, require run-time checking of array subscripts, as any expression may be used as the controlling condition of an IF function.

Constraints and guards

In designing the Powersim language, we therefore choose to construct a separate conditional statement for constraining expressions based on the values of index variables. A constrained expression is an expression followed by a constraint. A constraint is basically an index expression determining when the preceding expression is going to be evaluated. Below is an example where the problem presented above is solved using constrained expressions:

B(i) = A(i+1) WHEN i < LAST(i)POWERSIM also has a FIRST function for returning the lower limit of a range or index variable. The COUNT function may be used to compute the number of elements in a range or separate values taken on by an index variable. BUT 0 WHEN DEFAULT

Here two constrained expressions, separated by BUT are used to define B. The expressions are:

A(i+1) WHEN i < LAST(i)

and

0 WHEN DEFAULT

A boolean expression following WHEN is called a guard. DEFAULT is a guard that may be used in the last constrained expression to cover all cases that are not included in earlier guards in the constrained expression list.

The key to understanding the impact of constrained expressions on compile-time validation of array subscripts lies in the fact that only index variables, range elements, ranges, and integer numbers are allowed as operands when expressing guards, array dimensions, and array subscripts. (Note that model variables are excluded from this list.) This implies that Powersim is able to determine and verify the values of all array subscripts without having to simulate the model.

Examples of when to use arrays

Replicated structures

Models often contain many identical or almost identical structures  especially large-scale models of realistic systems. If we, as an example, want to make a business simulator involving work force, capital, production, markets, etc. it is easy to identify several duplicate structures, e.g.:

1	Different kinds of capital, e.g. buildings and machines

2	Different market segments

3	Different kinds of workers

4	Different product lines

5	Different accounts payable, e.g., marketing expenses, goods, taxes, wages, dividends, debt

If we wanted to make a model of four competing companies, say, this would involve four similar structures  the main differences being values of parameters (constants) and accumulators (levels). Once a model of one company is developed, more companies may be added just by adding a company dimension to every variable of the model.

There are two important advantages of putting similar structures into arrays:

1	Maintainability  Changes to an array structures immediately takes effect for all elements of the array.

2	Complexity  Models sometimes become significantly smaller when using arrays (see Figure 26).

A	B
Figure 26: Combining similar scalar structures into one array structure. A shows separate structures for each type of capital while b shows structure with variables of capital type dimension.

State transitions

When modeling systems involving state transitions, it is common to express this as a sequence of accumulators with interconnected flows. Some examples are:

1	Training of people, moving people from a less skilled to a more skilled state

2	Aging of people, moving people from one age group to the next

3	Production, moving goods from less finished to more finished states

4	Transport, moving goods from one place to another

5	Capital upgrade or maintenance, moving capital from one state to another

Figure 27-a displays a typical model of a production process using scalar variables. In Figure 27-b the same model is presented using vectors. The Production variable has one element less than Goods (observe the exclamation marks on the flows). Note that the structure of the array version will be unchanged, even if the number of production phases should be changed.

a) State transitions using scalar variables	b) State transitions using vectors
Figure 27: State transitions using scalars and vectors

The structure in Figure 27-b may also be used to model a N-th order material delay, if separate inflows and outflows are added. The DELAYMTR function is normally used to express material delays, but if the contents of the levels implicitly defined by the DELAYMTR function need to be accessed, an explicit structure like the one in Figure 28 may be used.

a) Diagram of material delay structure	b) Associated equations
	level InTransit(p=RPhases) = 0 +dt*(Input        |p = FIRST(p);0) +dt*(Progress(p-1)|p > FIRST(p);0) -dt*(Progress(p)  |p < LAST(p) ;0) -dt*(Output       |p = LAST(p) ;0) aux Input = PULSE(5, 5, 0) aux Output = Progress(LAST(RPhases)) aux Progress(RPhases) = InTransit/ (DelayTime/COUNT(RPhases)) const DelayTime = 10
Figure 28: Material delay structure using vectors

State information

If a system goes through discrete states, this may sometimes be modeled using a vector with the same number of elements as there are system states. Each time the system state changes, the elements of the state vector are shifted cyclically, using the SHIFTCIF function.

As an example, think of a process that may be in one of three distinct states; StateA, StateB, and StateC. Assume also that a variable NewState will be set to true whenever the system is going to be switched to the next state. Furthermore, assume that state transitions are cyclic, i.e., that StateA follows StateC.

a) Diagram of state transition	b) Associated equations
	range RState = StateA, StateB, StateC aux ChangeState = SHIFTCIF(NewState, State)  const State(RState) = [1,0,0] aux NewState = ... "Some boolean expression"
Figure 29: Discrete system states

Observe how the system states are defined as elements of an enumeration range. Initially the first state of the State vector is true (1), and the others false (0). Whenever NewState is true, the r.h.s. of the ChangeState definition will shift the elements of State one position to the right, changing the state from [1, 0, 0] to [0, 1, 0] the first time, and to [0, 0, 1] the second time, and to [1, 0, 0] the third time, etc.

Testing for a given state may be done using the following expressions:

State(StateA)  will be true whenever the system is in the first state

State(StateB)  will be true whenever the system is in the second state

State(StateC)  will be true whenever the system is in the third state

Object attributes

A modeler is sometimes interested in keeping track, not only on the number of objects, but also certain object attributes or properties. As an example, we may be working on a production model, where products have attributes like lifetime, functionality, price, etc.

In Figure 30 the scalar and array version of the attribute part of a model is presented. In Figure 30-b a range RAttribute is defined like this:

range	RAttribute = EPrice, EFunctionality, ELifetime, EInventory

The price of our product may will be available as Product(EPrice). The other attributes are accessed correspondingly.

The significance of this solution is that all attributes are moved along when the object (here product) flows through the system or is accessed via links. Addition of more attributes may be done without changing the structure of the model.

a) Separate variables for each attribute	b) Attributes aggregated in variable dimension
Figure 30: Separate and aggregate attributes

History of values

As a final example of how arrays may be useful to the modeler, let us look at the problem of keeping track of previous values of variables. Let us assume that we are making an economic model, and that we want to keep track of the income for the recent 12 months.

Structure for remembering values	Associated equations
	level MonthlyIncome(i=1..12) = 0 +dt*(Income WHEN i=1 BUT 0) aux Income = ... "Income rate" aux NewMonth = TIMECYCLE(1, 1) aux SaveIncome = SHIFTLIF(NewMonth, MonthlyIncome)
Figure 31: Model for remembering values

This model accumulates Income in the first element of the MonthlyIncome vector, which has 12 elements. Every month the elements of MonthlyIncome are shifted one position, and the first element is cleared (all this is done by the SHIFTLIF function).

Main differences between arrays in DYNAMO and Powersim

In DYNAMO index variables and ranges are combined into FOR variables. Each dimension of a variable must be defined in a separate statement. Powersims introduction of guards and constrained expressions makes it always possible to define a multi-dimensional variable in a single statement. This is important when working in a graphical environment, and also removes redundancy from the language. DYNAMO does not have array literals, and multi-dimensional array constants must be defined one dimension at the time. DYNAMO does not have functions returning arrays.

Adding arrays to scalar models

The normal way of constructing an array model, is by first making and testing a scalar version of the model. Then a set of ranges are defined, and selected variables are given dimensions based on the defined ranges. Powersim has been designed to make the transition from scalar models to array structures as smooth and easy as possible. Most scalar equations will be accepted without change also after changing a variable to an array. This is achieved through generation of default flow definitions and implicit definition of array subscripts.

Experiences from applications

The array features of Powersim have been used with success in several large-scale projects (Powersim 1993). Many modeling problems are not practically solvable without using arrays. Even models that are solvable using only scalars, sometimes become much easier to develop, explain and maintain when using arrays. In conclusion, the family of simulation problems that are best solved using a system dynamics tool has been extended a great deal through Powersim's array mechanism.


Creating Multi-User Network Simulation Games in Powersim
Creating Multi-User Network Simulation Games

  Introduction to Network Games

  Files used by the network game object

  Phases of the game

  Asymmetric games

  Symmetric games

  Sources of decisions

  Determining decision source from special model variables

  Defining decision variables of an asymmetric game

  Defining decision variables of a symmetric game

  Setting up the game on each computer

  Running a Network Game

  Replaying a previous game

  Creating Different Interfaces of a Game

  The Stock Market Game

  Building the stock market model

  Building the user interface

  Defining the network game object

  Running the game

  Protecting the game

  Setting up a game in a network

  Testing a network game set-up

  The Beer Distribution Game


Introduction to network games

Group simulations

A network game is a group simulation and requires a network with personal computers (PCs) connected to a central server. The server is used to store common files. All PCs must have access to the same network drive on the server.

Up to ten players

Up to ten players may participate in the simulation at the same time.

Hint	It is possible to have several games, each with up to ten players, running concurrently, given that the player files (PSS) and game files (PSN) are set up correctly. See below.

Observers

In addition, an unlimited number of observers may be connected to the game. The game administrator will typically act as an observer to the game.

Synchronization and transfer of data

Each player runs his own version of the simulation model. The simulators are synchronized by the network game object, and data is transferred in order to ensure that each simulator produces the same result as on the other computers in the game.

Very limited amounts of data need to be transferred via the network in order to keep the simulators in the same state. As illustrated in the figure below, a simulation is defined entirely in terms of the simulation model (structure), the initial state of the simulator, and the external events influencing the state of the simulation.

Initialization

Since all players use the same simulation model, the structure and the initial state of the game will be the same for all players. Additional initializations may be specified by the game administrator (see Edit Game File dialog box). Such initializations will be communicated to each game by the network game object on simulation start-up, ensuring equal initial state of all participating simulation games.

Decisions

Decisions made by the players are the external factors influencing the models. Such factors will be broadcasted to all participating games, and used to modify the model states at synchronized points in the simulation. Players control the simulation by modifying values of model variables through the use of input objects.

One of the main tasks of the network game object is to initialize all the games with the same values, and then to communicate user decisions to all participating games at given points in time during the simulations.

Two simulation modes - strategic and operational

The user can choose between two simulator modes during a simulation: strategic and operational mode. A check box of the Define Network Game dialog box determines if the strategic mode will be available to the player of the game.


Files used by the network game object

Each model participating in a network game, must have a network game object. The network game objects communicate using shared files, which must reside in a common disk, i.e., on a network drive. There are three categories of files shared among network game objects:

Player Files (*.PSN - Powersim Node)

Game Files (*.PSS - Powersim Server)

Decision Files (*.TXT)

See also

Player Files

Game Files

Decision Files


Player files

Each game must have a network game object referring to a local player file (extension PSN for Powersim Node). The player file lists the different game set-ups that are available to this player, along with the associated player numbers.


Game files

The purpose of a game file is to define a mode in which the game can be played, for example, one player against the computer, three players against each other, etc.

Game files should be shared by all participating games (the files should be located at the shared network disk drive). By convention, game files have the extension PSS (Powersim Server). The game file contains the following information:

•	Descriptive name of game set-up

•	List of decision variables that the users may set to control the game

•	Initialization of parameters to the game

•	Decision period, i.e., simulation time between points where decisions may take place

•	Number of players participating in the game

•	List of players that will be simulated by the model

•	Name of files where decisions are stored when running the game

Each player file must refer to one or more game files. When the game starts, the user is asked to select from the list of game set-ups. The purpose of each game set-up is to define a mode in which the game can be played, for example, one player against the computer, three players against each other, etc.


Decision files

Each player's decisions are stored in a separate file on the common network drive (extension TXT). The decisions files contain columns of text in the following format:

Time	Variable name	Variable name	...
t1	v11	v21
t2	v12	v22	...
...	...	...	...
The figure below displays the files involved in a network simulation:

The game administrator and any other observers to the game have player number 0, and do not have associated decision files.


Phases of the game (Network Game)
Phases of the game

The network game object is designed to support simulations where the players of the game cyclically enter a planning phase, followed by an operational phase:

When the model (SIM file) is loaded, the associated player file (PSN) is processed, and a game file (PSS) selected. This also defines the decision file (TXT) for the player.

The game file (PSS) determines how often the game will pause in order to let the players make decisions. When all players have made their decisions up to a given point in time, the simulators automatically start running until the time for the next decision. The process may be described like this:

Note	Before a game starts, all decision files used by the game should be deleted (by the game administrator).


Asymmetric games

In an asymmetric game all players play different roles. The user interfaces used by different players should therefore be different. This is easily done by putting the user interfaces into separate models. The simulation itself should be put in a co-model which is shared by the different user interface models (main models). See figure below:

At a more detailed level, assume that the shared co-model has the following variables (among other variables):

Variable	Description
FactoryDesiredProduction	Factory's desired production
DistributorOrders	Distributor's orders for goods from the factory
WholesalerOrders	Wholesaler's orders for goods from the distributor
RetailerOrders	Retailer's orders for goods from the wholesaler
It is natural to use slider/bar objects to control each of the above variables. In the factory model, for example, a slider can be created and connected to the variable PRODLINE.FactoryDesiredProduction, where PRODLINE is the name of the (shared) co-model. This relationship is displayed below:

Similarly, a slider in the DISTR model can be connected to the variable PRODLINE.DistributorOrders; a slider in the WHOLE model can be connected to PRODLINE.WholesalerOrders; and a slider in RETAIL can be connected to PRODLINE.RetailerOrders.


Symmetric games

In a symmetric game all players give the same kind of input, and receive the same sort of output from the system. It is therefore possible to use the same user interface for all players.

In order for this to work, the symmetric part of the model must be modeled using vectors. Each player control its own element of the vector variables of the shared model. As a convention, we suggest that a symmetric network game model contains a numeric subrange named PlayerRange. The definition below is taken from the equations view of Powersim, and displays a PlayerRange with four players:

range	PlayerRange = 1..4

The range of players must start with 1 (one) and have a maximum of 10 (ten) elements.

As in the asymmetric case, the user interface may be put in a separate (main) model. (It is also possible to combine model and user interface in the same model. This is, however, a less flexible solution.)

Assume that we are making a game where several distributors are competing. One decision that a distributor would make is to determine the ordering rate for incoming goods. This variable should be defined as a vector with elements of the PlayerRange, like this:

const	Orders(PlayerRange) = 0

When playing a game, each player is running its own copy of the simulation model defining the game. Each player has a unique player number, which is defined in the player file (PSN). In the symmetric case, the network game object automatically maps each player to the first element of the PlayerRange of that player's simulation model. This means that all values concerning the current player are accessed as element number 1 (one) of the player vector variables. As an example, a slider for setting the value of the current player's ordering rate should be connected to the array element Orders(1).

In other words, when making a symmetric game, all dynamic objects concerning the current player should be connected to element 1 (one) of the model variables.


Sources of decisions (Network Game)
Sources of decisions

Decisions may come from five different sources during a simulation; the player (all modes), the competitors (operational mode), the simulation model (simulated players), or assumptions about competitors (strategic mode). If fewer players participate than the maximum number of players, dummy decisions of non-participating players must be provided. These decisions should ensure that non-participating players do not influence the course of the game in any way.


Determining decision source from special model variables (Network Game)
Determining decision source from special model variables

As an example, let us look at a game where the players are going to control a variable called Price.

  Defining decision variables of an asymmetric game

  Defining decision variables of a symmetric game


Defining decision variables of an asymmetric game

If we are making an asymmetric game, the definition of Price should look like this:

aux	Price = SELECTDECISION(PLAYERNUMBER, Price_Decided, Price_Assumed, Price_Simulated, Price_Dummy)

The parameters to SELECTDECISION are:

PLAYERNUMBER	Number of this player
Price_Decided	Price determined by player
Price_Assumed	Price assumed by other player
Price_Simulated	Price determined by model
Price_Dummy	Price if player is not participating
If the game does not support strategic mode Price_Assumed may be set to any value. If the game always is set up to include all players Price_Dummy may be set to any value.


Defining decision variables of a symmetric game

In the symmetric case all decision variables should be vectors with elements from one and up. As explained above, it is convenient to define a named range for the player dimension. Below we have defined a PlayerRange with room for four players.

range PlayerRange = 1..4

Now, the definition of Price can be expressed like this:

aux Price(p=PlayerRange) = SELECTDECISION(INDEX(p), Price_Decided(p), Price_Assumed(p), Price_Simulated(p), Price_Dummy)

The parameters to SELECTDECISION are:

INDEX(p)	Local player number, P
Price_Decided(p)	Price determined local player P
Price_Assumed(p)	Price assumed by this player about local player P
Price_Simulated(p)	Price determined by model for player P
Price_Dummy	Price of non-participating player
Price_Decided, Price_Assumed, and Price_Simulated should be vectors with elements defined by PlayerRange (i.e., the same dimensions as Price).

The current player always is local player number 1 (one). The relationship between local (L) player numbers (used by the model) and global (G) player numbers (displayed in the title line of the game control panel) is the following:

L = (G - PLAYERNUMBER + GETTOTPLAYERS) MOD GETTOTPLAYERS + 1

G = (L + PLAYERNUMBER - 1) MOD GETTOTPLAYERS

SELECTDECISION will return the following values in the different modes:

Player / Mode	Operational	Strategic
This Player	Price_Decided	Price_Decided
Competitors	Price_Decided	Price_Assumed
Simulated Competitors	Price_Simulated	Price_Assumed
Non-participating players	Price_Dummy	Price_Dummy


Setting up the game on each computer (Network Game)
Setting up the game on each computer

A game may be tested to some extent by simulating one player against the computer. As this involves only one computer, there is no need to access a shared disk drive, or to have access to more than one computer.

When more than one player is going to participate in the game, the simulation model (SIM file) and the player file (PSN file) should be copied to each of the computers that participate in the simulation. One important change must be made to the PSN files, as each player must have a unique number. The changes may be made either by editing the PSN files (for example using NOTEPAD), or by using the Edit Player File dialog box of the network game object in each of the simulation models. If you are using a text editor, like NOTEPAD, you should look for the File<n> entries of the [GameFiles] section of the PSN file. An example is given below:

[GameFiles]

File1=2,C:\PROJECT\POWERSIM\DEMOS\BEER_WHO.PSS

The number following the equal sign determines the player number (here 2). (The text following the comma determines the name of the game file.)


Running a network game

To run a network game

1	Open a model containing a network game object. The "Select game to be played" dialog box is then opened. You are asked to select from the list of game set-ups defined by the player file (PSN file) of the network game object.

2	Start the game by pressing the Run button. When the simulation is started, the network game object pauses the simulation after model initialization, and displays the Game Control dialog box to the user.

3	As a player, you may now make decisions in the game. Decisions may be tested along with assumptions about competitors by pressing the Try Decisions button. Several decision periods may be tested by making decisions and assumptions and pressing Try Decisions again.

4	You may use the Revert to Game button to reset the simulation to the current time and state. Here a new set of decisions may be tested, or the current set of decisions may be accepted.

5	When Accept Decisions is pressed, the game will wait for all the other players to make (and accept) their decisions, and continue simulation to the next decision period.


Replaying a previous game (Network Game)
Replaying a previous game

By starting the simulator as player number 0 (observer) and a set of decision files already present, the simulator will run according to the previously stored decisions. This may, for example, be used in a debriefing session.

It is also possible to restart a game that has been stopped, for example, because of a mistake. When restarted, the simulator will ask if you want to re-join an earlier run, if a decision file already exists. If you answer Yes to this question, any previous decisions you've made will be repeated, and you can continue to make decisions after the last decision already present in the decision file (TXT) on the server.


Creating Different Interfaces of a Game (Network Game)
Creating different interfaces of a game

Sometimes we would like to make several language versions of a game. It may also be an idea to make a game administrator's version. In these versions we may let the user view all decisions made by the players, and comparative graphs and tables may be presented.

All this may be achieved by designing the network game as a two-layered system with a main model defining the user interface and a co-model containing the actual simulation. The figure below displays a game (Model) with three different user interfaces; a German end-user interface, an English end-user interface, and a separate interface for the game administrator.

This arrangement also has the advantage that the simulation model itself may be fully developed and tested without having to deal with the end-user interface of the model.


Stock Market Game - Example of symmetric network game
The Stock Market Game

This is a game where players can buy and sell shares. The price of the shares varies over time. The goal is to buy and sell at the correct time, in order to increase our assets (cash plus value of owned shares).

The Stock Market Game is a symmetric game. We therefore define a numeric subrange PlayerRange with elements from 1 to the maximum number of players, say 4. Use the Edit Define Range dialog box to define the PlayerRange.

range	PlayerRange = 1..4

See

  Building the stock market model

  Basic Structure

  Selecting Decision Variables

  Simulated Decisions

  Assumptions To Be Used In Strategic Mode

  Development In The Stock Price

  Scores

  The Complete Stock Market Model

  Building the user interface

  The User Windows

  Creating a player file

  Creating the Buying and Selling window

  Creating the Stock Market window

  Creating the Developing Strategies window

  Defining the network game object

  Running the game

  Protecting the game

  Setting up a game in a network

  Testing a network game set-up


Building the stock market model

  Basic Structure

  Selecting Decision Variables

  Simulated Decisions

  Assumptions To Be Used In Strategic Mode

  Development In The Stock Price

  Scores

  The Complete Stock Market Model


Basic structure

The diagram below displays the basic structure of the game.

The level of Cash is influenced by the selling and buying of shares. Selling shares means that we get a cash in flow equal to the number of shares sold times the price (value) of each share.

1	Double click on Cash_In to define the variable.

2	Enter PlayerRange in the Dimensions field and ValueOfShares*Sell in the Definition field.

Note	The equations below are taken from the Equations view.

dim	Cash_In = (PlayerRange)

aux	Cash_In = ValueOfShares*Sell

3	Buying shares means that we must spend an amount of cash equal to the number of shares times the price (value) of each share. Double click in Cash_Out and enter the definition below:

dim	Cash_Out = (PlayerRange)

aux	Cash_Out = ValueOfShares*Buy

4	Liquidity (available cash) restricts buying in the sense that we cannot buy more shares than we are able to pay for. The variable Buy_Max defines the maximum number of shares that we can afford to buy. It is defined like this:

dim	Buy_Max = (PlayerRange)

aux	Buy_Max = FLOOR(Cash/ValueOfShares)

We assume that it is impossible to buy partial shares. This is ensured by the FLOOR function, which is used to get the integral part of Cash / ValueOfShares.

5	The initial number of shares can be set to zero. The flows in and out of Shares are created by default, as can be seen from the equations below.

dim	Shares = (PlayerRange)

init	Shares = 0 { ShareUnits }

flow	Shares = -dt*Sell +dt*Buy

6	The amount of money is initialized to 100 currency units. The flows are created automatically.

dim	Cash = (PlayerRange)

init	Cash = 100 { CurrencyUnits }

flow	Cash = -dt*Cash_Out +dt*Cash_In


Selecting decision variables

The decisions in the game are centered around buying and selling. As described in Sources of decisions decisions may come from different sources; a player, a player's assumption about a competitor, or the simulation model. We therefore create three decision variables for buying and three for selling, like this:

1	The function SELECTDECISION is used in the definition of Sell and Buy. The definition of Sell becomes:

dim	Sell = (p=PlayerRange)

aux	Sell = MIN(Shares, SELECTDECISION(INDEX(p), Sell_Decided, Sell_Assumed, Sell_Simulated, 0))

unit	Sell = Share/Month

The MIN function ensures that we do not sell more shares than we own. This index variable P is used to determine the player number of each element of the Sell vector when calling SELECTDECISION.

2	In a similar fashion Buy is defined:

dim	Buy = (p=PlayerRange)

aux	Buy = MIN(Buy_Max, SELECTDECISION(INDEX(p), Buy_Decided, Buy_Assumed, Buy_Simulated, 0))

unit	Buy = Share/Month

Here the MIN function is used to avoid buying more shares than we can pay for.


Simulated decisions

When the computer is acting as decision maker in a game, we have to model the decision making process that leads to the buying or selling of shares. In this simple example we base these decisions on the current value of the shares and the trend in the price, as depicted below:

1	We buy shares if the value is not too high and the price is growing. In the equations below we buy only if the shares are less expensive than 0.9 currency units. We also buy only if the trend is positive.

dim	Buy_Simulated = (PlayerRange)

aux	Buy_Simulated = IF((TrendValueOfShares>0) AND (ValueOfShares<0.9), 10, 0)

unit	Buy_Simulated = Share/Month

2	Selling is done if the value is greater than 1 and the price is falling, or if the value of the shares is very high (greater than 1.5).

dim	Sell_Simulated = (PlayerRange)

aux	Sell_Simulated = IF((TrendValueOfShares < 0) AND (ValueOfShares > 1) OR - Logical Or (ValueOfShares > 1.5), 20, 0)

unit	Sell_Simulated = Share/Month

Note	Buy_Simulated and Sell_Simulated only serve as simple illustrations of how decisions may be based on current and past values of model variables.

3	The trend in price change is picked up by the TrendValueOfShares variable, defined next:

dim	TrendValueOfShares = (PlayerRange)

aux	TrendValueOfShares = TREND(ValueOfShares, 2, ValueOfShares)

unit	TrendValueOfShares = Currency/Share/Month


Assumptions to be used in strategic mode

When the user presses Try Decisions, he will use assumptions about the development in price when testing out strategies. (The real price is not available in a planning session.)

1	We use the STRATEGICMODE function to select between the user's assumption and the real stock market price.

aux	ValueOfShares = IF(STRATEGICMODE, ValueOfShares_Assumed, ValueOfShares_Real)

2	The assumed price can be initialized to one:

const	ValueOfShares_Assumed = 1

3	If you want the model to set the assumed price equal to the real price during the operational mode, this can be done using the ASSIGN function. This makes it easier for the players to find a good starting point for the stock price when entering the strategic mode.

aux	SetVOS = IF(NOT STRATEGICMODE, ASSIGN(ValueOfShares_Assumed, ValueOfShares_Real), 0)


Development in the stock price

1	In this example, the real development in stock price is determined using a GRAPH function with TIME as the independent variable.

aux	ValueOfShares_Real = GRAPH(TIME,0,5,[1,1.37,0.18,0.27,0.46,0.97,1.55,1.98,0.51,0.32,1"Min:0;Max:2"])

The players' decisions will not influence the stock price during the game (which is also the case with small players in the market).


Scores

The total assets of each player is used to determine the scores in the game.

1	Assets are defined as cash plus number of shares times current value of each share.

dim	Assets = (PlayerRange)

aux	Assets = Cash + Shares * ValueOfShares

unit	Assets = Currency

2	The current players' assets over the average assets of the competitors is used as the score.

dim	Score = (p=PlayerRange)

aux	Score = Assets DIVZ0 SUM(q=PlayerRange; IF((INDEX(q) <> INDEX(p)) AND (INDEX(q) <= GETTOTPLAYERS), Assets(q), 0) DIVZ1 (GETTOTPLAYERS-1))

The DIVZ0 and DIVZ1 functions are used to handle divide-by-zero conditions. The SUM function is used to add together the assets of the competitors. The index variable P indexes the Score vector, while Q indexes the Assets vector. The IF function is used to return the assets of player Q, or zero if Q = P or Q is greater than the number of participating players.


The complete stock market model

If we put together the pieces above we get a model of players buying and selling shares. The model is available as the file SHARES.SIM that comes with Powersim.


Making The User Interface Of The Stock Market Model
Building the user interface

We are now ready to make the game interface that will be used by the players. This is best done using SHARES.SIM as a co-model, and create a new (main) model where the interface is defined.

We plan to make the following windows that the player can use when running the game:

•	Buying and Selling - Used to buy and sell shares

•	Stock Market - Displays the stock price development

•	Developing Strategies - Used to test strategies

Note	If you want to do the following as an exercise, we suggest that you copy the original SHARES.SIM to a new directory and store all files belonging to the exercise in this directory.

  Creating a player file

  Creating the Buying and Selling window

  Creating the Stock Market window

  Creating the Developing Strategies window


Creating a player file

1	Create a new document using the menu command File New in Powersim.

2	Add SHARES.SIM as a co-model of the newly created model.

3	Choose Simulate Simulation Setup.

4	Open the Co-models part of the Simulation Setup dialog box, and press the Add button.

5	Select SHARES.SIM and press OK in the file browser that is opened from Add.

6	Close Simulation Setup and store your model in the file SHARESPL.SIM (which stands for SHARES PLayer).

Note	This file is also present on the distributed disks.


Creating the Buying and Selling window

To create the window

1	From the Windows menu select New Window.

2	In the newly created window, enter the objects displayed below. Counting from left to right, the top row contains a slider/bar object (Buy) a number object (Shares) and a slider/bar object (Sell). The arrows below Buy and Sell are line objects. The four objects at the bottom are all number objects.

  To define the contents of the Buying and Selling window

  To customize the Buying and Selling window


To define the contents of the Buying and Selling window

1	Define The Buy slider/bar object by double-clicking on it and setting the following attributes:

•	Parameters - SHARES.Buy_Secided(1). First select Shares in the Models combo box; then select Buy_Decided(1) in the Variables list box; and press Add.

•	On Pause - Should be switched on in order to avoid changes to Buy_Decided except when the game is paused, waiting for user input.

•	Label Position - Top

•	Orientation - Horizontal

•	Present - On

•	Alignment - Right

•	Field Width - 10

•	Label - To specify the Buy label, select SHARES.Buy_Decided(1) in the Parameters list and press Label. Type Buy in the text field of the Bar Label dialog box.

•	Axis - Select SHARES.Buy_Decided(1) in the Parameters list and press the Axis button and type in 0 as Minimum and 100 as Maximum of the Bar Axis and Scale dialog box. Set Position to None. Press Line and set Style to None.

•	Background - Press this button and set both Style and Pattern to None.

2	Define the number object Shares by double-clicking on it and setting the following:

•	Model - SHARES

•	Parameter - SHARES .Shares(1)

•	Alignment - Center

•	Field Width - 10

•	Label Position - Top

•	Label - Click on this button and type Shares in the Text box of the Number Label dialog box. In the same dialog press Layout, and select centered alignment.

3	Define the Sell slider in a similar way as Buy, except that Sell_Decided(1) is used instead of Buy_Decided.

4	Define the Score number object in the same manner as Shares, except that the parameter should be SHARES.Score(1).

5	Input should not be allowed. Clear Allow Input Always and On Pause.

6	The Assets number object is defined like Score, except that the parameter should be SHARES.Assets(1).

7	The Cash number object is defined like Score, except that the parameter should be SHARES.Cash(1).

8	The Value per Share number object is defined like Score, except that the parameter should be SHARES.ValueOfShares.


To customize the Buying and Selling window

1	Scroll the window in order to position the Buy object in the upper left hand corner of the window.

2	Open Format Options [image] to set the window attributes of the window.

3	Select Window Attributes in the Category list of the Options dialog box, and set the following:

•	Sizing Frame - On

•	Minimize Box - On

•	Horz. Scrollbar - Off

•	Vert. Scrollbar - Off

•	Caption - Buying and Selling

4	Press OK

5	Size the window to enclose the desired objects, for example, like this:

6	To remove the sizing frame, open the Format Options [image] again and switch off Sizing Frame.


Creating the Stock Market window

Note	This part need not be completed in order to run the example. You may skip to Defining the Network Game Object.

The Stock Market window will contain the following graph:

To create the Stock Market window

1	From the Simulate Simulation Setup dialog box select Main in the Parallel Simulation list, and then press Open. A new window into the Main model is created.

2	Close the Simulation Setup and scroll the window so the contents of the Buying and Selling window is scrolled out of view.

3	Create a time graph object and define it like this:

4	Parameters - Enter SHARES.ValueOfShares into this list.

5	Value (Y) Axis: Axis - Press this button to open the Value (Y) Axis dialog box.

6	Press Label and type in the text Value of one Share.

7	Position the time graph object in the upper left hand corner of the window.

8	Size the window to enclose the graph.

9	Open the Format Options Window Attributes dialog box, and set the following attributes.

•	Sizing Frame - Off

•	Minimize Box - On

•	Horz. Scrollbar - Off

•	Vert. Scrollbar - Off

•	Caption - Stock Market

10	Press OK

11	You have now made the second window into our game.


Creating the Developing Strategies window

Note	This part need not be completed in order to run the example. You may skip to Defining the Network Game Object.

Before trying out decisions, you have to make certain assumptions about competitors and future the stock price.

To create the Developing Strategies window

1	From the Simulate Simulation Setup dialog box select Main in the Parallel Simulation list, and then press Open. A new window into the Main model is created.

2	Close the Simulation Setup and scroll the window so the contents of the Buying and Selling window and the Stock Market window is scrolled out of view.

3	Create the following objects in the new window:

4	The Assumptions about competitors box is a text object, enclosing two smaller text objects, Buying and Selling. Inside Buying you make three number objects without labels. The parameters are SHARES.Buy_Assumed(2), SHARES.Buy_Assumed(3), and SHARES.Buy_Assumed(4).

5	Inside the Selling text box you make three similar number object, with parameters SHARES.Sell_Assumed(2), SHARES.Sell_Assumed(3), and SHARES.Sell_Assumed(4).

Hint	You will save time if you make one of the objects first (for example the SHARES.Buy_Assumed(2) object), and than use copy/paste to make the rest of the objects. Finally you change the parameters of the pasted objects.

6	The object to the right in the above figure is a number object. You set the parameter to SHARES.ValueOfShares_Assumed.

7	Position the objects and size the window to enclose the desired parts.

8	Open the Format Options Window Attributes dialog box, and set the attributes as described for Market Share (above).


Defining the network game object

In the previous topics we defined the game model and user interface. Now we will create the network game object for setting up the game.

To define the network game object

1	Create a network object in the main model (SHARESPL.SIM).

2	Position the object outside the parts displayed in any of the windows we created above (see Making the user interface of the stock market model).

3	Double-click on the network object to open the Define Network Game dialog box.

4	Type SHAREPL.PSN in the Name field.

5	Click the Edit File button to open the Edit Player File dialog box.

6	Press the Add button to open the Game File and Player Number dialog box.

7	Enter SHARE.PSS in the Name field and 1 in the Player field.

8	Click the Edit File button to open the Edit Game File dialog box.

9	Let us make a game file where one player plays against the computer. In the Name of Game field enter the text "Play against computer".

10	Since this is a symmetric game, turn on Symmetric.

11	We have prepared the model for strategic mode, so we should also switch on Strategic.

12	In the Player/Decision Parameter group we use the Add button to determine decision parameters.

13	Enter SHARES.Buy_Decided(%d) in the Player/Decision Parameter field. Since this is a symmetric game there is only one option in the Player list.

14	Press OK.

15	Use the Add button again, this time entering SHARES.Sell_Decided(%d) in the Player/Decision Parameter field.

16	Enter 1 as the decision Period. This means that the game will pause every time unit (simulated Month) to allow players to make decisions (and test out strategies).

17	You specify the names of decision files by entering a file name (with a %d in it) in the Decision Files Mask field.

18	Set the number of players to two (one player and the computer).

19	Press the Set button.

20	Switch on the second check mark of the Simulated list box, telling the system that the first player is played by a person, while the second is played by the computer.

21	You may now press OK in all open dialog boxes, and save your work before you run the game.


Running the game

To run the game

1	Click Run [image] to start the game. The Game Control panel will be presented.

2	You may move it out of your way (for example into the lower right hand corner of the display) while you look at the other windows of the game.

3	Open the Buying and Selling window. You have no shares and 100 currency units. The current price of one share is 1.07 currency units.

4	Do you want to buy shares? If so, just use the Buy slider bar or click in the number box below.

5	Press Accept Decisions when you have made up your mind. The simulation continues until the next month, where the Game Control panel is presented again.

6	Open the Stock Market window to see that the Prices are rising.

7	Do you want to buy or sell? If so, use the Buying and Selling window. Press Accept Decisions when done.

To test out strategies

1	Open the Developing Strategies window. Since only one competitor is currently active (the computer), only the topmost numbers of the Buying and Selling groups are in use.

2	Here you may type in how many shares you expect your competitor to buy or sell. You may also enter the expected stock price.

3	Then press the Try Decisions button.

4	The simulation will now go on for another month, and you will have the option to continue trying decisions for another month, or revert to the game.

5	If you press the Revert to Game button, the simulation is set back to the point where you first pressed Try Decisions. If you answer Yes to the question "Keep current decisions?", the values currently entered in the Buying and Selling dialog box will be kept until the Game Control panel is presented again. You will now be allowed to try out another set of assumptions, or you may accept a set of decisions for the next period.


Protecting The Game

You may protect your game to avoid changes to the model (including accidental closing of windows), or from inspection by users.

To protect a game from changes

1	Open File Properties Access

2	Switch off the Edit check mark. You may also assign a password to the change of attributes.

To protect a game from inspection

1	Save the model with a protection password. (See File Save As.)

Hint	You should also consider distributing your game with the run-time version of Powersim, which does not allow for modification of models, and also has a simpler interface.


Setting up a game in a network

In Defining the network game object we created a network game object and set up a simulation where one user played against the computer. Below we will look at how the game may be set up as a competition between two human players running the game on different computers in a network.

To set up a game in a network

1	We start out with the SHARESPL.SIM model. Open the model and use the Simulate Simulation Setup dialog box.

2	Click on Open to create a new window into Main and click OK to close Simulation Setup.

3	Locate the network game object inside the new window and double click on the object. This brings up the Define Network Game dialog box.

4	Press the Edit File button in order to edit the player file SHAREPL.PSN.

5	Since we want to make another game set-up, we use the Add button to open the Game File and Player Number dialog box.

6	The game file of a network simulation should reside in a shared drive. In our example, G: is a shared disk drive, with a directory named TMP. We create a game setup named SHARECOMP.PSS (SHARES COMPETING) here.

7	Type 1 as the player number.

8	Press the Edit File button to edit the game file.

9	We may now enter the game setup from scratch, or we may start out from the setup we defined earlier using the Import feature of Edit Game File. Press the Import button and select the file SHARES.PSS.

10	Change the contents of the Edit Game File dialog box as the following.

11	Type "Compete against one player" in the Name of Game field.

12	Put the decision files on a shared directory by editing the Decision Files Mask. In our example "G:\TMP\SHARES%d.TXT" is used.

13	Remove any check marks in the Simulated list.

14	Close all open dialog boxes by means of their OK buttons. When the Select game to be played dialog box appears, observe that there are two alternatives available, as displayed below.

15	You should select "Compete against one player" and press OK.

16	Now the game has been set up for one computer. Save the model SHARESPL.SIM and copy it along with SHARE.SIM and SHAREPL.PSN to the second computer that is going to participate in the game.

17	On this second computer, open Powersim and load SHARESPL.SIM.

18	Open the network game object.

19	Each player must have a unique PSN file. This is the reason why it should be put in a local directory. Press the Edit File button in order to edit the local player file SHAREPL.PSN.

20	We want to change the player number of the second game setup from 1 to 2. Select the second entry in the Player/Game Set-up File list and press the Edit button. (You may also double click on the entry.)

21	Type 2 in the Player field.

22	You can now close all open dialog boxes using their OK buttons. In the Select game to be played dialog box you should pick the entry "Compete against one player" before pressing OK.

The game is now ready to be played, as described in Running the game. (Save the model SHARESPL.SIM first.)

Note	The simulation of a new period will start until both players have made their decisions (pressed the Accept Decisions button of the Game Control panel).


Testing a network game set-up

To test a network game set-up

1	Check presence of network game object. The model(s) participating in a network game must have exactly one network game object.

2	Check that player numbers are unique. Start the game on each computer and check that the Game Control panels contain different player numbers; for example, Player 1, Player 2, etc. If not, edit the Player File of one of the games, as described above.

3	Check that player files (extension PSN) are local. Each computer participating in a network game must have its own copy of the PSN file. If the player numbers of several players change after you have edited a player file, this means that you are using the same PSN file for several players. In that case you should copy the PSN file of each player to a local directory and edit each copy separately.

4	Check that each player is playing the same game. Start the game on each computer and press Accept Decisions in every game. If the simulation does not advance to the next decision period, check that every participating player uses the same game set-up. This is checked by closing and re-opening the model (for example, SHARESPL.SIM) or by opening and closing the Define Network Game object in all participating computers. Make sure you select the same game to be played on every computer (when the Select game to be played dialog box is presented).

5	Check that decision files (extension TXT) are placed in a shared directory. If the game will still not run, open the Edit Game File dialog box from one of the participating computers, and check that the Decision Files Mask refer to a shared directory. If it does not, fix it.

6	Check that all player files (extension PSN) refer to the same game file (extension PSS). If Decision Files Mask refer to a shared directory and the game will still not run, open the Edit Player File dialog box of every player and check that all player files refer to the same PSS file for the game set-up that is being played. (The PSS file should reside in a shared directory, available to both computers.)

7	Check access rights to files and directories when setting up the game. Access rights to files and directories vary among file systems and networks. See your local network administrator for assistance if you don't know the security system of the network you are using, or if you do not have the authorization to set up the necessary access rights.

The user setting up the game must have read/write access to the PSS and PSN files and read/write access to the directory where these files are stored. (Read/write access to a directory includes the rights to create files, delete files, list files, and make the directory current.)

8	Check access rights to files and directories when playing the game. If you still have problems, check that all participating users have read/write access to the shared directory where the decision files are stored, and that users have read/write access to files stored in the decision files directory. When playing the game, the users need read access to the PSS files and the PSN files.


Beer Distribution Game - Example of Asymmetric Network Game
Beer Distribution Game

The Beer Distribution Game is a classic system dynamics game. The Powersim version of it is an example of a symmetric network game. On the distributed disks you will find the model BEER.SIM, which is a co-model used by the following game interface models:

•	BEER_FAC.SIM - Player playing factory

•	BEER_WHO.SIM - Player playing wholesaler

•	BEER_RET.SIM - Player playing retailer

•	BEER_ADM.SIM - Game administrator

By first studying the you should be able to understand the operation of the BEER game as well, just by looking at the mentioned files.

The model BEER.SIM is also a good example of the use of arrays to represent symmetric structures. In this model the factory, the wholesaler and the retailer are represented as elements of array variables.

See also

  Stock Market Game


Objects

This topic contains formal descriptions of all Powersim object types and their related dialog boxes. Objects are divided into four sub-groups, listed below.

  Model Objects - Specifying a model's structure, namely variables, links, and flows

  Dynamic Objects - Presenting simulation results and adjusting model parameters

  Static Objects - Customizing simulators using text and graphics

  Transfer Objects - Exchanging information with other models, files, or applications

  Common Dialog Boxes - For  use by several object types


Model Objects

Model objects are used to specify a model's structure, that is, the variables and the links and flows that influence the variables. There are six model object types - levels, auxiliaries, constants, links, delayed links, and flows.

See also

  Variables, Links and Flows

  Define Variable dialog box

  Edit Graph/Vector dialog box


Variables, Links and Flows
Variables, Links, and Flows

The model objects found in Powersim models are shown below.

Object	Symbol	Button
Level
Auxiliary
Constant
Link
Delayed link
Flow
The first three object types are variables; the other three are used to connect and influence variables.

You can define several attributes of a variable in the Define Variable dialog box, including equation, unit of measure, textual documentation, and dimension (scalar or array). If a variable is selected when you choose Edit Define Object, the Define Variable dialog box opens.


Define Variable dialog box

Dialog box options

Variable

This drop-down list contains all variables in the model. The header shows the variable that is currently being defined. Each variable in the list is preceded by a symbol indicating whether it is a level, an auxiliary, or a constant. Undefined variables are labeled with a question mark. The question mark disappears once you define the variable.

•	To go straight to the first undefined variable in the list, type a question mark "?" from the keyboard.

•	To go to the first item in the list beginning with a letter, you can simply press that letter key.

Selected Only

Check this box to limit the Variables list (see above) to the variables currently selected in the diagram or in the equations listing.

Hint	Selected Only is useful when you work with large models, since the dialog box will open faster when a small number of variables are selected, and it is easier to locate desired variables in a smaller list.

Unit of Measure

Use this list to type or select a unit-of-measure expression for the current variable. Each variable in the model has a unit expression attached to it. The list contains all unit expressions used in the model.

Dimensions

Use this list to specify whether you want the current variable to be a scalar or an array.

•	To change a variable from a scalar to an array, enter a dimension definition.

•	To change a variable from an array to a scalar, remove the dimension definition. If the Dimension text box is empty, the current variable is considered a scalar.

Definition

This text box displays a mathematical definition of the current variable. You may type directly into the text box, insert numbers and special characters from the dialog box's built-in numeric keypad, or insert selections from the Linked Variables, Functions, Units, and Range Variables lists.

When the dialog box opens, Definition is selected by default; with all text selected as well. The text box breaks lines automatically.

•	To manually insert a line break, type Ctrl + Enter.

•	To move focus to the next control in the dialog box type Tab.

•	To insert tabulators in the definition, type Ctrl + Tab.

The mathematical definition of a level consists of two parts:

1	Initial, which defines the initial value of the level.

2	Flow, which defines how the variable is changed dynamically each simulation step.

Powersim automatically generates the flow part of the level definition based on the flows connected to the current level in the diagram.

Initial and Flow

If the current variable is a level, these radio buttons determine whether the Definition text box will display the initial definition or the flow definition of the level.

These buttons are visible only if the current variable is a level. When you choose Init, which is the default setting, you may edit the initial definition of the level. When you choose Flow, the Definition text box shows the flow part of the level definition. If no flows are connected to the current level, the Flow button is disabled.

Full View

Check this box if you want the definition to be displayed in full view. Then the Definition text box is expanded downward to allow you to read a large definition without having to scroll the text box.

Graph

Use this button to define graph functions and vectors. Hitting it will open the Edit Graph/Vector dialog box, which is a graphical editor for generating graph functions and vectors. If you close Edit Graph/Vector by clicking OK, the generated graph function or vector is inserted at the text marker (or replaces the selection) in the Definition text box.

Documentation

You may type a textual documentation of the current variable in this text box.

Hint	It is highly recommended that you take the time to enter a few lines of documentation for each variable, explaining its meaning and the logic behind its definition.

Linked Variables

This list contains all the variables that are linked to the current variable in the diagram. If the current variable is an auxiliary or a level, you can insert input variable names into the Definition or the Documentation text box by double-clicking in the list.

Note	Powersim requires that all linked variables appear in the definition of a variable. If you wish to exclude any of the input variables from the definition, you must delete the corresponding links in the diagram.

Functions

Double-click in this list to insert a function into the Definition or the Documentation text box. The function name is pasted with or without argument templates, depending on the setting of the Paste Function Arguments check box.

Function Group

The content of the Functions list is determined by the group selected in the Function Group list.

•	To see all standard functions in the Functions list, choose {All}.

Paste Function Arguments

Check this box if you want the function argument templates to be pasted along with the function name when you double-click on a name in the Functions list.

Ranges

Double-click in this list to insert a range or range element into Dimension or Definition (which must be selected first). To define new ranges, close Define Variable and open Define Range from the Edit menu.

Units

Double-click in this list to insert a predefined unit into the Unit of Measure text box (which must be selected first).

•	To define new units, close the Define Variable dialog box and choose Define Unit from the Edit menu.

Set

Use this button to confirm the current dimension, definition, documentation, and unit expression. If you try to confirm an invalid definition, Powersim will display an error message.

Locate

Use this button to scroll the current variable into the center of the diagram window.

Hint	Locate is useful if you wish to see the model structure surrounding the current variable. All you need to do is click on Locate and move the dialog box aside.

<Keypad>

Use the keypad buttons to enter numbers and special characters into the selected text box rather than typing them from the keyboard.

<Edit buttons>

The edit buttons are located at the bottom of the keypad. Use these buttons for clipboard access and for undoing typing, deleting, or pasting:

Button	Command	Shortcut
	Cut	Ctrl+X
	Copy	Ctrl+C
	Paste	Ctrl+V
	Undo	Ctrl+Z
Text is cut or copied from or pasted into the selected text box. The Paste button is disabled if no text is found on the clipboard. The Cut and Copy buttons are disabled if no text is selected.

More>>, Less<<

Use this button to expand or compress the dialog box.

See also

Working with the Define Variable Dialog box


Edit Graph/Vector
Edit Graph/Vector dialog box

This dialog box is a graphical editor for specifying Graph functions or literal vectors to be used in the definition of a variable.

Dialog box options

Coordinates

Use this list box to display the X and Y coordinates for each data point of the graph function.

The X column of the list is output only. The numbers are determined by the current settings of Points, X-Axis Step, and X-Axis Min.

If both X-Axis Step and X-Axis Min are literals, the values of the X column are a series, with Points elements of real numbers with a fixed interval equal to Step between them, starting at Min (that is, if Points = 4, Min = 0, and Step = 1, the X-Value numbers will be 0, 1, 2, 3).

If the Step and/or the Min arguments are defined as nonliterals (expressions) , the X column of Coordinates will contain a number of lines (equal to Points), saying Point #n, where n is the line number, starting at 1 (that is, if Points = 3, the X-Value lines will be Point #1, Point #2, Point #3).

The X and Y columns define a set of ordered pairs that are mapped to a curve in the graph box. This means that the curve is automatically updated when numbers in the Y column are altered, and vice versa.

When you open the dialog box, the contents of the Coordinates list (and the shape of the graph) are determined by the current selection in the Definition text box of the Define Variable dialog box. If nothing is selected, all Y-values are 0. A textual representation of the graph (a function call) will be inserted at the text marker when you push the OK button.

Example     GRAPH(CR,0.00,1.00,[1.05,1,0.9,0.7,0.6,0.55"Min:0;Max:1.5"])

Coordinates List in Vector Mode

The list contains index number (integer) and value for each vector element. The index list contains increasing numbers 1, 2, 3, ... The number of indices is determined by the setting in the Elements text box.

Y

You may enter Y-values directly by first selecting one or more lines in the Coordinates list and then typing a literal value into the Y text box.

Points

Use this group to determine the number of data points in the graph. In the text box you may type the desired number. Legal values range from 1 to 500.

Elements (Vector Mode)

When you select Vector in the Edit What list, the Points group changes its name to Elements. You may then use the text box to specify the number of elements in the vector.

Del

Use Del to delete selected lines in the Coordinates list, which represent data points or vector elements. If nothing is selected, the last data point in the list is deleted.

Ins

Use Ins to insert a data point in the Coordinates list. If nothing is selected, a data point is appended at the end.

X-Axis

Use this group to specify X-axis parameters for the graph function.

Min

Type the X argument of the graph function, that is, the lower boundary of the interval of X-values defined by the graph function. The default value is 0. You can specify it as either a literal or an expression.

Step

Type the Dx argument of the graph function, that is, the interval on the x-axis between each data point in the graph. The default value is 0.1. You can specify it as either a literal or an expression.

Y-Axis

Use this group to specify Y-axis parameters for the graph function.

Min, Max

Use these text boxes to define the scaling of the Y-axis. The default values of the Min and Max settings are 0 and 1, respectively.

Output (<variable name>)

The <variable name> part of this output text above the Y-axis displays the name of the variable that the Y-axis represents. Normally, the selected area in the Definition text box of the Define Variable dialog box represents the entire right-hand side of the current variable definition. Therefore, the name of the current variable is indicated here.

In vector mode, the text changes to "Value (Y)".

<graph box>

The graph box shows graphically how output values are related to input values using a two-dimensional diagram in which the output of the graph function is represented by the vertical (Y) axis, and the input is represented by the horizontal (X) axis.

You can update the curve directly by pointing in the graph box with the mouse and pressing the left mouse button at the same time. The Coordinates lists will automatically be updated and scrolled to show the part of the graph that is being updated.

Vector Mode

When you choose Vector in the Edit What list, the graph box shows a graphical representation of a vector using a two-dimensional diagram in which the value of each element is represented by the vertical (Y) axis and the index number is represented by the horizontal (X) axis.

Input (X)

Type or select an expression that becomes the X parameter of the generated graph function. The expression must contain a literal or at least one connected variable and/or TIME. If this requirement is not fulfilled, an error message will appear when you try to confirm the generated graph function in the Define Variable dialog box.

If Input Variables is empty when you open Edit Graph/Vector, and no graph function is selected in the Definition text box, the default content of the Input (X) text box is TIME.

Input Variables

This list contains all variables that are linked as inputs to the current variable in the diagram. Double-click on an item in the list to paste the variable into the Input (X) text box.

OK

Hit this button to confirm the current graph/vector definition, close the dialog box, and paste the generated graph function into the selected portion of the Definition text box of the Define Variable dialog box.

Set

Hit this button to confirm the current graph definition.

Zoom

Hit this button to enlarge or reduce the contents of the graph box.

Edit What

Use this list to choose between Graph and Vector editor mode. In Graph mode, the editor produces a Graph function, in Vector mode, it produces a one-dimensional, constant array. The default setting is determined by whether or not the current variable is a scalar or an array. If it is an array, the Edit What option is set to Vector by default. Otherwise, it is set to Graph.

Interpolation

Use this list to choose the interpolation mode for the graph function. The list contains the following modes:

•	Line (default)

•	Curve

•	Step

The chosen interpolation is used in the graphical curve.

View As (Vector Mode)

When you choose Vector in Edit What, the Interpolation list changes its name, though not its menu contents, to View As. The chosen view does not affect the vector produced by the curve.

Asymptotes

When interpolation is set to Line, you can set the asymptote mode for the graph function using this list. The list contains the following modes:

•	Horizontal (default)

•	Linear

If Interpolation is set to Curve or Step, Asymptotes will automatically be set to Linear or Horizontal, respectively, with the other entry disabled. The chosen asymptote mode does not alter the appearance of the graphical curve.

<Keypad>

Use the keypad buttons to enter numbers and special characters into the selected text box as an alternative to typing them from the keyboard.

<Edit buttons>

The edit buttons are located at the bottom of the keypad. These are buttons for clipboard access and for undoing typing, deleting or pasting:

Button	Command	Shortcut
	Cut	Ctrl+X
	Copy	Ctrl+C
	Paste	Ctrl+V
	Undo	Ctrl+Z
Text is cut or copied from or pasted into the selected text box. The Paste button is disabled if no text is found on the clipboard. The Cut and Copy buttons are disabled if no text is selected.

The Paste button makes it easy to copy data from other documents, such as a spreadsheet, to a graph function or a vector in Powersim.

If you try to paste something into the Coordinates list, the following rules determine the result:

•	If you select several cells, the pasted text is placed in the selected cells to the extent that there is room for it. If the clipboard contains more entries than the number of selected cells, new lines are automatically inserted.

•	Powersim assumes that the clipboard contains one or more text strings separated by blanks, tabs, or linefeeds. Each text string found in the clipboard will be pasted into the current cell of the Coordinates list. The current Coordinates cell is incremented each time a separator character is read.

•	If a text string that is to be pasted into a cell is not a legal number, an error message will appear. The numbers must conform to the settings in the Windows Control Panel.


Dynamic Objects

Dynamic objects are used to present simulation results and to adjust model parameters.They present simulated values or alter the value of selected variables as time passes. Each object uses one or several presentation methods for simulated data. Some objects are output only, that is, they do not take user input.

Name	Methods	Output only
Array Graph	Presents an array of values as a line graph or a series of bars
Button	Presents values as pushbuttons, check-marks, or radio buttons
Gauge	Presents values as a moving bar or needle
Multimedia	Presents video, animation, sound, text, pictures, or message boxes based on the state of a simulation
Number	Presents values as numbers
Scatter Graph	Presents two variables in a two-dimensional graph	X
Slider/Bar	Presents values as horizontal or vertical slider buttons or bars
Time Graph	Presents values as two-dimensional line graphs and/or areas	X
Time Table	Presents values as tables of numbers	X
Command Button	Makes a button to control the simulator. Not for input or output of values.
 See also

  Input and Output Objects

  Control Variables

  Local or Global Settings

  Keeping Input Object Values Between Simulation Runs


Input and Output Objects

All dynamic objects can output simulation results. Most of them can also take user input. An object that receives input allows you to interact with a running simulation, while objects that are output only are used to present information about a simulation.

Note	Input objects must be connected to variables that may receive input. Only levels and constants can receive user input. Variables whose initialization is based on other variables may not receive input during the initialization.


Control Variables

Some dynamic objects have a Control item in the Models combo box of their definition dialog box. Control is a meta co-model containing a set of parameters for accessing the simulation setup, the run setup, and the simulation state (running or pausing) of the model.

Some of the parameters are always read-only (Run and Time); others are read-only during simulation (StartTime, StopTime, TimeStep, RunCount).

For example, you may set the Control.Play parameter from an input object to switch the simulation on or off.

See also

List of Control Variables


List of Control Variables

Item Name	Explanation	See dialog box
StartTime	Start time of current simulation	Simulation Setup
StopTime	Stop time of current simulation	Simulation Setup
TimeStep	Timestep of current simulation	Simulation Setup
AbsErr	Absolute error limit of integration	Simulation Setup
RelErr	Relative error limit of integration	Simulation Setup
Run	Number of current run
RunCount	Number of runs in current simulation	Run Setup
TimeDelay	Execution time per time step	Run Setup
Play	Is the model running? (False=0; True=1)
Pause	Is the model paused? (False=0; True=1)
Time	Current simulation time


Local or Global Settings

If you change options in the definition dialog box of a dynamic object while nothing is selected in the Parameters list, you will change the default settings of these options for the particular object. The default settings are the settings that are assigned to every new parameter of an object. Conversely, when something is selected in the Parameters list, your changes will apply only to the selected parameters.


Keeping Input Object Values Between Simulation Runs

This feature enables Powersim to "remember" input values provided by the user from one simulation run to another. The primary use of this feature is to allow the model user to set a value before the simulation starts, without having to change the definition of the variable.

To keep the input value of selected parameters between runs, check the Keep Values box of the actual input object. You may then bring back the parameters' original value (as specified in the Define Variable dialog box) by choosing Simulate Clear Results.

If Keep Value is switched on, the final value of one simulation will be used as the initial value of the next, that is, values are kept between simulations.

If the Keep Value box is switched off (default) for a particular parameter, input from the current object will be discarded when a new simulation run is initiated. This means that whenever a new run is started, the parameter will be assigned its original value.

Note	If several input objects are connected to one parameter, the parameter will keep its value between runs if one or more of the input objects have Keep Values switched on.

Hint	If the model is distributed using the Run-Time version of Powersim, or if File Properties Acess Edit is switched off, the user cannot edit variable definitions, but he can still change values using input objects with Keep Value switched on.


Array Graph Object

An array graph object displays the current value of several parameters as a line graph or as a series of bars. If the parameters are modifiable (nonauxiliaries), you can click inside the array graph object with the mouse and directly manipulate the associated variables by moving the mouse pointer while pressing the left mouse button.

The array graph object is different from the time graph object in that array graph puts parameter variables along the horizontal axis, while time graph puts time there.

The array graph has much in common with the Edit Graph/Vector dialog box, which is used to define parameters for graph functions and literal values of vectors. The only difference is that array graph operates on variable values, while edit graph/vector operates on variable definitions (accessible only when the model is not running).

Hint	The array graph is perfect for displaying the same kind of information at run time as the graph/vector editor can display at edit time.

See also

  Array Graph example

  Define Array Graph dialog box


Array Graph example

The array graph object below (see XARGRPH.SIM) displays the average temperature in Bergen for each month of the year. The values are stored in a vector, Temperature, with 12 elements. You can also use 12 individual variables, say TempJan, TempFeb, TempMar, etc.

The definition of Temperature is given below:

const	Temperature(1..12) = [1.4, 1.2, 3.1, 5.9, 10.4, 12.8, 15.1, 14.9, 12.1, 8.3, 5.5, 3.2]

The array graph object can also display values as bars, as in a histogram:

Note	The model need not be running for you to modify parameter values using the array graph object - just double click on the object, switch on Keep Value, and you are free to edit values when not simulating.


Define Array Graph dialog box

Use this dialog box to define an array graph object.

Dialog box options

Models

You can choose which models to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Variables

Displays all variable names (scalars) and variable elements (arrays) of the current model, which is normally the main model. To add a variable to the Parameters box, double-click on the variable in the list or select the variable and hit the Add button. Array variables are listed by elements, enabling you to select the elements of an array you wish to add to the Parameters box.

Parameters

This list displays the variables that are parameters to the object. To remove a parameter from the list, double-click on the variable or select the parameter and hit the Remove button.

Add

Adds selected variables of the Variables list to the Parameters list.

Remove

Removes selected parameters from the Parameters list.

Y-Axis

This group deals with the definition of the vertical axis and grid.

Axis

Opens the Y-Axis dialog box.

Minor Grid, Major Grid

Opens the Minor Y-Grid or Major Y-Grid dialog box, which allows you to define color and line style of major and minor grids along the Y-axis.

X-Axis

This group deals with the definition of the horizontal axis and grid.

Axis

Opens the X-Axis dialog box.

Grid

Opens the X-Grid dialog box, which allows you to define color and line style of grids along the X-axis. There is one grid line per parameter.

Label

Displays the label for the selection in the Parameters list. The label is put below the X-axis as a tick label for the given parameter(s). Use the Insert Field button to paste a text field into the Label text.

Insert Field

Opens the Field dialog box for pasting fields into the Label text.

Hint	The field code {Par:Element} displays the subscripts of each parameter as tick labels. This setting is recommended for vector parameters.

To set the label for all parameters in one operation

1	Select the entire contents of the Variables list.

2	Type in a label (optionally using the Insert Field button).

3	Press the Set button.

Drawing

This group determines how the graph line or bar is displayed.

Line

If this box is checked, a line will be displayed along the graph. Click on the Line button to open the Graph Line dialog box to set custom style and color for the line.

Area

If this box is checked, the area below the graph will be filled. Click on the Area button to open the Area Below Graph dialog box to set custom style and color for the filling.

Graph Area

Use this button to set the background color and border for the graph area. The Graph Area dialog box will open.

Type

You can choose between line and bar. The line setting will draw straight lines between the points representing values of parameters, while the bar setting will display the values as a histogram using vertical bars.

Title

Use this command to change the object title. It opens a dialog box (Array Graph Title) for editing a text item.

Background

Use this command to change the background of the object. It opens the Background Area dialog box for changing colors, patterns, etc.

Allow Input

This group determines when input to the array graph is permitted during runtime.

Always

Input is accepted anytime (during runtime).

On Pause

Input is accepted only when the simulation is paused.

Keep Values

Check this box to keep input values between simulation runs (see Keeping Input Object Values Between Simulation Runs ).

If this box is checked, you can give input to the array graph also when the simulation is not running. When starting the simulation, variables will be initialized using the current values of the array graph object. This also means that the final values of one simulation can be used as the initial values of the next one.

Note	If you switch Edit Access (see File Properties Access) off, you can edit array graph objects when the simulation is not running just by pointing and clicking. If Edit Access is on, you must select the object before you can edit it (the first mouse click selects the object, the second starts editing).


Button Object

A Button object displays the current value of certain variables as one of the button states set, clear, or other. Buttons may be used to set variable values and values of control variables, such as Play and Pause.

Buttons may be displayed as pushbuttons, checkmarks or radio buttons. The table below (see XBUTTON1.SIM) displays how the different button types are drawn in the three states.

The button state is determined by the value of the associated parameter (scalar variable or array element) together with the settings of the Values group of the Define Button dialog box.

See

  Button example

  Define Button dialog box

See also

  Command Button


Button example

The button object below (see XBUTTON2.SIM) is connected to a constant that acts as a model parameter.

When you click in one of the choices of the button object, the value of the connected constant is set to a corresponding value. The respective values for High, Medium, and Low have been predefined in the Define Button dialog box.


Define Button dialog box

Use this dialog box to define a button object.

Dialog box options

Model

You can choose which model to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Variables

Displays all variable names (scalars) and variable elements (arrays) of the current model, which is normally the main model. To add a variable to the Parameters box, double-click on the variable in the list or select the variable and hit the Add button. Array variables are listed by elements, enabling you to select the elements of an array you wish to add to the Parameters box.

Parameters

This list displays the variables that are parameters to the object. To remove a parameter from the list, double-click on the variable or select the parameter and hit the Remove button.

Add

Adds selected variables of the Variables list to the Parameters list.

Remove

Removes selected parameters from the Parameters list.

Command

This group operates on the current selection in the Parameters list box. Here you may specify actions (how the value of the associated parameter will be modified) when the user clicks with the mouse inside a button. The possible actions are listed below:

Action	Explanation
None	The variable will be unchanged.
Set	The variable will get the value specified in the Set text box of the Values group.
Clear	The variable will get the value specified in the Clear text box of the Values group.
Toggle	If the current value of the variable is equal to the one specified in the Set text box of the Values group, a Clear action will take place. Otherwise a Set action will take place.
On Press

Specify action to be taken when you point inside a button with the mouse cursor and press the mouse button.

On Repeat

Specify action to be taken while you keep the mouse button depressed with the mouse cursor inside a button. The repeat rate is defined by Windows Control Panel Keyboard Repeat Rate.

On Release

Specify action to be taken when you point inside a button and release the mouse button.

Button

This group operates on the current selection in the Parameters list box. Here you may define the text associated with each button.

Text

You may type in the text to be displayed for the buttons. The text may contain fields.

Insert Field

Use this command to insert a field in the Text box. Click the button to open the Field dialog box.

Font

Use this command to change the button font. Click the button to open the Font dialog box.

Values

This group operates on the current selection in the Parameters list box. You may specify the values associated with the set and clear state of selected buttons. Individual buttons of the same Button object may have different values associated with the set and clear states.

Set

Changes the value associated with the set state of the selected buttons. The default value is one (1).

Clear

Changes the value associated with the clear state of the selected buttons. The default value is zero (0).

Exclusive

If this checkmark is on, only one button in the Button object may be in the set state at the time. This means that if you take an action that causes a button to become set, Powersim will put all other buttons (and associated parameter values) in the clear state.

Size

All buttons of a Button object are the same size. Use this group to determine the size of buttons.

Width

Changes the width of buttons.

Height

Changes the height of buttons.

Auto Size Object

If this checkmark is on, Powersim will give the Button object a size that will enclose all defined buttons and the object title. The Button object size will be adjusted automatically if you add or remove buttons.

Set

Hit this button when you finish editing a text box. Set becomes the default button when you edit a text box, so pressing the Return key during text input will cause the Set command to be performed.

Title

Use this command to change the object title using the Button Title dialog box.

Background

Use this command to change the background of the object. It opens the Background Area dialog box for changing colors, patterns, etc.

Move Up, Move Down

Moves the selected variables up/down in the Parameters list.

Orientation

You can choose between horizontal and vertical orientation of the buttons.

Display As

You can determine how buttons are displayed - as pushbuttons, checkmarks, or radio buttons.

Possible States

This list box determines the number of ways a button can be displayed. The table below illustrates how a button will be displayed, depending on Possible States and the value of the associated parameter.

State	Value=Clear	Value=Set	Value=Other
1-State	Display as Clear	Display as Clear	Display as Clear
2-States	Display as Clear	Display as Set	Display as Clear
3-States	Display as Clear	Display as Set	Display as Other
Value=Clear means that the parameter value is equal to the contents of the Clear text box. Value=Set means that the value is equal to the contents of the Set text box. Value=Other means that the value differs from both Set and Clear.

Allow Input

When this box is checked, you may use the mouse to change the state of the buttons. The commands associated with various mouse actions are defined in the Command group (see above).

Input on Pause

When this box is checked, you may give input to the buttons by clicking the mouse only when the simulation is paused.

Keep Value

Check this box to keep input values between simulation runs (see Keeping Input Object Values Between Simulation Runs ).


Gauge Object

The gauge is an input/output object that displays a model variable as a moving bar or needle. The gauge can be formatted in countless ways, including coloring, shape, and axis.

See also

  Gauge example

  Define Gauge dialog box

  Gauge Shape dialog box

  Predefined Gauge Shapes dialog box

  Gauge Sectors dialog box

  Gauge Needle dialog box

  Gauge Bar dialog box


Gauge example

In the example below (see XGAUGE.SIM), the value of the variable Speed is presented both a gauge needle and a number inside the gauge.


Define Gauge dialog box

Use this dialog box to define a gauge object.

Dialog box options

Model

You can choose which model to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Parameter

You can choose a variable or array element to be presented by the gauge object.

Number

Use this group to format the number displayed by the gauge object (if present).

Field Width

You can change the field width of the number displayed by the gauge object.

Format

Use this button to open a pop-up menu with formatting options for the value cell of the number. The options are as follows:

•	Position: Opens a cascading menu, allowing you to choose the number's position relative to the gauge sector. None means that no number will be displayed in the gauge.

•	Box: Customizes the number box. Opens the Number Box dialog box for changing colors, patterns, etc.

•	Font: Changes the number font. Opens the Font dialog box.

•	Number: Changes the way numeric values are formatted when displayed. Opens the Format Number dialog box.

•	Alignment: Opens a cascading menu, allowing you to determine the left, center, or right alignment of a number displayed inside the number box.

Allow Input

Use this group to indicate whether you want to be able to change the value of the parameter variable during a simulation run. If Always or On Pause is checked, two buttons will be shown below the gauge. Use the left button to reduce the parameter, the right one to increase it.

Always

Check Always to enable input whenever a simulation is running or pausing.

On Pause

Check On Pause to enable input only when a simulation is pausing.

Title

Use this command to change the object title using the Gauge Title dialog box.

Background

Use this command to change the background of the object. It opens the Background Area dialog box for changing colors, patterns, etc.

Axis

Use this command to change the gauge axis from the Gauge Axis dialog box.

Shape

Use this command to change the shape of the gauge from the Define Shape dialog box.

Predefined

Click this button to choose among 12 Predefined Gauge Shapes.


Gauge Shape dialog box

Use this command to change the shape of a gauge object. The gauge sector may be circular or rectangular, and the parameter's value displayed by the gauge may be a needle or a filled area (bar).

Dialog box options

Pie

Use this group to set the animate angle and extra angle for the gauge if type is pie.

Animate Angle

This option determines the size of the angle (measured in degrees) within which the gauge needle or bar is to move. Legal values are between 1 and 360.

Extra Angle

This option determines how much extra space (measured in degrees) to reserve for the gauge. The needle (or bar) will not be displayed here. The sum of Animate Angle and Extra Angle must not exceed 360.

Type

You can choose between a pie-shaped (circular) and a rectangular sector.

Animate

Use this box to choose whether the gauge parameter will be displayed as a needle or a bar (filled area).

Area

Use this command to change the background of the gauge sector. It opens the Gauge Area dialog box for changing colors, patterns, etc.

Predefined

Click this button to choose among 12 Predefined Gauge Shapes .

Sectors

Click this button to define the sectors of your gauge object using the Gauge Sectors dialog box.

Needle

If Animate = Needle, you can click this button to define the gauge needle from the Gauge Needle dialog box.

Bar

If Animate = Bar, you can click this button to define the gauge bar from the Gauge Bar dialog box.


Predefined Gauge Shapes dialog box

There are 12 different predefined gauges. Click at the desired shape and click OK.

Dialog box options

The 12 shapes can be systematized as follows:

Rows

•	In the first row are four rectangular gauges.

•	In the next row the gauges are circular with Animation Angle = 90.

•	In the last row the gauges are circular with Animation Angle = 270.

Columns

•	The first column has gauges with needles and without sectors.

•	The second column has gauges with bars, still without sectors.

•	The last two columns are almost the same as the two previous ones. The only difference is the use of sectors.


Gauge Sectors dialog box

Gauge sectors can visualize properties of a certain range of values. For example, a green and a red sector can symbolize critical values of the parameter.

Dialog box options

From, To, Pattern list

All defined sectors are displayed in this list box. Each sector is defined by a lower value, an upper value, and a color (pattern).

Set

Click this button to assign the From, To, and Pattern specified in the Define Sector group to the selected sector of the list above.

Insert

Click this button to insert the From, To, and Pattern specified in the Define Sector group as a new sector in the list above.

Remove

Click this button to remove the selected item in the sector list above.

Define Sector

Use this group to define a sector by using the three attributes From, To, and Pattern.

From

Specifies at which value (absolute or percent) the sector starts.

To

Specifies at which value (absolute or percent) the sector ends.

Pattern

Specifies which color and pattern the sector will be displayed in. Click the Edit button to open the Sector Area dialog box.

Outer Radius

Sectors will be displayed in the gauge as an area with an inner and an outer radius. The outer sector radius can be

•	Outside Axis

•	At Axis

•	Inside Axis

Inner Radius

The inner sector radius can be

•	At Axis

•	Inside Axis

•	In Sector

•	At the Center

Numbers

You may choose between two ways to interpret the From and To values of a sector definition

•	As absolute numbers. The From and To values are directly related to the value of the parameter.

•	As a pertentage of the size of the gauge area. This choice may be useful if the range of the parameter is unknown.


Gauge Needle dialog box

Use this dialog box to change the shape, color, and radius of the gauge needle.

{bml DDEFGANE.BMP}

Dialog box options

Outer Radius

As in the case of sectors, a needle has an inner and an outer radius. The outer needle radius can be

•	Outside Axis

•	At Axis

•	Inside Axis

Inner Radius

The inner needle radius can be

•	At Axis

•	Inside Axis

•	In Sector

•	At the Center

•	Below Center

Shape

You can choose among three different needle shapes

•	Triangle

•	Diamond

•	Line

Animation Color

Use this group to change the color of the needle. There are two modes available:

Fixed Color

If you choose this option, the needle will have a fixed color. You can change the color by clicking the Edit button, which opens the Needle Border and Interior dialog box.

Active Sector Color

If you choose this option, the needle is painted in the same color as the sector it points to. If the needle does not point in a sector, the fixed color is used.

Fixed Color

Click this button to change the fixed animation color of the needle. It opens the Needle Border and Interior dialog box.


Gauge Bar dialog box

Use this dialog box to change the color and radius of the gauge bar.

Dialog box options

Outer Radius

As in the case of sectors, a bar has an inner and an outer radius. The outer bar radius can be

•	Outside Axis

•	At Axis

•	Inside Axis

Inner Radius

The inner bar radius can be

•	At Axis

•	Inside Axis

•	In Sector

•	At the Center

Animation Color

Use this group to change the color of the bar. There are three modes available:

Fixed Color

If you choose this option, the bar will have a fixed color. You can change the color by clicking the Fixed Color button.

Sector Colors

If you choose this option, the bar is split into partitions equal to each sector. Each partition gets the color of the corresponding sector. If no sector is present, the fixed color is used.

Active Sector Color

If you choose this option, the bar is painted in the same color as the sector it points to. If the bar does not point in a sector, the fixed color is used.

Fixed Color

Click this button to change the fixed animation color of the bar. It opens the Bar Interior dialog box.


Number Object

A number object displays the current value of a certain variable as a number. If the parameter associated with a number object is a constant, or a level whose initial value is not dependant on other variables, you may adjust the value of the constant directly by clicking on the object and entering the desired value from the keyboard.

See also

  Number example

  Define Number dialog box


Number example

The number object below (see XNUMBER.SIM) displays the current value of the variable Revenue.


Define Number dialog box

Use this dialog box to define a number object.

Dialog box options

Model

You can choose which model to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Parameter

You can choose a variable or array element to be presented by the number object.

Number

Use this group to format the number displayed by the object.

Field Width

You can change the field width of the number displayed by the object.

Format

Use this button to open a pop-up menu with formatting options for the value cell of the number object. The options are as follows:

•	Box: Use this command to customize the number box. It opens the Number Box dialog box for changing colors, patterns, etc.

•	Font: Use this command to change the number font. It opens the Font dialog box.

•	Number: Use this command to change the way numeric values are formatted when displayed. It opens the Format Number dialog box.

•	Alignment: Use this command to open a cascading menu, allowing you to determine the left, center, or right alignment of a number displayed inside the number box.

Label

Use this group to define the object's label, which is normally the name of the variable presented by the number object.

Label Position

Changes the position of the object label. You can choose between Right, Left, Top, and Bottom.

Label

Use this command to change the contents of the object label. It opens the Number Label dialog box for editing a text item.

Background

Use this command to customize the background of the number object. It opens the Background Area dialog box for changing colors, patterns, etc.

Allow Input

Use this group to indicate whether you want to be able to change the value of the parameter variable during a simulation run.

Always

Check Always to enable input whenever a simulation is running or pausing.

On Pause

Check On Pause to enable input only when a simulation is pausing.

Pause on Input

Check this box if you want Powersim to automatically pause a simulation when you click in the object with the mouse. This feature allows you to easily change parameter values during a simulation run.

Limit Input

Check this box if you want the number object to reject input values that do not lie within the selected variable's min-max interval.

Keep Value

Check this box if you want the object to keep the value displayed in the number box when starting a new simulation. See also: Keeping Input Object Values Between Simulation Runs ).


Multimedia Object

This is a true multi purpose presentation that allows you to present video, animation, sound, text, pictures, and message boxes based on the state of a simulation. The multi-media feature is also an input presentation that allows the model to obtain information from a playing video, the user's response to a message, etc.

See also

  Introduction to multimedia

  Working with the multimedia object

  Define Multimedia dialog box

  Advanced Settings dialog box

  Define Text Presentation dialog box

  Define Picture Presentation dialog box

  Define Video Presentation dialog box

  Preview Video dialog box

  Define Sound Presentation dialog box

  Define Message Box Presentation dialog box


Introduction to multimedia

The main function of the multimedia object, is to provide information through the highly communicative media, such as video, sound and pictures. A message box can be displayed by itself, or in combination with a multimedia presentation. This opens up for interactive multimedia: The user gives input to the simulation by answering questions put forward as message boxes that appear under certain conditions during a simulation.

The multimedia object allows you to create simulators where the multimedia is closely connected to the behavior of the simulation. At the beginning of the simulation, an introduction can be displayed as a video clip. When given conditions are met in the model, the simulation can pause, and a voice message explain something about what is going on. Or you can simply display warnings or status information as the simulation goes on. Decisions that should be made by the user running the simulation, can be made by displaying message boxes with options the user can choose from.

Presentations can be made either in the diagram or in pop-up windows

Multimedia presentations can be displayed either inside a multimedia object in the diagram, or in pop-up windows that appear under given conditions during simulation.

Multimedia presentation in child window inside diagram

Multimedia presentation in pop-up window.

Introduction to multimedia scripts

A model can contain several multimedia objects, and each object can hold a list of presentations that will be made based on given values of input parameters to the object. The following describes a multimedia script for a simulation model:

•	When time becomes 1 play introduction video

•	If liquidity gets low play voice message and ask user if he wants to decrease investments

•	While profits are high display happy face

•	When simulation stops play debriefing video

The actual script will look like this:

Event Name	Condition	Type
Introduction	Control.Time = 1	Video
Liquidity warning	LiquidityDropsLow = 1	Sound
Profits are good	Profits > 0.1	Picture
Debriefing	Control.Time = 360	Video
Conditions control when presentations start

A given multimedia presentation is started whenever the corresponding condition becomes true. A condition is evaluated by comparing the value of an input parameter to one or two constants, using one of the following relational operators:

Operator	Explanation
<	Parameter less than value
<=	Parameter less than or equal to value
=	Parameter equal to value
<>	Parameter not equal to value
<=	Parameter greater than or equal to value
>	Parameter greater than value
in	Parameter inside interval, that is, greater than or equal to lower limit and less than or equal to upper limit
not in	Parameter outside interval, that is, less than lower limit or greater than upper limit
Note	Tests involving equality (especially = and <>) should be done with care, as parameter values are floating point numbers, which many not be exact representations of the corresponding mathematical expressions. As an example, SQRT(POW(X, 2)) may not compute to exactly X, even if [image] is the same as x itself. This has to do with round-off errors in mathematical computations on a digital computer.

Using priorities to resolve conflicting presentations

The fact that a multimedia object can define several presentations that will be made under various conditions, leads to the possibility of more than one condition being true at the same time. As it is not possible to display more than one picture in one place at the same time, we need to resolve which presentation to choose if several conditions are true simultaneously.

Presentations are ordered according to priority, where each entry in the presentation list have higher priority than all entries listed below. If the Terminate on Higher Priority check mark is set for a presentation, the presentation will be terminated whenever a higher priority presentation wants to start. Otherwise the current presentation will continue until it is terminated for other reasons.

Below is a table displaying how a conflict between two presentations is resolved. Presentation A is currently active when B's condition gets true.

Setting for A	Priority of A < priority of B	Priority of A > priority of B
Terminate on higher priority: Yes	Terminate A, start B.	Continue A, hold back B.
Terminate on higher priority: No	Continue A, hold back B.	Continue A, hold back B.
If B is held back, B will be started when A terminates, given that B's condition is still true, and that no higher priority presentation is pending.

When do presentations end?

As described above, a presentation can be terminated prematurely if the Terminate on Higher Priority setting is on, and a higher priority presentation wants to start. Normally a presentation ends when it is finished. For a video or a sound presentation this means that the video or sound track is completed. For a text and a still picture presentation, a duration (seconds) can be entered when defining the presentation. When a static presentation (text, picture) is started, a timer begins counting down. When the specified time has elapsed, the presentation is "finished", and will be terminated, unless the Loop while Condition is True check mark is on. A message box is a presentation that is completed when the user selects one of the options, for example by clicking on the OK button.

Presentation	Finishes when
Video	Finishes when the last frame has been displayed
Sound	Finishes when the last sound has been played
Text and picture	Finishes when the elapsed time has passed
Message box	Finishes when user gives answer (presses button)
If the Loop while Condition is True setting is on, a presentation continues from the beginning when it reaches the end. This can be used to make a continuous sound or video. Looping presentations end on the following events:

•	A higher priority presentation wants to start, and the Terminate on Higher Priority is set.

•	The condition controlling the condition gets false, and the Terminate on Condition not True setting is set. The presentation will complete the current loop before it ends.

•	The user starts editing the model, a new simulation run is started, or the model is closed.

Pausing the simulation while a presentation is active

It is possible both to pause the simulation while a presentation is made, and to make a presentation while the simulation is still running. The Pause while Presenting setting controls this option. If on, the simulation is paused when the presentation starts. Simulation continues automatically when the presentation finishes. If Pause while Presenting is switched off, the simulation will run in parallel with the presentation.


Define Multimedia dialog box

Use this dialog box to define a multimedia object.

Dialog box options

Name

Enter the name of a presentation here.

Type

Choose type of presentation from this list. The type cannot be changed for an existing presentation, unless you delete the presentation using Remove and create a new one using Insert or Append.

Model

Choose a model to pick a parameter from in the Parameter list below.

Parameter

Here you select a parameter to control the presentation(s) selected in the Presentations list. The value if the input parameter is compared using the settings in the Condition group to determine when a presentation should be started and stopped.

Pause while Presenting

Set this check mark if you want the simulation to be paused whenever one of the presentation(s) selected in the Presentations list is active. If unchecked, the simulation will continue while the presentation is made.

Terminate on Higher Priority

A presentation with this setting switched on will be terminated immediately whenever a higher priority presentation wants to start.

Terminate on Condition not True

If this check mark is switched on for a presentation, the presentation will be terminated if the controlling condition becomes false, even if the presentation is not finished.

Loop while Condition is True

If you want a presentation to repeat itself, switch on this check mark for that presentation. When the presentation is finished, it will start from the beginning, given that the controlling condition is still true.

Condition

Use this group together with the Model/Parameter setting to determine when a presentation should be active.

Operator

This setting determines how the value of the Parameter will be compared to the value listed in the Value box and the 2nd Value box.

Operator	Condition true when
<	Parameter < Value
<=	Parameter <= Value
=	Parameter = Value
<>	Parameter <> Value
<=	Parameter >= Value
<	Parameter > Value
in	(Value <= Parameter) and (Parameter <= 2nd Value)
not in	(Parameter < Value) or (2nd Value < Parameter)
Value/2nd Value

Type in a number to be compared to the selected Parameter using the selected Operator.

Set

Press Set after a change to one of the properties of a presentation, for example after editing the Name field. This will copy the values you have set to the selected entries in the Presentations list. When you change a field, for example by typing in the Name field, the Set button becomes default button, so you can just complete your editing by pressing Return, and the Set button will automatically be invoked.

Up/Down

Use these buttons to sort presentations in the Presentations list. The selected items in the list will be moved up or down when you press these buttons. Remember that priorities decrease top down in the Presentations list, so you should list the most critical presentations first.

Append

Press this button to insert a new presentation after the current selection in the Presentations list. Before pressing Append, you should enter values for the properties of the new presentation by filling in Name, Type, Model, Parameter, etc. Especially the Type field is important to set, as it cannot be changed without removing the presentation and creating a new one.

Insert

Press this button to insert a new presentation before the current selection in the Presentations list. Before pressing Insert, you should enter values for the properties of the new presentation by filling in Name, Type, Model, Parameter, etc. Especially the Type field is important to set, as it cannot be changed without removing the presentation and creating a new one.

Edit

Make a selection in the Presentations list and press Edit to view and change type specific options of a presentation, for example entering the text of a text presentation. You can also double click on an entry in the Presentations list to edit a presentation. The dialog boxes for editing each of the multimedia types are explained later in this chapter.

Remove

This button will remove the selected entries in the Presentations list. If you hit Remove by accident, just press Cancel, and you will get back the presentations you had at the time when you opened up the dialog box.

Advanced

This button opens up a dialog box for setting attributes that are common to all presentation contained in the multimedia object.


Advanced Settings dialog box

Dialog box options

Appearance

This group determines the appearance of the window that is used to display presentations.

Display in

Choose between Diagram and Window. If Diagram is chosen, the presentation will be made inside the multimedia object in the diagram window. If Window is picked, a pop-up window will opened when giving a presentation.

Border

A border can be set only for presentations displayed in a window. You can choose between None, Thin, Resizing and Dialog Frame. Use the Background button to set border, background, etc. for presentations made in the diagram.

Title Bar

Title bar can be set only for presentations displayed in a window. If checked, the pop-up windows will be equipped with a title bar (also called caption).

System Menu

System menu can be set only for windows with title bar. If checked, the pop-up window will have a system menu.

Playbar

Sound and video presentation can have a play bar. If checked, a playbar will be displayed whenever a sound or video presentation is active.

Hide when not Active

If checked, the multimedia object will be hidden from the diagram window except when you are editing the model, or when a presentation is active in the object. If unchecked, the multimedia object will be displayed as a frame object whenever it is not presenting. The colors and styles for the object is set using the Background button.

The multimedia object is displayed differently, depending on editing state, presentation state, and settings made in the Advanced dialog box.

	Model is being edited.
	Display in Diagram is set, and presentation is active.
	Display in Diagram is set, and no presentation is active, and Hide when not Active is off.
object hidden	Display in Window is set, or Display in Diagram is set, and no presentation is active, and Hide when not Active is on.
Position

Position can be set only for presentations displayed in a window.

Vertical

You can choose between Bottom, Middle and Top.

Horizontal

You can choose between Left, Center and Right.

Keep Position

A presentation window can be moved to an arbitrary position while running, given that the window has a title bar (caption). If Keep Position is checked, the window position is remembered when a presentation is finished, and used to restore the window position when a new presentation starts.

Background

Use this button to open define the border, shade, shape and interior of the multimedia object when displayed in the diagram. The common Area dialog box is opened.


Define Text Presentation dialog box

Dialog box options

The above dialog box is opened by pressing the Edit button inside the Define Multimedia dialog box, with a text presentation selected in the Presentations list.

Output

The presentation can be associated with an output parameter. When a presentation starts, the value of the output parameter will be set to one. When the presentation ends, the output parameter is set to zero.

Model

Choose a model to pick a parameter from in the Parameter list below.

Parameter

Pick an optional output parameter to receive information about when the presentation starts and ends.

Text

Here you can type in the text to be displayed when the text object is presented.

Window Title

Here you enter a text to be displayed in the title bar (caption) if the presentation is displayed in a window that has a title bar. The window title will be ignored if the presentation is made inside the diagram or the Title Bar is switched off in the Advanced Settings dialog box.

Font

Use this button to choose a font for the text. It opens a standard Font dialog box.

Layout

Use this button to choose a orientation and alignment for the text. It opens a common Text Layout dialog box.

Duration

Enter how many seconds the presentation should be displayed when activated. The presentation can be ended before the elapsed time, depending on the settings made for Terminate on Higher Priority, Terminate on Condition not True, and Loop while Condition is True. See Define Multimedia dialog box.

Msg. Box

If checked, the presentation has an associated message box that will be displayed whenever the presentation starts. Click on the button to define the properties of the message box. Clear the check mark to remove the associated message box. For presentations with an associated message box, the presentation ends when the user closes the message box.


Define Picture Presentation dialog box

Dialog box options

The above dialog box is opened by pressing the Edit button inside the Define Multimedia dialog box, with a picture presentation selected in the Presentations list. The dialog box is very similar to the Define Picture dialog box.

Output

The presentation can be associated with an output parameter. When a presentation starts, the value of the output parameter will be set to one. When the presentation ends, the output parameter is set to zero.

Model

Choose a model to pick a parameter from in the Parameter list below.

Parameter

Pick an optional output parameter to receive information about when the presentation starts and ends.

Scale

Scale to

(see Define Picture)

Relative to Original Picture Size

(see Define Picture)

Window Title

Here you enter a text to be displayed in the title bar (caption) if the presentation is displayed in a window that has a title bar. The window title will be ignored if the presentation is made inside the diagram or the Title Bar is switched off in the Advanced Settings dialog box.

Paste

(see Define Picture)

Paste as Type

(see Define Picture)

Duration

Enter how many seconds the presentation should be displayed when activated. The presentation can be ended before the elapsed time, depending on the settings made for Terminate on Higher Priority, Terminate on Condition not True, and Loop while Condition is True. See Define Multimedia dialog box.

Msg. Box

If checked, the presentation has an associated message box that will be displayed whenever the presentation starts. Click on the button to define the properties of the message box. Uncheck the check mark to remove the associated message box. For presentations with an associated message box, the presentation ends when the user closes the message box.


Define Video Presentation dialog box

Dialog box options

The above dialog box is opened by pressing the Edit button inside the Define Multimedia dialog box, with a video presentation selected in the Presentations list.

Output

The presentation can be associated with an output parameter. When a presentation starts, the value of the output parameter will be set to one. When the presentation ends, the output parameter is set to zero.

Model

Choose a model to pick a parameter from in the Parameter list below.

Parameter

Pick an optional output parameter to receive information about when the presentation starts and ends.

File Name

Here you can enter the name of a video file (a file with extension AVI). Use the Browse button to activate the Open File dialog box for selecting a file.

Browse

Opens a dialog for selecting an AVI file into the File Name field.

Frames

This group is used to select a range of frames to be present from the AVI file listed in the File Name box. The selected frames implicitly defines the duration of the video presentation.

From

Show video starting with this frame.

To

Video presentation ends at this frame.

Preview

Use this button to open the Preview Video dialog box to preview the video and optionally pick a from frame and a to frame.

Window Title

Here you enter a text to be displayed in the title bar (caption) if the presentation is displayed in a window that has a title bar. The window title will be ignored if the presentation is made inside the diagram or the Title Bar is switched off in the Advanced Settings dialog box.

Msg. Box

If checked, the presentation has an associated message box that will be displayed whenever the presentation starts. Click on the button to define the properties of the message box. Uncheck the check mark to remove the associated message box. For presentations with an associated message box, the presentation ends when the user closes the message box.


Preview Video dialog box

Dialog box options

The above dialog is opened from the Define Video Presentation dialog box, and lets you preview a video and select the frames that you want to take part in the presentation.

The buttons below the preview window have the following meaning:

	Go to first frame
	Fast backward
	Step backward
	Play
	Pause
	Stop
	Step forward
	Fast forward
	Go to last frame
From Frame

Here you can type in the number of the first frame that you want to include in you presentation. You can copy the current frame into the From Frame field by pressing the Set From button.

To Frame

Here you can type in the number of the last frame that you want to include in you presentation. You can copy the current frame into the To Frame field by pressing the Set To button.

Frame
The frame text field holds the number of the frame that is currently displayed in the preview window. The frame number is updated when the video is played. When the video is stopped you can enter a frame number here in order to seek to a given frame in the video file.

Set From

Use this button to update the From Frame field with the current Frame number.

Set To

Use this button to update the To Frame field with the current Frame number.


Define Sound Presentation dialog box

Dialog box options

The above dialog box is opened by pressing the Edit button inside the Define Multimedia dialog box, with a sound presentation selected in the Presentations list. The sound presentation plays an entire WAV file. Later versions will include possibilities to play CD-Audio and MIDI and parts of a WAV file. If you need to play part of a WAV file, you should use a tool for editing sound, and save the desired section in a separate file.

Output

The presentation can be associated with an output parameter. When a presentation starts, the value of the output parameter will be set to one. When the presentation ends, the output parameter is set to zero.

Model

Choose a model to pick a parameter from in the Parameter list below.

Parameter

Pick an optional output parameter to receive information about when the presentation starts and ends.

Sound File

Here you can enter the name of a sound file (a file with extension WAV). Use the Browse button to open the Open File dialog box for selecting a file.

Browse

Opens a dialog for selecting an WAV file into the Sound File field.

Window Title

Here you enter a text to be displayed in the title bar (caption) if the presentation is displayed in a window that has a title bar. The window title will be ignored if the presentation is made inside the diagram or the Title Bar is switched off in the Advanced Settings dialog box.

Msg. Box

If checked, the presentation has an associated message box that will be displayed whenever the presentation starts. Click on the button to define the properties of the message box. Uncheck the check mark to remove the associated message box. For presentations with an associated message box, the presentation ends when the user closes the message box.


Define Message Box Presentation dialog box

Dialog box options

The above dialog box is opened by pressing the Edit button inside the Define Multimedia dialog box, with a message box presentation selected in the Presentations list. The dialog box is also opened when pressing the Msg. Box button of any of the define Text, Picture, Video or Sound presentation dialog boxes. The dialog box is used to define a message box presentation, or a message box attached to another presentation.

Output

The presentation can be associated with an output parameter. The output parameter receives the value associated with the button the user use to close the dialog box.

Model

Choose a model to pick a parameter from in the Parameter list below.

Parameter

Pick an optional output parameter to receive value associated with the button used to close the message box. The value associated with Cancel is returned if the dialog box is closed using the Esc key, the Close command of the system menu, or the close button in the title bar.

Text

Here you can type in the text to be displayed when the message box is presented.

Window Title

Here you enter a text to be displayed in the title bar (caption) if the presentation is displayed in a window that has a title bar. The window title will be ignored if the presentation is made inside the diagram or the Title Bar is switched off in the Advanced Settings dialog box.

Buttons

Here you can select which buttons to be displayed in the message box. Possible choices are:

•	Abort/Retry/Ignore

•	OK

•	OK/Cancel

•	Retry/Cancel

•	Yes/No

•	Yes/No/Cancel

Icon

What icon is to be shown. Possible values are:

	Stop-sign
	Question Mark
	Exclamation Mark
	Information
	None
Return Values

A list showing what to return for each button. Each entry in the list displays a button and its associated return value. If the user ends the message box by pressing the given button, the corresponding value will be assigned to the Output Parameter, as explained earlier. If the user closes the message box using the Esc key or Close in the system menu, this will be the same as hitting the Cancel button.

Value

Number box for editing a selected return value.

Set

Assign the contents of the Value box to the button currently selected in the Return Values list.


Scatter Graph Object

A scatter graph displays the relationship between two variables in a two-dimensional graph by using one variable as the X-coordinate and the other as the Y-coordinate.

See also

  Scatter Graph example

  Define Scatter Graph dialog box


Scatter Graph example

In the scatter graph below (see XSCATTER.SIM), the values of Capital and Consumption are plotted as the result of a simulation. Each point (X, Y) on the graph corresponds to a particular point in time where Capital = X and Consumption = Y.


Define Scatter Graph dialog box

Use this dialog box to change the definition of a scatter graph object.

Dialog box options

Horizontal (X) Axis, Vertical (Y) Axis

The scatter graph allows for only one parameter along each of the two axes. These groups deal with the definition of the horizontal and the vertical axes.

Model

Use this combo box to select a model from which to pick the parameter to be plotted along an axis. If only one model is available (no co-models), the combo box will be dimmed.

Parameter

Use this combo box to select the parameter for an axis.

Axis

Use this combo box to open the X-Axis or the Y-Axis dialog box.

Minor Grid, Major Grid

Use this combo box to open the Minor Grid or Major Grid dialog box that lets you change the color and style of the axis line.

Drawing

Use this group to change the way the graph is plotted. Check Line to use a line to connect neighboring points in the graph. The default line style is a black line with unit width (one point). Check Marker to put markers along the graph line at each time step (see Step below).

Line

Use this button to change color, width, and style of the graph.

Marker

Use this button to select colors and style for markers.

Graph Area

Use this button to open the Graph Area dialog box for changing colors and pattern of the graph area.

Times

Use this group to define the time interval for which the graph will be displayed. Normally the entire length of the simulation will be included in the graph.

From

Determines the time value of the first point to be plotted in the graph. If you check the box, the value of Simulation Setup Start Time will be used.

To

Determines the time value of the last point to be plotted in the graph. If you check the box, the value of Simulation Setup Stop Time will be used.

Step

Determines the time interval to be used between plotting markers (see Marker above). If you check the box, the value of Simulation Setup Time Step will be used.

Set

Use this button to accept the values entered in the text boxes From, To, Step, and Save Limit. The Set button becomes the default push button whenever you edit a text box. Then the Return key can be used to end editing of a number. When you press Set, OK again becomes the default pushbutton.

Title

Use this command to change the object title from the Scatter Graph Title dialog box.

Background

Use this command to customize the background of the scatter graph object. It opens the Background Area dialog box for changing colors, patterns, etc.

Save Limit (points)

Normally the scatter graph saves data for both parameters at each time step. A large number of time steps (small time step and/or large time span) requires a significant amount of memory (approximately 16 bytes per time step). The value in the Save Limit text box determines the maximum number of points that will be saved for each parameter. If you set it to 51, for example, a maximum of 50 points will be used when saving parameter values. If the time range has 101 steps, data will be saved for every other time step. When plotting intermediate values, Powersim uses linear interpolation.


Slider/Bar Object

A slider/bar object displays the current value of certain variables as bars and/or slider buttons along a horizontal or vertical value axis. Optionally it can also display its parameters' values as numbers.

See also

  Slider/Bar example

  Define Slider/Bar dialog box


Slider/Bar example

The slider/bar object below (see XSLIDERB.SIM) contains two variables. The variable Inventory is presented as a bar. The bar is output only. The variable Inv_Coverage, which is a constant in the model, is presented as a slider. The slider allows you to adjust the variable directly by dragging the button while a simulation is running.

A horizontally orientated slider/bar object with labels positioned to the left and number boxes not present

A slider/bar object can also contain a number box for each parameter, allowing you to see the precise numerical value as you adjust variables by dragging the slider button. If present, the number boxes are always positioned opposite their corresponding label.

A vertically oriented slider/bar object with the label positioned on top and number boxes present


Define Slider/Bar dialog box

Use this dialog box to define a slider/bar object.

Dialog box options

Models

You can choose which models to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Variables

Displays all variable names (scalars) and variable elements (arrays) of the current model, which is normally the main model. To add a variable to the Parameters box, double-click on the variable in the list or select the variable and hit the Add button. Array variables are listed by elements, enabling you to select the elements of an array you wish to add to the Parameters box.

Parameters

Lists the variables that are parameters to the object. You can adjust these variables using slider buttons, or view them as bars. To remove a parameter from the list, double-click on the variable, or select the parameter and hit the Remove button.

Add

Adds selected variables of the Variables list to the Parameters list.

Remove

Removes selected parameters from the Parameters list.

Bar

Use this group to change the bar attributes.

Label Position

You can choose between top, bottom, left, and right position for the bar label. The Label position also determines the position of the number box, if present, as the number box is always placed opposite the label.

Label

You can change the label contents of the selected variables. The Label button opens the Bar Label dialog box for editing a text item. It is disabled if no variables are selected in the Parameters list.

Axis

Opens the Bar Axis and Scale dialog box.

Bar Area

Opens the Bar Box dialog box for changing colors, patterns, etc.

Fill With

Opens the Bar Fill Area dialog box for changing colors, patterns, etc.

Number

Use this group to change the definition of the number part of the object.

Field Width

Use this button to change the field width of the number displayed by the object.

Format

Use this button to open a pop-up menu with formatting options for the value cell of the slider/bar object. The options are as follows:

•	Box: Use this command to customize the number box. It opens the Number Box dialog box for changing colors, patterns, etc. All number cells share one box format.

•	Font: Use this command to change the number font. Opens the Font dialog box. All number cells share one font setting.

•	Number: Use this command to change the way numeric values are formatted when displayed. Opens the Format Number dialog box.

•	Alignment: Use this command to open a cascading menu, allowing you to determine the left, center, or right alignment of a number displayed inside the number box. All number cells use a common alignment setting. Changing the alignment will be reflected on all parameters, regardless of selection in the Parameters list.

Notes

•	All settings, except for Number, are shared by all parameters. The Number format is applied to the current selection in the Parameters list.

•	The number format is assigned to the selection in the Parameters list. If the selection is empty, the default number format used for new parameters is defined.

Present

Shows or hides the number box.

Orientation

Choose between horizontal and vertical orientation of the bars. The default is horizontal.

Title

Use this command to change the object title from the Bar Title dialog box.

Background

Use this command to open the Background Area dialog box for changing colors, patterns, etc.

Move Up, Move Down

Use this command to move the selected variables up/down in the Parameters list.

Allow Input

Use this group to indicate whether you want to be able to change the value of the parameter variable during a simulation run.

Note	Changes in the Allow Input group are assigned to the selection in the Parameters list. If the selection is empty, the settings are made for all parameters.

Always

Check Always to enable input whenever a simulation is running or pausing.

On Pause

Check On Pause to enable input only when a simulation is pausing.

Pause on Input

Check this box if you want Powersim to automatically pause a simulation when you click in the object with the mouse. This allows you to easily change parameter values during a simulation run.

Keep Value

Check this box if you want the object to keep the value displayed in the number box when starting a new simulation. See also: Keeping Input Object Values Between Simulation Runs

Note	The Keep Value setting is assigned to the selection in the Parameters list. If the selection is empty, the setting is made for all parameters.

Limit Input

Check this box if you want the slider/bar to reject input values that do not lie within the selected variable's min-max interval. The Limit Input setting is assigned to the selection in the Parameters list. If the selection is empty, the setting is made for all parameters.


Time Graph Object

A time graph displays a two-dimensional graph of one or more variables' development over time. It has Time as the variable along the x-axis, and one or more dependent variables along the y-axis.

See also

  Time Graph Example

  Define Time Graph dialog box

  Graph Drawing dialog box


Time Graph Example

In the time graph below (see XTIMEGRP.SIM), the values of the variables Inventory and Shipments are plotted along the vertical (Y) axis of the graph.


Define Time Graph dialog box

Use this dialog box to change the definition of a time graph object.

Dialog box options

Models

You can choose which models to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Variables

Displays all variable names (scalars) and variable elements (arrays) of the current model, which is normally the main model. To add a variable to the Parameters box, double-click on the variable in the list or select the variable and hit the Add button. Array variables are listed by elements, enabling you to select the elements of an array you wish to add to the Parameters box.

Parameters

Displays the variables that are parameters to the object. To remove a parameter from the list, double-click on the variable or select the parameter and hit the Remove button.

Time graph and time table objects store the simulated values of their parameter variables. These values are displayed provided that the parameters are also included in the Displayed Series list in the Display dialog box (opened by hitting the Display button). Adding a variable to the Parameters list also automatically adds it to the Displayed Series list in the Display dialog box.

Add

Adds selected variables of the Variables list to the Parameters list.

Remove

Removes selected parameters from the Parameters list.

Time (X) Axis, Value (Y) Axis

Use these groups to change the definition of the x- and y-axis.

Axis

Opens the Time (X) Axis dialog box or the Value (Y) Axis dialog box.

Minor Grid, Major Grid

Opens the Minor Grid or Major Grid dialog box.

Grid lines may be put in the background of the time graph. Major grid lines are put at every major unit along the axis, while minor grid lines are put at the minor unit positions along the axis. Major and minor units are defined in the Scale section of the Value (Y) Axis and Time (X) Axis dialog boxes.

Labeled Scales

Check this box to have legends printed next to scaling values on the y-axis. This option may only be selected when View Normalized is chosen since this is the only mode where the time graph object applies different y-axis scalings for the time series displayed.

Drawing

Use this group to change the way selected parameters' values are displayed. The changes made in this group apply to the selected parameters in the Parameters list. If no parameters are selected, the settings apply to all parameters.

Line

Check this button if you want the graphs to be plotted using lines.

Marker

Check this button if you want the graphs to be plotted using markers.

Area

Check this button if you want the graphs to be plotted using filled areas.

Custom

Opens the Graph Drawing dialog box.

Hint 	Different drawing attributes may be set for individual parameters. You may, for example, select one parameter in the Parameters list box and switch on the Marker style, and then select another and give it the Line style.

View

Choose view for graph plots. You can choose among four views. The variables are plotted along the same x-axis in all views. The difference between the views is related to the use of the y-axis, as described below.

Based

All variables are displayed using one common y-axis scaling. The scaling is determined by the settings of the Value (Y) Axis dialog box which you can open by hitting Axis in the Value (Y) Axis group.

Stacked

The variables are plotted using a stacked y-axis scale, where the "bottom line" of each variable is defined by the previously plotted variable. The plotting order is determined by the sorting in the Displayed Series list of the Display dialog box.

Distributed

The variables are plotted using a 100% distribution of the variables on the y-axis.

Normalized

The variables are plotted using their respective y-axis scale settings, and using the x-axis as the "bottom line".

Hint 	If you wish to see the actual min and max values of each plotted variable, check the Legends Scale box (described above). For more details about setting up the legend, see the description of Legend below.

Display

Opens the Display dialog box. It may be used to control which series to be displayed by the current object, the plotting order, copying of time series data to the clipboard, etc.

Graph Area

Opens the Graph Area dialog box, for changing colors, patterns, etc., of the graph area.

Title

Use this command to change the object title from the Title dialog box.

Background

Use this command to customize the background of the number object. It opens the Background Area dialog box for changing colors, patterns, etc.

Generations

Opens the Generations dialog box. Generations are used for holding the results of previous simulations.

Legend

A legend is a key that identifies the series markers in a graph plot. The legend includes each color, pattern, number, or symbol used as a marker, followed by the corresponding variable name.

Legends are placed along the right side of the graph. The plot area is reduced to accommodate the legend. If the legend is removed, the plot area returns to its original size.

Hit the Legend button to open the Graph Legend dialog box for changing legend options.

Gen Legend

Opens the Generations Legend dialog box, for hiding, showing, or customizing legends containing information about generations.

Hi-Lo Lines

Opens a dialog box for choosing the color and style for hi-lo lines in a graph. (See the Line dialog box.) If turned on, hi-lo lines are extended from the highest to the lowest value of each variable. In order to turn high-low lines off, choose None as the style.

Drop Lines

Opens the Drop Line dialog box for choosing the color and style for drop lines in the graph. If turned on, drop lines are extended from each marker to the bottom line (x-axis). In order to turn high-low lines off, choose None as the style.

Save Limit (pts)

Normally the time graph saves data for every parameter at each time step. When the number of time steps is large (small time step and/or large time span), this will require significant amounts of memory (approximately eight bytes per parameter per time step). The value in the Save Limit text box determines the maximum number of points that will be saved for each parameter. By setting it down to 50, for example, a maximum of 50 points will be used when saving parameter values.

Note	Setting down the save limit may cause sudden changes in parameter values to disappear from the graph (for example, pulses).


Graph Drawing
Graph Drawing dialog box

Use this dialog box to customize the line, marker, and area settings of a time graph object.

Dialog box options

Line

Use this group to change the color and the style of the plotted line. You may choose either a fixed or a cyclic color and style. In the latter case, for each displayed time series, the cyclic sequence of line style and line color is changed. The change is done in the following way: The line color is set to the next available color in the color cycle. Each time the line color wraps around, the line style is changed to the next style in the style cycle.

Area

Use this group to change the appearance of a plotted area.

Fill

The settnings in this group refer to the area below the graph, and can be filled according to the settings of the Fill box:

•	None: The interior is not filled at all.

•	Pattern: Pattern, Foreground and Background are available for defining the fill. You may choose either fixed or cyclic pattern and foreground/background colors. If you choose Cycle, for each displayed time series, the cyclic sequence of pattern, background, and foreground is changed. The change is done in the following way: The foreground color is set to the next available color in the color cycle. Each time the foreground color wraps around, the background color is changed to the next color in the color cycle. Each time the background color wraps around, the pattern is changed to the next color in the patter cycle.

•	Solid: A Color button is available for selecting any color to use when filling the graph. Press the Color button to open the Color dialog box.

•	Shade: Makes Shade Style, Color Mixing, From Color and To Color available.

Marker

Use this group to customize the marker.

Type

You may choose among None, Cycle, Number, and a fixed shape marker type.

Border

Choose the border color for the chosen marker type. If Type Number is chosen, this list box is disabled.

Interior

Choose the interior color for the chosen marker type.

Font

Changes the font of the number marker. Opens the Font dialog box.

Hint	All of the attributes found in the Line, Area, and Marker groups of this dialog box may be set to Cycle. The result of the Cycle option is that for each time series displayed by the object Powersim will use different line colors and styles, area patterns and colors, and marker types and colors. The best result will normally be either to set all or none of the attributes to Cycle. If you are working on a color display and you have a black and white printer, Cyclic graph drawing gives a good result both on screen and printer.


Time Table Object

A time table presents the time series history of certain variables, in columns or rows.

See also

  Time Table Example

  Define Time Table dialog box


Time Table Example

The time table below (see XTIMETBL.SIM) displays the history of the variables Balance and Interest.


Define Time Table dialog box

Use this dialog box to define a time table object.

Dialog box options

Models

You can choose which models to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Variables

Displays all variable names (scalars) and variable elements (arrays) of the current model, which is normally the main model. To add a variable to the Parameters box, double-click on the variable in the list or select the variable and hit the Add button. Array variables are listed by elements, enabling you to select the elements of an array you wish to add to the Parameters box.

Parameters

Displays the variables that are parameters to the object. To remove a parameter from the list, double-click on the variable or select the parameter and hit the Remove button.

Time graph and time table objects store the simulated values of their parameter variables. These values are displayed provided that the parameters are also included in the Displayed Series list in the Display dialog box (opened by hitting the Display button). Adding a variable to the Parameters list also automatically adds it to the Displayed Series list in the Display dialog box.

Add

Adds selected variables of the Variables list to the Parameters list.

Remove

Removes selected parameters from the Parameters list.

Times

Use this group to change the time settings of the table object. If you check Auto, the table will follow the simulation setup, that is, the Start Time, Stop Time, and Time Step settings in the Simulation Setup dialog box will be used.

From

The first time the table reports values.

To

The last time the table reports values.

Step

The time between each stored and reported value.

Note	A table may contain interpolated values, for example, if a simulation has a time step of 1.0 and the Step size of the Times group is set to 0.5, every other cell of the table will contain an interpolated value.

Column Widths

Use this group to change the column widths of the time table object. Type or select values for the following columns widths, or check Auto to apply default settings:

Time

Width of the leftmost column.

Par

Width of the column of the selected parameters when Orientation Horizontal is chosen.

Num

Column width used for cells containing numbers when Orientation Vertical is chosen.

Labels

Use this group to change the text contents of the time and parameter labels of the table (see figure below).

Ins Field

Use this command to insert a field in the Parameter text box. Hit the button to open the Field dialog box.

Time

To change the time labels, type a new text string in this text box.

Parameter

To change the parameter labels, type a new text string and/or insert field codes in this text box.

Orientation

Choose between horizontal and vertical listing of the parameter values of the time table object. If values are displayed in rows, the orientation is said to be horizontal. Correspondingly the orientation is vertical if values are displayed in columns.

Horizontal (default)

The parameter variables are listed in columns from left to right with the simulated values listed downwards in rows.

Vertical

The parameter variables are listed downwards in rows with the values listed in columns from left to right, one column for each successive time step.

Display

Opens the Display dialog box. It may be used to control which series to be displayed by the current object, the plotting order, copying of time series data to the clipboard, etc.

Title

Use this command to change the object title. It opens a dialog box (Time Table Title) for editing a text item.

Background

Use this command to customize the background of the time table object. It opens the Background Area dialog box for changing colors, patterns, etc.

Generations

Opens the Generations dialog box. Generations are used for holding the results of previous simulations.

Gen Legend

Opens the Generations Legend dialog box, for hiding, showing, or customizing legends containing information about generations.

Cell Format

Use this button to format the table cells by making selections in the associated pop-up menu. The options are as follows:

•	Label: Opens a cascading menu for parameter names and the time labels. Click on Font to change the font used in the label texts of the time table (opens the Font dialog box), and click on Alignment to choose between left, center and right alignment of label cells.

•	Number: Opens a cascading menu for formatting parameter and time values. Click on Font to change the font used in the numbers of the time table (opens the Font dialog box).Click on Value Format to define the value format of current selection in the Parameters list. If no parameters are selected, the default for new parameters is set. Click on Time Format to define the format of the time values. Click on Alignment to choose between left, center and right alignment of value cells.

•	Grid: Opens a cascading menu for formatting major and minor grid. Major Grid opens the Parameters Separators dialog box for changing color and style for the grid used to separate parameters. Minor Grid opens the Time Separators dialog box for changing color and style for the grid used to separate the time part of the table and the parameter variables.

•	Background: Opens the Table Area dialog box, for changing colors, patterns, etc., of the table area.


Static Objects

You can use static objects to customize simulators, draw causal-loop diagrams, and provide various kinds of information using text and graphics. The term "static" indicates that the appearance of the objects is not affected by simulation results, as it is for dynamic objects.

Name	Function
Text	Displays text in the diagram workspace
Frame	Draws a frame in the diagram workspace
Picture	Displays a picture in the diagram workspace
Line	Draws a line in the diagram workspace


Text Object

A text object displays its text contents within a chosen shape in the diagram. Double-click on a text object to change its contents and format.

See also

  Text example

  Define Text dialog box

  Direct text editing


Text example

The text object below is found in XTEXT.SIM.

As an example, let us edit the text object displaying the text "Market Sector".

To edit a text directly

1	Select the text object, and click inside the text [image].

2	A frame will be drawn around the text. You can now enter the new text directly into the object.

3	Hit Return to end text entry. (You can hit Esc to cancel editing.) Windows 3.x and 95 users can also click outside the text frame to end the edit operation. To force a new line inside the text frame, hit Ctrl + Return.

As you type into a direct text entry frame, the frame will expand to enclose the text you enter. You can start a new line by pressing Return. When clicking outside the text frame, the object containing the text will be reformatted. If the text should disappear in full or in part, you may have entered a text that is too big for the object. Try enlarging the object by dragging one of its sizing handles.

For text objects it is possible to switch on Adjust object size to fit text. This is useful if you want the text frame to enclose the text exactly, or if you do not want the text to have a frame at all.


Define Text dialog box

Use this dialog box to define a text object.

Dialog box options

Text

Use this text box to specify the contents of the text output. A text specification may contain text and field codes (if the Ins Field button is enabled).

Adjust object size to fit text

When you check this box, the object will be resized to enclose the contained text exactly.

Hint	You should switch on this setting for text objects representing variable names of causal loop diagrams.

Insert Field

Use this command to insert a field that controls the insertion of text or numbers. The field you select is inserted at the text marker of the Text box. When you hit the button, the Field dialog box opens. Available fields depend on the particular text item you are editing.

Border

Use this group to change the color and style of the text border.

Shape

Use this combo box to choose among 16 basic shapes (see figure below).

Use the buttons at the bottom of the dialog box ( [image] [image] [image] [image]) to rotate and flip the shape you selected.

Interior

Use this group to change the filling of the interior.

Fill

You can fill the interior according to the settings of the Fill box:

•	Select None if you do not want to fill the interior at all.

•	Select Pattern to choose among Pattern, Foreground, and Background to define the fill.

•	Select Solid to make a Color button available to choose a color to use when filling. Press the Color button to open the Color dialog box.

•	Select Shade to choose among Shade Style, Color Mixing, From Color, and To Color.

Font

Click this button to open the Font dialog box and change the text font.

Layout

Click this button to open the Text Layout dialog box and change the orientation and alignment settings for the text.

Shade

Use this check box to switch shaded border on or off.


Frame Object

A frame object draws a rectangular or oval frame in the diagram. Double-click on a frame object to change its formatting.

See also

  Frame example

  Define Frame dialog box


Frame example

The frame object below is found in XFRAME.SIM.


Define Frame dialog box

Use this dialog box to define a frame object.

Dialog box options

Border

Use this group to change the color, style, and shape of the border. To turn border off, choose None as the style. You may choose rectangle, round rectangle, or oval shapes.

Interior

Use this group to change the filling, pattern, foreground color, and background color.

Hint	The interior of a graph refers to the area below the graph and can be filled according to the settings of the Fill box.

Fill

Use the Fill box to select how to fill the active object or item.

•	Select None if you do not want to fill the interior at all.

•	Select Pattern to choose among Pattern, Foreground, and Background to define the fill.

•	Select Solid to make a Color button available to choose a color to use when filling the graph. Press the Color button to open a standard dialog box to choose a color (see Color dialog box).

•	Select Shade to choose among Shade Style, Color Mixing, From Color, and To Color.

Shape

Use this combo box to choose among 16 basic shapes (see figure below).

Use the buttons at the bottom of the dialog box ( [image] [image] [image] [image]) to rotate and flip the shape you selected.

Shade

Use this check box to switch shaded border on or off.


Picture Object

 A picture object displays a picture in the diagram. To transfer an image to the picture object, you must first put the image on the clipboard (for example, copy it from a painting program). Then you can paste it into the picture object from within the Define Picture dialog box.

See also

  Picture example

  Define Picture dialog box


Picture example

The picture object below is found in XPICTURE.SIM.


Define Picture dialog box

Use this dialog box to change the definition of a picture object.

Dialog box options

Current Picture Type

This field displays the type of the picture currently displayed by the object.

Scale To

Enter a percentage to scale the selected object. A number greater than 100 will enlarge the object. A number less than 100 will reduce the object.

Relative to Original Size

If this box is checked, the picture will be scaled relative to the original size of the picture. If it is not checked, the picture will be scaled relative to the current size of the picture object.

Hint 	Scaling relative to the original size will restore the correct aspect ratio of a picture that has been previously resized and had its aspect ratio changed.

Display Picture

Use this check box to show or hide the picture.

Background

Use this command to customize the background of the picture object. It opens the Picture Background dialog box to change colors, patterns, etc.

Paste

Click this button to paste the clipboard contents to the picture object according to the chosen Paste Type (see below).

Paste as Type

You can choose what picture type you want to paste. Use the clipboard to define the contents of the picture object. Powersim accepts pictures in three formats:

•	Picture

•	DIB Bitmap

•	Bitmap

Most Windows applications produce one or more of these formats when copying information to the clipboard. When more than one format is available, the following information will assist you in selecting the appropriate format.

Picture

This is a Windows Metafile, that is, a set of drawing commands that will produce a graphical output when executed. Pictures in this format have the advantage that they may be scaled arbitrarily without loss of quality. The Metafile format normally requires less memory space than the other two formats.

DIB Bitmap

This is a Windows device independent bitmap (DIB), which holds colored pixel values of a picture. Bitmaps have the disadvantages of large memory requirements and loss of picture quality when scaled to a resolution different from the original.

Bitmap

This format is in the old Windows device dependent bitmap (DDB) form. Avoid using it if a DIB bitmap is available. DDB bitmaps do not store size in metric units and do not contain a picture palette. The result of displaying a DDB bitmap is therefore not likely to be correct on a printer or on another display type (for example, after a change from VGA to XGA).


Line Object

A line object draws a straight or curved line in a diagram.

See also

  Line example

  Define Line dialog box


Line example

The line object below is found in XLINE.SIM.


Define Line dialog box

Use this dialog box to define line objects. These objects may be used, for example, to draw causal loop diagrams.

Dialog box options

Arrow Heads

Choose this for the line. You can choose among left, right, double, and no arrow.

Shape

Choose either line (straight) or curve shape. If you choose curve,  you can edit the line as a Bézier curve.

Color

Choose this to display the line color.

Head, Tail

Click these buttons to change the text contents of the arrow head and tail labels. They open the Head/Tail Label dialog box to edit a text item.

Delay Mark

If this box is checked, two small lines are drawn across the line. They denote a delayed influence in conventional causal loop diagrams.


Transfer Objects

Transfer objects facilitate transfer of information between model variables and variables of other models, external files, and other applictions.

Name	Description
Archive	Connects simulation to external data file
DDE	Dynamic Data Exchange with other applications
Chain	Creates variable connections between main- and co-models
Network Game	Manages multi-user simulation games in a network environment
Note	Only constants can be used as the destination parameter in transfer objects.


Archive Object

The Archive object is used to transfer parameter values to or from external files. Both single values and time series can be transferred.

Examples of uses include:

•	Initializing variables with data stored in file

•	Loading data for variables from external time series during simulation

•	Saving parameters to file

•	Saving time series to file

Hint	You may define a variable using historical data by importing a time series from a file. Simulation results may be exported in order to make statistical analysis and comparisons with collected data.

See also

  Archive example

  Define Archive dialog box

  Commom Description of Archive and DDE objects


Archive example

The archive object depicted below (see XARCHIVE.SIM.) is used to save time series to a file.


Define Archive dialog box

Use this dialog box to define an archive object.

Dialog box options

Models

You can choose which models to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Variables

Displays all variable names (scalars) and variable elements (arrays) of the current model, which is normally the main model. To add a variable to the Parameters box, double-click on the variable in the list or select the variable and hit the Add button. Array variables are listed by elements, enabling you to select the elements of an array you wish to add to the Parameters box.

Parameters

Displays the variables that are parameters to the object. To remove a parameter from the list, double-click on the variable or select the parameter and hit the Remove button.

Add

Adds selected variables of the Variables list to the Parameters list.

Remove

Removes selected parameters from the Parameters list.

Move Up, Move Down

Moves the selected variables up/down in the Parameters list.

Transfer

Use this combo box to choose between import (From File) and export (To File) of data. From File means that data will be loaded from an external file, and used to set the values of the parameters of the Parameters list box. To File is used to transfer parameter values to an external file.

Orientation

Data may be oriented either horizontally or vertically. If data for a parameter is stored in one row, the orientation is said to be horizontal. Correspondingly the orientation is vertical if parameter values are stored in columns.

Column Separator

This combo box may be used to choose between different ways of separating columns within the data set.

Line Terminator

This setting determines how lines of the data set will be terminated. The system will interpret imported data in a liberal way, allowing the system to recognize text lines independently of the line terminator setting.

Numerical Format

Different countries and computer programs operate with varying decimal and thousands separators when representing numbers as text. Use this box to choose the appropriate format for your data.

Update

Use this button to transfer data according to the current settings of the dialog box. If From File is selected as Transfer type, data will be loaded into the object. The list of Parameters will be updated if Parameter Names is turned on. If Transfer Times is on and Time Values is off, the value of Step will be updated.

Insert Field

The run number (see Run Setup) may be used as part of the file name of the File dialog box. This makes it possible to store data from different runs in different files. As an example, the file name DATA{RUN}.TXT will store data for a simulation with multiple runs in the files DATA1.TXT, DATA2.TXT, etc.

Browse

This button will open a dialog box for selecting a file name for the File edit box.

File

Enter the name of a file in this text box. You may use the Browse button to look up existing files.

Times

This group is enabled only when transferring time series, that is, when the Series radio button is switched on. The settings are used to determine the times associated with the data in a time series.

From, To

Determines the time associated with the first and last value of each time series.

When exporting data, you should normally select Auto for From and To. The same is true when importing with Transfer Times switched off.

If both Transfer Times and Headers are switched on, times will be read from the imported data. The entire Times group will therefore be disabled.

Step

This setting determines the interval between successive data points in the time series.

If the current simulation contains a large number of time steps, you may want to increase the value of Step from its Auto value to a larger number in order to reduce the number of values in the generated time series.

Include

Transferred data may contain headers for each time series, and an additional series holding the associated time values.

Headers

Turn this switch on if headers are part of the transferred data. If Headers is on during export, Powersim will add parameter names to the exported time series. Importing data with Headers turned on, causes Powersim to treat the first item of each imported time series as the name of that series. Together with the Parameter Names switch this can be used to extract parameter names from the imported file.

Time Values

Time values may be part of the transferred data set as an initial time series. During export, this switch determines whether or not the data will include an extra parameter holding the times associated with the data. When importing data with time values present, you should switch on the Time Values switch. If both Transfer Times and Time Values are switched on, timings will be taken from the imported file. If Transfer Times is on and Time Values off, Powersim will disregard the time values that are stored in the imported data set (the first time series will be skipped).

From Source

This group determines how to interpret parameter names (headings) and time values when importing data (The group is disabled during export.)

Parameter Names

This switch is enabled only if Headers is turned on. If Parameter Names is on, Powersim will read the names of each time series from the imported data, and associate each series with the corresponding variable or array element of the current simulation model. This will override (replace) the list of parameters in the Parameters list box. With Parameter Names switched on, you may press Update in order to import the associated data, and have the system fill the Parameters list with the names of time series that are present in the external data set.

Transfer Times

This switch will be disabled for export, and when Single is checked. When switched on, this setting causes Powersim to use information from the imported data to interpret the timings of imported data series.

If Time Values is also on, actual times of imported values will be taken from the external data set and the Times group will be disabled.

Values

Data may be transferred either as single values or time series.

Single

If Single is selected, only one value will be transferred for each parameter during the entire simulation.

Series

If Series is selected, several values will be present for each parameter. Each value holds the value of the associated parameter at a given point in time. Several other settings are enabled only for Series, for example, Times and Transfer Times.


DDE Object

The DDE protocol allows for flexible and powerful transfer of data between applications. You can use the DDE object for several purposes, including:

•	Retrieval of parameter values from external applications (for example, spreadsheets)

•	Monitoring external events (for example, through programs supporting analog/digital input)

•	Controlling external devices (for example, through programs supporting analog/digital output)

•	Visualizing variable values through external applications (for example, charting programs)

•	Exporting data to external applications for analysis or storage (for example, statistical programs)

Note	The same options as described for the archive object are relevant for DDE transfers.

See also

  Setting up DDE

  DDE example

  Define DDE dialog box

  Synchronization of DDE Transactions

  Common Properties of Archive and DDE objects


DDE example

The DDE object depicted below (see XDDE.SIM.) is used to import parameter values from another application.

In the example above, the following lines have been entered in the Service, Topic and Item fields of the Define DDE dialog box:

In the Service field, the name of the application is given. For Microsoft Excel, the service name is EXCEL.EXE. Pathname should not be entered, provided that the programs path is included in the systems PATH variable (refer to Setting up DDE). To open Excel without opening a workbook, the parameter /e can be given.

In the Topic field, the filename of the workbook is given. Note that Excel does not support pathnames, and this is therefore omitted. If the output data is to be sent to a specific sheet in the workbook, the name of this sheet must be supplied after the filename, as shown below:

In the Item name, a cell reference in Excel may be specified. In the above example, a cell reference named Yearly_Interest_Rates has been created in Microsoft Excel, from which Powersim will collect data for the simulation.

See also

  Setting up DDE


Setting up DDE

The DDE Object provides an easy way of exchanging data between different applications. To make it easier to use, we will in the following discuss how to connect to other applications from Powersim.

The application Powersim is connecting to, is called the server application.

At the bottom of the Define DDE dialog box there are three fields: Service, Topic and Item. These fields are used by Powersim when connecting to a server application. In this section, only these three fields will be discussed.

The Service field

There are three ways Powersim can connect to a server application:

1.	Powersim tries to locate the program in the folders listed in the PATH-variable (recommended).

2.	Powersim tries to execute a given command string (containing path and program information) (not recommended).

3.	Powersim tries to locate the program using the Registry Database (Windows 95 and Windows NT4.0 only) (not recommended).

We will in the following look at these three methods separately.

Method 1: Locate program in PATH-folders (recommended)

This method requires that the folder in which the program lies, is added to the PATH variable. How to do this is dependent on what operating system you are using:

Windows NT4.0:

1.	Start Control Panel.

2.	Select System.

3.	Select the Environment tab.

4.	Add the PATH variable, or edit it if it exists. The variable should contain the path to the server application, using short filenames only. When youre finished, click the OK-button. (NB! The total length of the PATH variable must not exceed 256 characters!)

5.	Restart the computer.

Windows 3.x, 95:

1.	Start Notepad (or another text editor).

2.	Open the C:\Autoexec.bat file.

3.	Scroll down to the declaration of the PATH variable.

4.	Edit the PATH line, so that it contains the path to the server application, using only short filenames. (NB! The total length of the PATH variable must not exceed 256 characters!)

5.	Save the Autoexec.bat file, and restart the computer.

When this is done, the only thing that must be entered into the Service field in the Define DDE dialog box, is the name of the application, and its startup parameters.

For Microsoft Excel, the Service field would look like this:

For Microsoft Access, the Service field would look like this:

Observe the startup parameter /NOSTARTUP. This parameter forces MsAccess to start without opening the Open File Wizard.

Method 2: Executing a command string (not recommended)

To connect to the server application this way, the path of the program must be entered into the Service field. This is a very fragile way of programming it, as it requires that the programs must be installed on the same path on all the computers that are going to run the model. Also, the path must be given using short file names. For Microsoft Excel, the Service field could look like this:

Method 3: Locating the program from the Registry (not recommended)

This method requires that the program is installed to a path containing only short filenames, or that the information stored in the Registry contains only short filenames. An advantage by using this method, is that the startup parameters are found in the Registry. For Microsoft Excel, the Service field would look like this:

The Topic field

This field must contain a legal topic for the server application, and this may vary between the different server applications. Usually, information about this field can be found in the server applications on-line help system, by searching the keyword DDE Server. Its common that parts of the Topic field contains reference to a file.

To connect to Microsoft Excel v7.0, it is possible to refer to the file in several ways:

1.	The file can be referred to without a path, which means that it is stored in the same folder as the model.

2.	The file can be referred to using a path relative to the path the model is saved.
Examples:
..\XLOutPut\[filename.xls]MySheet 	refers to a folder on the same level as the model folder,
XLOutPut\[filename.xls]MySheet refers to a subfolder of the model folder.

3.	The file can be referred to using an exact path, e.g., C:\MyWork\XlOutPut\\[filename.xls]MySheet. (not recommended).

Note! Microsoft Excel uses Workbooks, and the the sheets inside the Workbook must therefore be referred to like this: [filename.xls]MySheet. If a no reference to sheetname is given, Excel defaults the sheet to sheet1.

The Item field

This field must contain a legal item for the server application, and this may vary between the different server applications. Usually, information about this field can be found in the server applications on-line help system, by searching the keyword DDE Server.

In Microsoft Excel, the Item field can be used to transfer information cell ranges and named ranges. The Item field could look like this:

(refers to a cell range in the worksheet)

(refers to a named range in the worksheet)

See also

  DDE example


Define DDE dialog box

Use this dialog box to define a DDE object.

Note	From Powersim's point of view the transfer of data to and from files are very much the same as transferring data to or from other applications using DDE. The dialog box for defining a DDE object is therefore very similar to the archive object.

Dialog box options

Models

You can choose which models to draw variables from. The Model list contains the main model, any co-models, and the Control meta co-model.

Variables

Displays all variable names (scalars) and variable elements (arrays) of the current model, which is normally the main model. To add a variable to the Parameters box, double-click on the variable in the list or select the variable and hit the Add button. Array variables are listed by elements, enabling you to select the elements of an array you wish to add to the Parameters box.

Parameters

Displays the variables that are parameters to the object. To remove a parameter from the list, double-click on the variable or select the parameter and hit the Remove button.

Add

Adds selected variables of the Variables list to the Parameters list.

Remove

Removes selected parameters from the Parameters list.

Move Up, Move Down

Moves the selected variables up/down in the Parameters list.

Transfer

Use this combo box to choose between import (From Application) and export (To Application). From Application means that data will be loaded from an external application, and used to set the values of the parameters of the Parameters list box. To Application is used to transfer parameter values to an external application.

Orientation

Data may be oriented either horizontally or vertically. If data for a parameter is stored in one row, the orientation is said to be horizontal. Correspondingly the orientation is vertical if parameter values are stored in columns.

Column Separator

This combo box may be used to choose between different ways of separating columns within the data set.

Line Terminator

This setting determines how lines of the data set will be terminated. The system will interpret imported data in a liberal way, allowing the system to recognize text lines independently of the line terminator setting.

Numerical Format

Different countries and computer programs operate with varying decimal and thousands separators when representing numbers as text. Use this box to choose the appropriate format for your data.

Service

Enter the name of a DDE service in this text box. Service names are normally the names of DDE source (server) application program files. Examples include:

Application	Server Name
Microsoft Excel	EXCEL.EXE
Microsoft Word	WINWORD.EXE
Lotus 123	123W.EXE
Topic

Enter the name of a DDE topic in this text box. Topic names are normally file names used by the DDE source application (server) named in the Service edit box when referring to data.

Item

You don't need to specify an item name for all DDE transactions. When used, the item name normally identifies a piece of data inside the document defined by Topic. As an example Excel accepts cell references as item names, while Microsoft Word accepts bookmarks.

Automatic

This check box will be enabled only when Single is checked. If Automatic is on, data will be transferred whenever a source value changes. Otherwise data will be transferred only at the onset of the simulation, and when the Update button is pressed.

Times

This group is enabled only when transferring time series, that is, when the Series radio button is switched on. The settings are used to determine the times associated with the data in a time series.

From, To

Determines the time associated with the first and last value of each time series.

When exporting data, you should normally select Auto for From and To. The same is true when importing with Transfer Times switched off.

If both Transfer Times and Headers are switched on, times will be read from the imported data. The entire Times group will therefore be disabled.

Step

This setting determines the interval between successive data points in the time series.

If the current simulation contains a large number of time steps, you may want to increase the value of Step from its Auto value to a larger number in order to reduce the number of values in the generated time series.

Include

Transferred data may contain headers for each time series, and an additional series holding the associated time values.

Headers

Turn this switch on if headers are part of the transferred data. If Headers is on during export, Powersim will add parameter names to the exported time series. Importing data with Headers turned on, causes Powersim to treat the first item of each imported time series as the name of that series. Together with the Parameter Names switch this can be used to extract parameter names from the imported file.

Time Values

Time values may be part of the transferred data set as an initial time series. During export, this switch determines whether or not the data will include an extra parameter holding the times associated with the data. When importing data with time values present, you should switch on the Time Values switch. If both Transfer Times and Time Values are switched on, timings will be taken from the imported file. If Transfer Times is off and Time Values on, Powersim will disregard the time values that are stored in the imported data set (the first time series will be skipped).

From Source

This group determines how to interpret parameter names (headings) and time values when importing data (The group is disabled during export.)

Parameter Names

This switch is enabled only if Headers is turned on. If Parameter Names is on, Powersim will read the names of each time series from the imported data, and associate each series with the corresponding variable or array element of the current simulation model. This will override (replace) the list of parameters in the Parameters list box. With Parameter Names switched on, you may press Update in order to import the associated data, and have the system fill the Parameters list with the names of time series that are present in the external data set.

Transfer Times

This switch will be disabled for export, and when Single is checked. When switched on, this setting causes Powersim to use information from the imported data to interpret the timings of imported data series.

If Time Values is also on, actual times of imported values will be taken from the external data set and the Times group will be disabled.

Values

Data may be transferred either as single values or time series.

Single

If Single is selected, only one value will be transferred for each parameter during the entire simulation.

Series

If Series is selected, several values will be present for each parameter. Each value holds the value of the associated parameter at a given point in time. Several other settings are enabled only for Series, for example, Times and Transfer Times.


Synchronization of DDE Transactions

Use the DDE object to set up a DDE transaction where Powersim acts as a DDE client application. This means that Powersim may send or retrieve numerical data to or from applications that can act as DDE servers. Both single values and time series may be transferred.

Transfering Time Series

When a time series is transferred to an external application, the transfer will take place when the simulation is complete. (At this point the entire time series for a variable will be known, and possible to transfer to the server application.) When importing a time series from an external application, the transfer takes place at the onset of the simulation.

Transfering Single Values

Single value transfers will take place at the onset of the simulation for import, and at the end of the simulation for export. If automatic transfer is selected, values will be transferred between simulation steps. In the case of export (to another application) values will be transferred only if the value of the source Powersim parameter has changed. In the case of import (from another application) values will be updated between simulation steps whenever Powersim gets informed by the server application that an imported value has changed in the server application.

Table Listing Synchronization of Powersim and Server Application

Transaction	Onset of simulation	At end of each step	End of simulation
Import of time series and non-automatic single values	Transfer	No transfer	No transfer
Export of time series and non-automatic single values	No transfer	No transfer	Transfer
Automatic import of single values	Transfer	Transfer if external value has changed	No transfer
Automatic export of single values	Transfer	Transfer if Powersim parameter has changed	No transfer
Time Delay of One Time Step at One-Way Data Transfer

The fact that automatic transfer of single values takes place at the end of each simulation step, causes a delay of one time step between the source and the destination. As an example, if a Powersim auxiliary variable is defined equal to TIME, and its value is transferred to another application, the value observed by the receiving application will be equal to TIME - TIMESTEP during the simulation.

Time Delay of Two Time Steps at Two-Way Data Transfer

In some cases you may wish to use another application, such as a spreadsheet, to perform a calculation based on the value of a Powersim variable, and read the calculated result back into another Powersim variable. To create such a feedback between Powersim and a DDE server application you need to use two different DDE objects, one for the export and one for the import. Note, however, that such a transaction will imply a delay of two time steps between the export from Powersim and the corresponding response from the server. As an example, if TIME is exported to another application and imported back into Powersim, the imported value will be equal to TIME-2*TIMESTEP during the simulation. (During the two first time steps, the imported values will be independent of the exported values.)


Description of Archive and DDE objects
Common Properties of Archive and DDE objects

Since these two object types have many properties in common, we will describe these properties in a section that addresses both objects.

Data Format

Powersim uses Archive or DDE files in text format. You can use the options of the Define Archive or DDE dialog boxes to tailor the text format to most needs. In particular, the format may easily be defined in ways that allow for import and export to most spreadsheet programs, databases, word processors, and statistical packages.

Time Series or Single Values

Data can be stored either as single values or as time series. In the first case, only one value will be stored for each parameter (scalar variable or array element). Time series are used to store values of variables at different points in time.

Orientation

If more than one parameter is transferred at a time, or if a time series is transferred, it is important to know if data is stored in rows or in columns. Vertical orientation means that data for a parameter is stored vertically in one column, while horizontal orientation means that data for each parameter is stored in one row. See figures below:

Vertical Orientation

Horizontal Orientation

Headers

Parameter data may be stored as values only, or accompanied by headers. In the figure above, data are stored with headers. The two next figures show the same data without headers.

Vertical Orientation without Headers

Horizontal Orientation without Headers

Vertical Orientation with Headers and Times

Horizontal Orientation with Headers and Times

Times

When transferring time series, the time values associated with the data of a series may be transferred along with the parameter values. The figures above display a data set with both times and titles turned on.

The time values are stored as an initial first parameter. The title of the time value series is taken from the Simulate Simulation Setup Time Unit combo box, and has a default value of "TIME".

Numerical Format

Numbers may be stored in different formats, as in the Format Options General Numerical Format combo box. Since different Archive or DDE objects may operate with different formats, the numerical format option may be set individually for each Archive or DDE object.

Column Separator

As you have seen in the examples above, Archive or DDE texts can be split into several columns. The default column separator is the TAB character (Tabulator, ASCII character 9). The set of legal column separators are listed below.

•	space

•	tab

•	semicolon

•	period

•	comma

When loading an Archive or DDE, several consecutive column separators will be considered as one separator.

Line Terminator

Transferred data may contain more than one line of text. The default way of terminating each line is by adding the CR (Carriage Return, ASCII character number 13) character followed by the LF (Line Feed, ASCII character number 10) character to the text in the line. The set of legal line terminators are listed below.

•	LF

•	CF

•	CR-LF

When loading an Archive or DDE, Powersim will treat any combination of CR and/or LF as a valid line termination sequence. The choice of Line Terminator is therefore mainly of interest when storing data into an Archive or DDE file.

Time of Archive Transfer

When importing from an Archive, data is transferred at the start of the simulation. When exporting data, the Archive file is updated at the end of the simulation. In addition, the Update button of the Define Archive dialog box may be used to transfer data manually.

Time of DDE Transfer

Transfer of Time Series

When importing time series from other applications, data is transferred at the start of the simulation. When exporting time series, data is transferred at the end of the simulation. In addition the Update button of the Define DDE dialog box may be used to transfer data manually.

Transfer of Single Values

When single values are transferred, the DDE object will transfer data whenever a source value is changed. For export, this means that whenever a source parameter gets a new value during simulation, the DDE object will poke the updated set of data into the connected DDE source (server application). For import, the values of the parameters of the DDE object will be updated whenever Powersim gets a new set of data from the connected DDE source (server application).

This automatic transfer of data may be switched off by turning the Automatic check box off. Data will then be transferred only when the simulation begins (and when the Update button is pushed).

Specifying the Time Series

When time series are specified (as opposed to single values) several values will be stored for each parameter (scalar variable or array element).

When exporting data, the sequence of times used to determine when to store parameter values is determined by the following three settings:

Setting	Explanation
From	Time of first set of values
To	Time of final set of values
Step	Time interval between successive data sets
When importing data, the times associated with the different sets of parameter values can be determined in two different ways. The first alternative is identical to the export case above. Alternatively, if time values are stored along with the imported data, Powersim can use this information to determine the times of each individual set of parameter values in the data set. The latter method also allows for unequally spaced timings for imported time series.

If times are not stored along with the imported data, Powersim can calculate time values by distributing the imported time series over the specified time range. Powersim uses the following equation to determine the time step:

Step = (To - From) / Points

where Points is the number of points in the imported time series. From and To are given by the user, and will normally be set equal to the start time and the stop time of the simulation, respectively.

Specifying Parameters

Explicit Specification

When exporting data, the user must specify the list of parameters whose values are to be exported by the object.

Implicit Specification

In the import case, the user has the option of letting the system read parameter names from the imported data set. This requires that the imported data set contains headers that are names of scalar variables or array variable elements of the model.


Chain Object

Chain objects represent variable connections between co-models.

See also

  Chain Example

  Define Chain dialog box

  Co-Models


Chain Example

The chain object depicted below (see XCHAIN.SIM.) is used to import a parameter value from an co-model.


Define Chain dialog box

Use this dialog box to define a chain object.

Dialog box options

Source, Destination

Use these groups to choose the source and the target for the transfer of variable values.

Model

You can choose which model to draw variables from. The Model list contains the main model and all co-models.

Parameter

You can choose a variable or array element to become source or destination of the chain connection.

Label

Use this command to change the object title. It opens the Chain Label dialog box for editing a text item.


Network Game Object

The network game object allows you to create simulation games that may be run in a network environment, involving up to ten competing players or groups of players. The object is particularly useful in creating management games and competitive/co-operative classroom simulations.

Games based on the use of the network game object are continuous simulation models which are run concurrently on several computers. At fixed points in time, the simulators pause, and the players are allowed to make decisions.

The network game object allows the user to test out decisions and make assumptions about the competitors before making the final decisions at each decision point in the game. This allows the players to perform scenario planning and investigate strategies at each decision point during a game session.

The network game object is designed in a way that makes the resulting games completely independent of network architecture. The only requirement is that each personal computer in the network must have read/write access to a shared disk.

See also

  Define Network Game dialog box

  Edit Player File dialog box

  Game File and Player>howto

  Edit Game File

  Creating Multi-User Network Simulation Games in Powersim


Define Network Game dialog box

Use this dialog box to define a network game object.

Dialog box options

Player File (on Local Disk)

Use this group to select, delete, or edit a player file.

Name

The network game object must specify the name of a player file with key information about the player (group) and the available game set-ups that a player may choose from when starting a game. As a convention, PSN (Powersim Node) is used as a file name extension for player files. You may type in the name of a player file, or use the Browse button to select an existing file.

Browse

This button will open a dialog box for selecting a file name for the Name edit box.

Delete File

Use this button if you want to delete a player file that is no longer in use. The file named in the Name edit box will be deleted. (Alternatively you can of course delete a file using File Manager, Windows Explorer, or a DOS command.)

Edit File

Use this button to create or edit a player file. A player file may also be edited using a standard text editor, for example, NOTEPAD. It is, however, much more convenient to use the built-in player file editor of the network game object.


Edit Player File dialog box

Use this dialog box to edit a player file.

A player file lists one or more game files defining game set-ups available to the player of this game. One game file may, for example, define a set-up where the player is playing against the computer. Another may define a set-up for playing against another player.

Dialog box options

Player and Game Set-up File

This list box holds the game set-ups that are available to this player. The first column of the list holds a player number, and the second column the file name of the associated game set-up.

Add

Adds a new player/game set-up pair to the list box. The Game File and Player dialog box is opened for specifying player number and game set-up.

Remove

Removes the selected entry of the list box. You will be asked if the associated game set-up file should also be deleted.

Edit

Use this button to alter the contents of the selected entry in the list box. The same dialog box as for the Add button is opened, and initialized with the current selection in the list box.


Game File and Player

Use this dialog box to specify game file and player number.

Dialog box options

Game File (on Shared Disk)

This group holds name of a game file along with buttons for selecting and editing a game file.

Name

This text box holds the name of a game file. The name may be typed directly into the text box, or you may press the Browse button to select a file.

Browse

This button will open a dialog box for selecting a file name for the Name edit box.

Edit File

Use this button to create or edit a game file. A game file may also be edited using a standard text editor, for example, NOTEPAD. It is, however, much more convenient to use the built-in game file editor of the network game object.

Player

Enter the player number here. Player number zero (0) is assigned to observers to the game (e.g., the game administrator). Players participating in the game have numbers ranging from one (1) and up. All participants of a game must have unique player numbers.


Edit Game File

Use this dialog box to edit a game file.

Dialog box options

Name of Game

The name of the game set-up is entered in this text box.

Player/Decision Parameter

List of player numbers and decision parameters that the players can change.

Add

Opens the Decision Parameter dialog box for adding a new decision parameter to the Decision Parameters Mask list box. Type in the name in the edit field of the Decision Parameter combo box or select a parameter from the associated drop-down list. Select player (or All) from the Player combo box.

Remove

Remove the selected parameter(s) from the Player/Decision Parameter list box.

Period

Enter the time between decisions when playing the game. The time is measured in terms of the simulation time unit.

Decision Files Mask

Decisions are stored by the network game object in files on a shared disk (network file server). (If you are playing against the computer only, the decisions files can reside on the local computer.) Each player has his own decision file. Decision file names are equal for all players, except for the player number which must be part of the file name. Enter %d in the place of the player number when typing in the name of the Decision Files Mask. Example: g:\games\mygame%d.txt.

Remove

Remove all files with names matching the text in the Decision Files Mask edit box.

Initialization of Game

Parameters to the game (i.e., values of constant variables or initial values of levels) may be set from the game set-up file by adding entries to this list box.

Add

Opens the Game Initialization dialog box for adding a new entry to the Initialization of Game list box. Select parameter from the Parameter combo box and type in initial value in the Value text box.

Remove

Remove selected parameters from the Initialization of Game list box.

Edit

Change the name and/or value of the current entry in the Initialization of Game list box.

Set

Use this button to parse the contents of text fields. (Set becomes the default button whenever you alter the contents of a text box. This means that you may press Return in order to end text entry and have the new text checked.)

Import

Opens a file browser for selecting another game set-up file and copying its contents into the fields of the Define Network Game dialog box. This is useful when making several related game set-ups.

Strategic

This check determines whether or not the Try Decisions button of the game control panel will be enabled when the game is run.

Symmetric

Check this button if the players of the game uses the same user interface.

Players

Determines the number players (personal and simulated). The number of Players should be greater than zero. (Press the Set button if you alter the number if Players.)

Simulated

Turn on the check mark in front of each player number that is going to be simulated by the model. This is used to make games where one or more players are simulated, while others are played by persons (or groups).


List of Network Game Object Functions

The network game DLL enters the following additional functions into the Miscellaneous group of the Define Variable dialog box:

GETPLAYERS - Get number of players

GETSIMPLAYERS - Get number simulated of players

GETTOTPLAYERS - Get total number of players

PLAYERNUMBER - Get player number

SELECTDECISION - Select decision value

STRATEGICMODE - Test if game is in strategic mode

The three topmost functions return the number of human players, the number of simulated players, and the sum of the human and simulated players, respectively. The SELECTDECISION function is used to specify the decision sources that are used by the game (see figure above). PLAYERNUMBER returns the number of the current player. STRATEGICMODE returns True if the model is running in the strategic mode (the user has pressed Try Decisions). STRATEGICMODE will be False when running in operational mode (the user has pressed Accept Decisions).


Common Dialog Boxes

Below you will find descriptions of dialog boxes that are used by several object types in Powersim.

Note	Some of the dialog boxes described here may have different captions when opened from different objects.

  Area

  Axis

  Color

  Copy Time Series

  Display

  Field

  Field Types and Instructions

  Font

  Format Number

  Generations

  Generations Legend

  Line

  Text Layout

  Title


Area dialog box

Use this dialog box to change the settings of an object area.

Dialog box options

Border

Use this group to change the color, style, and shape of the border. In order to turn border off, choose None as the style. You may choose between rectangle, round rectangle, and oval shapes.

Interior

Use this group to change the filling, pattern, foreground color, and background color.

Hint	The interior of a graph refers to the area below the graph, and can be filled according to the settings of the Fill box.

Fill

Use the fill box to select how to fill the active object or item.

•	When None is selected, the interior is not filled at all.

•	Selecting Pattern makes Pattern, Foreground and Background available for defining the fill.

•	Selecting Solid makes a Color button available, for selecting any color to use when filling the graph. Pressing the Color button opens a standard dialog box for choosing a color (see Color dialog box ).

•	Selecting Shade makes Shade Style, Color Mixing, From Color and To Color available.

Shape

Use this combo box to choose between 16 basic shapes (see figure below).

Use the buttons at the bottom of the dialog box ( [image] [image] [image] [image]) to rotate and flip the selected shape.

Shade

Use this check box to switch shaded border on/off.


Axis dialog box

Use this dialog box to change the tick marks, tick labels (the numbers indicating the scales), and the scale settings of the axis.

Dialog box options

Tick Marks

Use this group to change the major and minor tick marks of the axis.

Tick Labels

Use this group to change the position and format of the tick labels of the axis.

Format

Use this button to define the format of the tick labels. A pop-up menu is displayed with items for opening the Font, Text Layout and Number Format dialog boxes respectively.

Scale

Use this group to change the scale settings of the axis. For each option you may either choose the automatic setting by checking the corresponding Auto box, or type a specific value in the text box.

Minimum, Maximum

Type or choose min and max values.

If current axis is a time axis, check the Auto box if you want the min or max value to be equal to start and stop time, defined in the Simulation Setup dialog box.

If current axis is a value axis, check the Auto box if you want the min or max value to follow the global scale settings, defined in the Scale dialog box (found in the Edit menu).

Minor Unit, Major Unit

The minor and major units determine the position of the minor and major tick marks and grid lines. Check the Auto box if you want Powersim to choose a setting for you.

Label

Opens the Axis Label dialog box that lets you change the label of the axis. See Title dialog box.

Line

Opens the Axis Line Style dialog box that lets you change the color and style of the axis line.


Color dialog box

Use this dialog box change the color of the current object or item. This is a standard Microsoft dialog box.


Copy Time Series
Copy Time Series dialog box

Time series of simulated data may be copied to the clipboard and pasted into other programs.

(To get to this dialog box, click the Display button in the Time Table or Time Graph dialog boxes.)

Dialog box options

Orientation

Choose between Horizontal and Vertical orientation of the copied data.

Include

Use this group to determine whether or not you wish to copy the Title of the selected series and the corresponding Time values along with the copied data.

Time Range

Use this group to specify the time range for the data to be copied. Type or select the From time (the first time it copies a value), To time (the last time it copies a value), and time Step (the time between each copied value).

If you check the Auto boxes, which is default, the copying will follow the simulation setup, that is, values will be copied each time step, from start time to stop time, as specified in the Simulation Setup dialog box.

OK

Copies the selected series according to the settings in the dialog box. The numerical format of copied numbers is determined from the Windows Control Panel, possibly overridden by the Numerical Format setting in the General options dialog box.


Display dialog box

The Display dialog box operates on simulation time series. It may be used to control which series to be displayed by the current object, the plotting order, copying of time series data to the clipboard, etc.

Dialog box options

Available Series

Displays all variables for which the object stores simulated values. To add a series from this list to the Displayed Series list, double-click on the series or select it and hit the Add button. The series already present in the Displayed Series list are disabled.

Displayed Series

This list contains the series that will be displayed by the object.

The plotting order is determined by the sorting of the list. If you use area drawing (the Area button of the Drawing group of the Define Time Graph dialog box is checked), some variables may be hidden by series plotted later. Changing the plotting order may be used to avoid this problem.

To remove a series from a plot, double-click on it or select it and hit the Remove button.

Add New Generations to Display List

Check this button if you wish new generations of simulated values to be automatically added to the Display Series list. This option is switched off by default.

Normally the current set of simulated values (the current generation) of a time table or time graph object will be lost when a new simulation starts. In order to keep simulated time series across simulations you should switch on the check box Simulation Starts New Generation (see Generations dialog box). When this check box is switched on, current time series of the Displayed Series list box will be stored under the next available generation number when a new simulation is started. Newly created series will be added to the Available Series list box. If the Add New Generations to Display List check box is switched on, new series will be added to the Displayed Series as well.

Copy

Copies the time series data selected from the Displayed Series list so you can export them to other applications, for example, to spreadsheets or word processors. Opens the Copy Time Series dialog box.

Order Available

Use this list to change the sorting order of the Available Series list.

Sort

Use this group to change the plotting order of the series in the Displayed Series list box.

Move Up, Move Down

Moves selected series in the Displayed Series list box up or down.

By Var

The contents of the Displayed Series list is sorted by variable name.

By Age

The contents of the Displayed Series list is sorted by age, that is, older generations come first.

By Max

The contents of the Displayed Series list box is sorted by max scaling value, that is, variables with higher max values (specify in Edit Scale) come first. If you use area drawing, this may reduce the problem of some variables hiding previously plotted variables.


Field dialog box

Use the Field dialog box to insert a field code at the text marker of the active text box. Fields are coded instructions that insert textual, numerical or other information into your document. Which field types that are available depends on the context in which the Field dialog box is opened. Field Types and Instructions shows the field types available for the various dialog boxes in Powersim.

Dialog box options

Insert Field Type

Select the type of field you want to insert. The box lists the fields available for the active text box. Selecting a field from the list replaces the contents of the Field Code text box with the field you selected.

Instructions

Choose any additional instructions for the field type. The box lists the instructions available to the selected field. Select an instruction from the list and hit the Add button to add the instruction to the Field Code text box.

Field Code

The box shows the field type and instructions you select or type. You can edit the field code in this text box.

Add

Adds the selected instruction to the Field Code text box.


Field Types and Instructions

List of Available Field Types

Field type	Displays	Instruction group	Used by dialog box
PAGE COLUMN ROW	Page number Column number Row number	Numbering Formats	Page Setup
FILENAME	File name of document	None	Page Setup
TITLE	Title of document	None	Page Setup
AUTHOR	Author of document	None	Page Setup
TIME	Printing time and date	Time Formats	Page Setup
TIMEFROM TIMETO	Time at generation start Time at generation end	Time Formats	Generations
TIMEUNIT	Time unit ("Time" if no time unit defined)	None	Define Time Table Axis Label
TIMEUSED	Time used during simulation	Time Span Formats	Generations
STARTTIME STOPTIME TIMESTEP	Simulation start time Simulation stop time Simulation time step	None	Generations
GEN	Generation number	None	Generations
PAR	Parameter	Parameter Formats	Graph Legend Bar Label Number Label Slider/Bar Axis Label
MIN	Min value	None	Graph Legend
MAX	Max value	None	Graph Legend
SOURCE	Source parameter	Parameter Formats	Chain Label
TARGET	Target parameter	Parameter Formats	Chain Label
X Y	X or Y parameter of Scatter Graph	Parameter Formats	Scatter Graph Axis Label
Field Instruction Groups

Instruction group	Instruction	Description
Time Formats	yy	Year (92)
	yyyy	Year (1992)
	m	Month (1..12)
	mm	Month (01..12)
	mmm	Month (Jan..Dec)
	mmmm	Month (January..December)
	d	Day (1..31)
	dd	Day (01..31)
	ddd	Day (Mon..Sun)
	dddd	Day (Monday..Sunday)
	h	Hour (0..23), (0..11 if AM/PM)
	hh	Hour (00..23), (00..11)
	m	Minute (0..59), Must be after 'h'
	mm	Minute (00..59), Must be after 'h'
	s	Second (0..59)
	ss	Second (00..59)
	AM/PM	Use 12 hour clock
	am/pm	Use 12 hour clock
	A/P	Use 12 hour clock
	a/p	Use 12 hour clock
Time Span Formats	h	Hours (0.. )
	m	Minutes (0..59) (0..* if no 'h')
	s	Seconds (0..59) (0..* if no 'm')
	d	Deci-seconds (1/10 sec.)
	c	Centi-seconds (1/100 sec.)
Numbering Formats	1, 2	Arabic
	I, II	Roman Capital
	i, ii	Roman Versal
	A, B	Letter Capital
	a, b	Letter Versal
Parameter Formats	Comod	Co-model name (empty for main model)
	Element	Subscript if parameter is an array, name if not. Example: A for A and 1 for B(1).
	Global	Common part of names of parameters. Example: A(1), A(2) gives A as the common name.
	Inidividual	Individual part of parameter name. Parameter name minus the global part (see above).
	Model	Model name ("Main" if main model)
	Subscr	Subscript (empty if not array)
	Unit	Unit of Measure expression
	Var	Variable name


Font dialog box

Use this dialog box to change the font settings of the selected text item(s).

Dialog box options

Font

Lists available fonts. Type or select the name of the font you want.

Font Style

Lists available styles for the font selected in the Font list box. Type or select the name of the font style you want.

Size

Lists available sizes for the font selected in the Font list box. Type or select the size you want.

Effects

Choose the formatting options you want and clear those you don't. You can choose any combination of strikeout and underlining.

Color

Controls the text color. Choose a color from the list.

Sample

The sample box shows the effects of the chosen formatting before you apply it to the document.


Number Formatting

In Powersim numbers are formatted according to a numeric picture, in a way similar to MS-Excel and MS-Word. Zeros ("0"), number signs ("#") and question marks ("?") are placeholders for digits.

See also

Format Number dialog box

Decimals

Use the national decimal separator ("." in English) followed by a number of decimal placeholders to define the number of decimals in the number. The numeric picture 0.000 means that numbers will be output using three decimals, whereas "0.0##" means that a miniumum of one and a maximum of three decimals will be displayed.

Unit

Text describing unit of measure can be added to the numeric picture by placing characters inside quotes ("text"), or by placing the escape character ("\") in front of another character. As an example, the numeric picture "DEM "0.00 will output 123.456 as DEM 123.46.

Thousand Separators

If you want your number to be displayed using thousand separators (groups of three digits), just put the national thousand separator ("," in English) between two digit placeholders in the numeric picture. The numeric picture #,##0 will display 123456789 as 123,456,789.

Numeric Picture

A numeric picture describes how numbers will be output. Different numeric pictures are described below.

Standard

Output numbers with a minimum loss of precision, and at the same time trying to use the number of decimals that the user has set in Windows' control panel.

+0

A plus in a numeric picture will print as "+" for positive numbers and "-" for negative numbers. Examples using the numeric picture above:

•	123 will be displayed as "+123"

•	-123 will be displayed as "-123"

-0

A minus in a numeric picture will print as " " for non-negative numbers and "-" for negative numbers. Examples using the numeric picture above:

•	123 will be displayed as " 123"

•	-123 will be displayed as "-123"

#,##0

The national thousand separator (, for English) between two digit placeholders means that the integer part of a number will be printed using groups of three digits, separated by the thousand separator. Example using the numeric picture above:

•	12345 will be displayed as "12,345".

0,

If a digit placeholder sequence is terminated by the national thousand separator, numbers will be divided by thousand before output. Example using the numeric picture above:

•	12345 will be displayed as "12". Terminating a sequence with two thousand separators, will divide the number by 1,000,000 (1,0002), and so on.

0.000

Zeros following the national decimal separator ("." for English) determines the minimum number of decimals that will be displayed. Example using the numeric picture above:

•	123.4567 will be output as "123.457"

0.0##

Number signs in the decimals part of a numeric picture defines optional decimal digits, that is, digits that will be printed only of not zero. Examples using the numeric picture above:

•	3.14 will print as "3.14"

•	99 will print as "99.0"

•	3.141592 will print as "3.141".

0000.0

The number of zeros in the integer portion of a numeric picture determines the minimum number of digits that will be used for the integer part of a number. Examples using the numeric picture above:

•	12 will print as "0012.0"

•	12345 will print as "12345.0"

"$"\ 0.00

Text can be quoted either by putting characters inside apostrophes ("…") or by putting a backslash ("\") in front of a character. Example using the numeric picture above:

•	10000 will print as "$ 10000.00"

Note	For some languages space (" ") is used as thousand separator. You should therefore quote space characters when used as text in a numeric picture. As an example, 10000 will print as "10.00 kr" using the number picture 0.00 "kr"; and as "10000.00 kr" using picture 0.00" kr". (In the latter example the space character is put inside the quotes.)

0;(0);"zero"

To specify individual formats for positive, negative and zero numbers, specify formats separated by semicolon. The first given format is used for positive numbers, the second for negative, and the third for zero. If only two formats are given, zero will be output according to the positive format. If only one format is given, all numbers will be formatted according to this format.

The format displayed above will output positive numbers rounded to the nearest integer, negative numbers rounded to the nearest integer and put inside parenthesis, and zero as the string "zero". Examples using the numeric picture above:

•	123.5 will be displayed as "124"

•	-123.5 will be displayed as "(124)", and 0 will be displayed as "zero"


Format Number dialog box

Use this dialog box to change number formatting.

Dialog box options

Type

Type in a numeric picture in the Type field, or select one of the samples in the list box.

Insert

Copy a number format from the Type text box to the Type list.

Delete

Deletes the current selection in the Type list box.

Reset

Reset the Type list to the default list.

Sample

Enter a number in the text box and see the result formatted according to the text in the Type field.


Generations dialog box

A generation is a time series of values produced by a simulation run. When multiple runs are performed, the time table and time graph objects can be used to show the results of several generations for comparison purposes.

Dialog box options

Description

Here you may type a text describing the generation which is selected in the Generations list box. The text will be used when displaying generations in the generation legend of time graph objects.

To edit the description of one or more generations, do as follows:

1	Select the desired entries of the Generations list

2	Edit the contents of the Description box

3	Press the Set button or hit the Return key

Generations

This box lists all saved generations. By clicking in the list, key information about the generation is displayed in the Description text box and the texts below.

Simulation Starts New Generation

If this field is checked, current simulation results are moved to the generations list when a new simulation is started (by choosing Run from the Simulate menu or pressing the Run button.) This makes it possible to display values of different simulation runs in the same time graph or time table. See also the Display dialog box.

Remove

Use this button to delete saved simulation results from the Generations list.

Set

Use this button to assign the contents of the Description text box to the selected entries of the generations list.

Insert Field

Use this button to insert fields in Description.

Set To Default

May be used to set Description to default. The default text string is loaded from the file POWERSIM.INI.

Use As Default

Hit this button to store the current contents of the Description box as the new default. The value is stored in the profile POWERSIM.INI. If Description is empty when Use As Default is pressed, the default is restored to the value when the system was shipped.

Note	The Simulate Clear Results command will clear all generations.


Generation Legend dialog box

Use this dialog box to hide or show the generation legend in the current time table or time graph object, and to change colors, patterns etc.

Dialog box options

Border

Use this group to change the color, style, and shading of the border. In order to turn border off, choose None as the style.

Interior

Use this group to change the filling of the legend box.

Fill

The interior of a generation legend can be filled according to the settings of the Fill box:

•	None: The interior is not filled at all.

•	Pattern: Pattern, Foreground and Background are available for defining the fill.

•	Solid: A Color button is available for selecting any color to use when filling the graph. Press the Color button to open the Color dialog box.

•	Shade: Makes Shade Style, Color Mixing, From Color and To Color available.

Font

Changes the button font. Opens the Font dialog box.

Shade

Use this check box to switch shaded border on/off.

Present

Shows/hides the generation legend.


Line dialog box

Use this dialog box to change the color and style of the selected line. The dialog box is used by several object types to edit different kinds of lines, such as graph axis and grid lines.

Dialog box options

Color

The Color combo box is used to set the color of the lines in question.

Style

The style of the lines is chosen from the Style combo box. In order to turn grid lines off, choose None as the style.


Text Layout dialog box

Use this dialog box to change the orientation and alignment settings for the current text items.

Dialog box options

Orientation

Choose between the four different text orientations available.

Alignment

Choose between the left, center and right text alignment.

Position

When available, this group enables you to position a text at nine different locations within the borders of an object.

•	To select between top, middle and bottom vertical placement, click on one of the three buttons to the left in order.

•	To select horizontal position left, center or right,click on one of the three buttons to the right.

Note	When using hexagons to visualize model structure, you should select middle, centered position (see example below).


Title dialog box

Use this dialog box to edit text items.

Dialog box options

Text

Use this text box to specify the contents of the text output. A text specification may contain text and field codes (if the Ins Field button is enabled).

Adjust object size to fit text

When checked, the object will be resized to enclose the contained text exactly.

Insert Field

Use this command to insert a field that controls the insertion of text or numbers. The selected field is inserted at the text marker of the Text box. When you hit the button, the Field dialog box opens. Available fields depend on the particular text item that is edited.

Border

Use this group to change the color and style of the text border.

Shape

Use this combo box to choose between 16 basic shapes (see figure below).

Use the buttons at the bottom of the dialog box ( [image] [image] [image] [image]) to rotate and flip the selected shape.

Interior

Use this group to change the filling of the interior.

Fill

The interior can be filled according to the settings of the Fill box:

•	None: The interior is not filled at all.

•	Pattern: Pattern, Foreground and Background are available for defining the fill.

•	Solid: A Color button is available for selecting any color to use when filling. Press the Color button to open the Color dialog box.

•	Shade: Makes Shade Style, Color Mixing, From Color and To Color available.

Font

Changes the text font. Opens the Font dialog box.

Layout

Changes the orientation and alignment settings for the text. Opens the Text Layout dialog box

Shade

Use this check box to switch shaded border on/off.

Present

Use this check box to show or hide the text.


Introduction to Powersim Command Button
Command Button

Powersim Command Button enables you to manage your models in a better way. By using the 24 different DDE commands in Powersim Constructor, Command Button offers sophisticated means of model management. It can best be described as a control panel, making it easier to control the Powersim session. Given a model with several input and output objects in different windows, switching between windows can now be easily achieved, simply by the click of a button. Command Button features commands for simulation control, window and document management.

See also

  How to define a Command Button

  The Define Command window

  DDE commands in Powersim Constructor


How to define a Command Button

1.	Click  [image] on the toolbar, and drag it onto the worksheet.

2.	Double click the Command Button in the worksheet to bring up the Define Command window.

3.	There are two ways of defining which commands the button should execute:

•	Double click the desired command in the Available commands list.

•	Type in the desired command in the Command window.

Only one command per line is allowed in the Command window.

4.	Click Title in the Define command window to enter the Command button title window. For more information on how to define the visual appearance of the button, please refer to chapter 1, Static Objects, in the Reference Manual.

5.	Click OK when the Command Button is defined the way you want it.

An example model, Command.sim, is included in the Bonus Pack, to demonstrate some of the commands in Powersim Command Button.


Define Window
The Define Command window.
Please click the buttons or windows you would like more infomation about.


Commands
Command

Contains the commands which will be executed when the button is clicked. Only one command is allowed per line. Commands can either be typed in manually, or selected by double clicking the command entry in the Available commands list.

More information about the available commands is available in the List of DDE commands.


Available commands

Shows a list of the available commands in Powersim Command Button. By double clicking the entry in this list, a selection for the Command window is made.

More information about the available commands is available in the List of DDE Commands.


Title Button
Title

Click the Title button to format the visual appearance of the Command Button.

More information about the Command button title window is available in Chapter 1, Static Objects, in the Reference Manual.


OK

Click OK to accept the Command Button.


Cancel

Click Cancel to abort the Define Command window.


Help

Click Help to show the first page of this help file.


Quick Tours in Powersim

  Tour 1: Running The Market Growth Simulator

  Tour 2: Building Your First Model!

  Tour 3: A More Advanced Model

  Tour 4: Turning a Model Into a Simulator

Note	Before you start, make sure that your Powersim is in simplified mode (check Simplified User Interface in the View menu).

See also

  Printing a help topic

  Main Powersim help


Foreword

Making business decisions

Today, business simulations are used in making business decisions. Faced with a decision on where to build natural gas storage containers, and how big to build these containers, one oil company used Powersim to build a simulation of the wells, the pipelines, and the markets. Once the simulation was built, decision-makers at the oil company could try different storage container scenarios. The consequences of the different scenarios could be understood in a risk-free environment before any investments in construction of storage containers were made.

Business simulations are also used in explaining business decisions to others in the organizations. For example, a major telecommunications company saw many of their competitors making risky forays into interactive television, adventures that were garnering much publicity. It was not enough to just focus on their core business; they also had to explain to the employees why investing in interactive TV and similar ventures were bad business decisions. This telecommunications company built an interactive simulation of how they perceived their business. This simulation was used by over 1200 employees in a series of management training workshops, where employees had an opportunity to run the simulated business and make investment decisions. The employees gained new appreciation for the corporate strategy, and a better understanding of how the thought leaders in their organization saw the dynamics of the next few years unfolding.

Both of these simulation success stories were achieved using Powersim. In each case a team of modelers and thought leaders from the business collaborated to build a custom model of the business problem. The models contained enough of the important details and complexities of the real world situation to be useful and believable.

Business simulations more common

The use of simulation in business is not yet an everyday occurrence, but it is spreading. In 1990, both of these examples would have been quite unusual. Although simulation technology was well understood by 1990, and the cost of the necessary software tools had become modest, very few business decisions were supported by simulating the consequences before taking action. It simply was not part of standard business practice. Now things are changing, and the use of business simulation is becoming more common.

At Powersim Corporation, we are committed to supporting the emerging practice of business simulation. We appreciate that the process of business decision-making is different from that of decision-making in public policy. Our tools are focused on modeling business problems, not on public policy or academic issues.

From models to simulators

Why this sudden change in business practice? Business models are not substantially easier to build now than they were at the beginning of the decade. Nor has there been a watershed event that has made the business community suddenly more receptive to simulation. From the viewpoint of us in the business modeling community, building simulation models for years, the change is welcome, but a little mysterious. However, from the viewpoint of our business customers, there has been a technology revolution of sorts. Once a model is built, it is now possible to build a high-quality user interface around it, and turn it into a business simulator. Anyone can run the business simulator, trying different decision scenarios and understanding the resultant behaviors.

The difference between a business simulation and a business simulator is much like the difference between a traditional mainframe computer and a modern PC. Both have similar technical capabilities: both can run payroll applications, print form letters, and perform a thousand other applications. But to unlock the power of a mainframe you must hire a team of highly trained individuals for its care and feeding. By contrast, the power of a PC is accessible to anyone with a little time and patience. The power of the PC is also much more accessible to an untrained person. In the same way, by wrapping a high-quality user interface around a business simulation, one can remove the simulation from the laboratory and make it available to anyone with the time and interest to play with it.

There are many tools that simulate, but Powersim is the essential tool for constructing business simulators. Why? Because its the only tool that supports building a high-quality user interface. Users in the 1990s have high expectations: they expect business simulators (and all software) to look good, to be easy to learn, to be simple and obvious, to have a help system, and to be bullet-proof. In Powersim, you can build a business simulator that has all these features.

The joy of simulators

Who has the time and interest to play with a business simulator? Everyone seems to make time. Some commercial simulators, like Maxis Corp.s SimCity are so much fun to play that they are sold as entertainment. While few business executives might admit to playing games, they will gladly play with a custom business simulator, crafted to model an aspect of their current environment. One very serious senior executive remarked that playing a custom simulator of his telecommunications company was "a joyful experience." Another senior executive at the same organization spent 10 hours over two evenings playing the simulation.

Crafting a joyful experience can mean the difference between 4 people understanding your model and its implications--and 1000 people understanding it. And joy is impossible if casual users must struggle with arcane controls, obscure commands, or cryptic numerical displays.

The value of simulators

Joy alone is not enough in a business context: there must also be value. What is the value of business managers playing a business simulator? Do the people playing the simulation make better decisions? Do they learn more about the world in which they must succeed?

For many years, we in the business modeling community have approached the problem of creating value by teaching business people a new way of thinking. We have taught them the basics of building models, and when that was too difficult, we taught "systems thinking," how to see their world the way a modeler might see it. Systems thinking is undoubtedly valuable for anyone who chooses to undergo the education--but it has certain shortcomings as a discipline that can be put to use within a business. Some people will never learn how to think systemically; and in fact, business people expect something less abstract and more tangible for their investments in time and money. Provide them a simulated experience--with their new situation, in their industry, in their context, with their assets and constraints--and youve empowered them to solve existing problems, and avoid potential ones.

Our goal at Powersim is to support you in "publishing" custom models of your business, making them available to everyone who might need to know or care. And there are a lot of people who might care: existing employees, new recruits, suppliers, distributors, customers, and investors.

Learning from simulators

By playing a simulator, by trying different combinations of decisions, a business manager can understand a simulation in a kind of kinesthetic way. Just as you dont need to understand the physics of skiing to learn how to ski, in the same way it is possible to play a simulation model and learn the dynamics of a business situation--without understanding the details of the underlying mechanics. Through simulation, a business person can thus acquire experience not only without "field" work, but without necessarily understanding details of the model behind it.

Powersim 2.5 supports two approaches to building business simulators: building a simulator within Powersim itself, and building a simulator in a general-purpose, interface-building language and using Powersim as a simulation engine.

Within Powersim, a modeler can use a host of interface objects. A modeler can present the state of the simulation by a gauge, by a graph of an array, and by many other means. A modeler can link a situation in a model to the playing of a sound, video, animation, or interactive message box.

We at Powersim recognize that there are other applications in the Windows world, applications that are better for building high-quality user interfaces than any modeling tool will ever be. Easy and natural communications are critical. We support DDE, OLE, and direct APIs. We speak the languages of the computational world!

As more and more organizations build business simulators to understand their world, and communicate it to others within their organization and outside, your job will become more exciting and more important. We at Powersim are committed to supporting you in your efforts to build business simulators.


Introduction to Powersim Constructor
Introduction to Powersim Constructor 2.5

  Foreword

  What Is Powersim Constructor and What Is It Used For?

  What Is a Business Simulator?

  Powersim Constructor and Its Relation to Business Simulators

  Methodological Issues

  Introduction

  Powersim as a Tool for System Dynamics Modeling

  Using Powersim to Teach Sustainable Economic Development

  Feeding Your Models with Real Business Data

  Powerful Modeling Using Array Variables


What Is Powersim and What Is It Used For?

Welcome to the world of dynamic simulation. Powersim takes its name from Powerful Simulation, which is exactly what it is. It is a simulation software package designed to give you the ability to make complex business simulators based on a modeling methodology called system dynamics. With Powersim, you first build a model that represents the elements of a system and how they interact with one another. When the model is finished, the result is a mini-laboratory where you can experiment with different policies before trying them out in the real world. The model by itself provides valuable insight; however, with Powersim you have the option of taking its development a step further by turning it into a simulator.


What Is a Business Simulator?

Simulators are useful tools for both communication and experimentation. You can create a model in Powersim to help you understand the complex relationships that exist within a dynamic system. As you create the model, you often learn as much about the system as you would by simulating different scenarios with a completed model. If you are introduced to an already completed model, however, you will lack the knowledge gained from the building experience. Further, you may know nothing about the theory behind the model but still need the insight that the model provides. Simulators can help newcomers understand not only the results of simulation runs using different conditions (parameters), but also why the model behaves as it does. By putting a level of abstraction on top of the model (an interface), a simulator can insulate you from the level-and-rate details but still provide you with enough information to understand the important concepts that the model is designed to communicate.

Simulators also provide a laboratory for experimentation. Managers must make tough decisions every day with only a partial understanding of the consequences. Simulators are a safe environment within which to speculate and discover new ways of looking at and dealing with complex problems. It is even possible to make simulators that are network games, allowing managers to be trained by competing against other players in settings such as managing a distribution network or commanding a company from start-up to success (or failure). Whatever the setting, simulators provide valuable (and safe) experience in policy formulation and decisionmaking.


Powersim and Its Relation to Business Simulators

Powersim is a unique tool in the field of simulation. It has features that help in model design, such as causal loop diagramming, and it supports level-and-rate modeling. Further, features of the software make it a fully integrated simulator package. A separate user interface can be designed within Powersim that allows you to interact with the model without ever seeing the model or even knowing that it is there. Of course, you can also have complete access to the model and even change its structure, if you desire. Powersim is flexible in the levels of complexity of both models and interfaces, and also in the degree of control you have. Because Powersim has been designed with simulator creation in mind, you will find it well suited to all the rigors of model and simulator design and creation.


Simulation

The following topics describes the simulation algorithms applied by Powersim and how to utilize some of its powerful simulation capabilities.

See

  The Simulation Process

  Introduction to Simulation

  Euler´s Method

  Runge-Kutta Integration Methods

  Comparing Integration Methods

  Concurrent Independent Simulations

  Performing a Background Simulation

  Co-Models

  Synchronizing Co-Models

  Co-models and Integration Methods

  Using Different Integration Methods for Different Parts of a Model

  Communication Between Models

  Several Instances of a Model

  Alternative Interfaces to a Model

  Troubleshooting

  Multiple Runs

  Generations - The Results of Previous Simulations

  Sensitivity Analysis

  Generating Test Input Data


The Simulation Process

  Introduction to Simulation

  Euler´s Method

  Runge-Kutta Integration Methods

  Overview

  2nd-Order Runge-Kutta Integration with Fixed Step Size

  3rd-Order Runge-Kutta Integration with Fixed Step Size

  4th-Order Runge-Kutta Integration with Fixed Step Size

  4th-Order Runge-Kutta Integration with Variable Step Size

  Comparing Integration Methods

  Potential Problem

  Speed

  Time Step And Accuracy

  Oscillation

  Using Generations


Introduction to Simulation

Systems that are analyzed with the help of dynamic models are often continuous. In such systems, variables change in a continuous manner, for example, the movement of planets, temperature changes, population growth, etc.

In discrete systems, variables change in steps at specified points of time, for example, bank deposits and withdrawals, serving queue systems, etc.

Calculating levels

In a truly continuous system, level variables would be calculated as the integral of the net rates flowing into or out of them. Levels in a model express the condition of the components in a system. They represent the accumulated change in the conditions we wish to study. As it is not possible to represent continuous change numerically, we need to divide time into several small steps.

Simulation portrays the development of the variables in a system over time. For every time step of a simulation, the level variables are updated to portray the current condition or state of the system. This is done by using mathematical techniques from integral calculations. For every time interval, the changes in the state of a system, and the difference in the level variables, are calculated.

Integration

To calculate the differences we can use the "difference quotient" [image], which gives an average slope for the state graph in that time interval. The equations that express the rates of change in the level variables are based on the present value of the levels at that particular point of time in the simulation. Therefore the derivative is applied in that time interval. The rate of change is expressed by the limits of the difference quotient when [image] moves towards 0.

In mathematics, there are rules to determine the derivative of a function. In system dynamics simulation, the problem has to be approached from the opposite direction since the values of the levels at every new point in time are not known. The value of a level, say F(t), at the previous point of time is known, and the derivative of the level's graph, say f(t), is also known. The derivative f(t) and the current value F(t) are used to calculate the value of the level at the next point of time in the simulation. This process is called integration.

Integration methods

Integration methods provided by Powersim are Euler integration, and Runge-Kutta second, third, and fourth order methods - the latter with both fixed and variable step size.

Runge-Kutta integration has two advantages. First, it makes it easy to change the simulation step size dynamically during simulation. This is particularly important in combined simulations, where events are not spaced uniformly in time. Secondly, Runge-Kutta integration is self-starting. There is thus no loss of efficiency when restarting from an event. This is also of critical importance in a combined simulation.

The calculation sequence employed by Powersim depends on the method chosen in the Simulation Setup dialog box, which is opened from the Simulate menu. The methods are explained in the following sections.


Euler´s Method

In evaluating a model using Euler's method, Powersim first calculates the initial conditions for the levels and flows. The flows are then used to update the levels. The new values for the levels are then used to re-calculate the flows and so on. Time is incremented by one time step between each iteration.

Euler's Algorithm

Let us say Lt represents a level at time t and F(Lt, t) represents the flow (derivative) of the level Lt at time t:

Lt 	- Value of level L at time t

F(Lt, t)	- Value of flow F of level L at time t

The following two steps are executed in order to calculate the integral over an interval from t to t + [image].

Step 1: Calculate the derivated flow when t = T

Flow = F(LevelT, T)

Step 2: Calculate the value of Level at t = T + [image] based on LevelT and Flow

LevelT + [image] = LevelT + [image] * Flow

Note	An important characteristic of Euler's method is that it assumes a flow is constant over the interval [image]. In other words, it uses the derivative information only at the beginning of the interval.

By making [image] smaller, you can reduce the amount of error imposed by Euler's method. As [image] approaches zero, Euler's approximation approaches an exact solution. But as you reduce [image], you also increase the number of calculations required and the amount of round-off error. Therefore, choosing an integration method will be dependent on the trade-off between computational speed and the accuracy of the integration method.

If the above explanation seems complicated, here is an example of what is going on.

Example

Let us look at a simple model consisting of one level and one flow. The example has the following diagram and equations:

	init L = 100 flow L = +dt*(F) aux F = -L/5
Here F is the flow of L, which is the derivative to be integrated in order to compute the value of L from time step to time step. When the model is simulated from time 0 to time 10 with a time step of 1, the following sequence of events unfolds.

Starting at time 0, L gets its initial value, i.e., 100. Computing F in this state yields -L/5 = -100/5 = -20. According to Euler's algorithm, the following equation produces the value of L at the next time step (when time = 1):

L(0+1) = L(0) + [image] * F(0) = 100 + 1 * -20 = 80

We now have the value 80 for L at time 1. In this state the value of F may be recomputed as -L/5 = 80/5 = 16. This gives the following value for L at time 2:

L(1+1) = L(1) + [image] * F(1) = 80 + 1 * -16 = 64

Continuing this way, we get the following results for times 0 to 10 (see figure below).


Runge-Kutta Integration Methods

  Overview

  2nd-Order Runge-Kutta Integration with Fixed Step Size

  3rd-Order Runge-Kutta Integration with Fixed Step Size

  4th-Order Runge-Kutta Integration with Fixed Step Size

  4th-Order Runge-Kutta Integration with Variable Step Size


Overview of Runge-Kutta Integration Methods

The Runge-Kutta methods make use of a more sophisticated procedure for estimating the change in levels over a given [image], thus providing a higher degree of accuracy.

Powersim provides four different types of Runge-Kutta integration methods, ranging from second to fourth order:

Order	Step size	Abbreviation
2	fixed	RK2
3	fixed	RK3
4	fixed	RK4-Fixed Step
4	variable	RK4-Var Step


2nd-Order Runge-Kutta Integration with Fixed Step Size

The 2nd-order Runge-Kutta method is the simplest. Basically, this algorithm uses two flow calculation within a given [image] to create an estimate of the change in a level over the [image].

Step 1: Estimate the flow at two points in the interval T to T+

F1 = [image] * F(LT, T)

F2 = [image] * F(LT + F1, T + 3/4* [image] )

Step 2: Calculate a second order estimate of LT + [image] by using a weighted average of F1 and F2

LT + [image] = LT + 1/3*F1 + 2/3*F2


3rd-Order Runge-Kutta Integration with Fixed Step Size

The 3rd order method works like the 2nd-order method, but uses three rather than two flow calculations within a given [image]. A weighted average of these calculations is used as an estimate for the change in the level.

Step 1: Estimate the flow at three points in the interval T to T+

F1 = [image] * F(LT, T)

F2 = [image] * F(LT + 1/2 * F1, T + 1/2 * [image])

F3 = [image] * F(LT + 3/4 * F2, T + 3/4 * [image])

Step 2: Calculate a 3rd order estimate of LT + [image] using a weighted average of flow estimates

L3T + [image] = LT + 2/9*F1 + 3/9*F2 + 4/9*F3


4th-Order Runge-Kutta Integration with Fixed Step Size

The 4th order method works like the 2nd-order method, except that it uses four, rather than two, flow calculations within a given [image]. In each [image] the derivative is evaluated four times: once at the initial point, two at trial midpoints, and once at a trial endpoint. From these derivatives the final function value is calculated. A weighted average of these calculations is used as the estimate for the change in the level. (The weighted averaging is based on the Taylor series expansion for a function of two variables.)

Step 1: Estimate the flow at four points in the interval T to T +

F1 = [image] * F(LT, T)

F2 = [image] * F(LT + 1/2 * F1, T + 1/2 * [image])

F3 = [image] * F(LT + 1/2 * F2, T + 1/2 * [image])

F4 = [image] * F(LT + F3, T + [image])

Step 2: Calculate a 4th order estimate of LT + [image] using a weighted average of flow estimates

LT + [image] = LT + 1/6*F1 + 2/6*F2 + 2/6*F3 + 1/6*F4


4th-Order Runge-Kutta Integration with Variable Step Size

The main purpose of the variable step size method is to achieve some predetermined accuracy in the solution with a minimal use of computational power.

Step 1: Estimate the flow at four points in the interval between T to T +

F1 = [image] * F(LT, T)

F2 = [image] * F(LT + 1/2 * F1, T + 1/2 * [image])

F3 = [image] * F(LT + 1/2 * F2, T + 1/2 * [image])

F4 = [image] * F(LT + F3, T + [image])

Step 2: Calculate a 4th order estimate of the flow using a weighted average of flow estimates

C4 = 1/6 * (F1 + 2*F2 + 2*F3 + F4)

Step 3: Calculate a 3rd order estimate of the flow using a weighted average of flow estimates

C3 = 1/3 * (F2 + 2*F3)

Step 4: Calculate an error estimate from the difference between the 3rd and the 4th order estimates

E = ABS(C4 - C3)

Step 5: Calculate an acceptable error limit

A = AbsError + ABS(RelError * C4)

Step 6: Repeat step 1 - 5 with smaller [image] if E > A for one or more levels

Step 7: Calculate a 4th order estimate of LT + [image]:

LT + [image] = LT + C4

 is adjusted according to the error estimate and the error limits given in the Simulation Setup dialog box. If the error estimate is too high, the calculated result is rejected, and the integration is repeated using a smaller [image]. This recalculation will rewind to the starting point of the current time step and repeat the process from Step 1 above.

Although the [image] used to calculate the results may vary, the time step between each reported result will always be equal to the time step given in the Simulation Setup dialog box. Powersim will never calculate using a higher [image] than the value of the Time Step box in the Simulation Setup dialog box. Powersim will also adjust [image] in a way that ensures data will be reported exactly at every user-specified time step. See also: Adjusting Calculation Time of RK4 Variable Step Size .


Comparing Integration Methods

  Potential Problem

  Speed

  Time Step And Accuracy

  Oscillation

  Using Generations


A Potential Problem With Higher Order Integration

Some modelers make use of the fact that Euler's algorithm employs the flow value at the beginning of the time step for the entire time step. This may, for example, be used to empty a level under certain circumstances. A common way of doing this is by using a pulse outflow with the same volume as the current value of the level (i.e., using an outflow with the value of the level divided by TIMESTEP).

The diagram above illustrates this technique. The equations are:

init	L = 10

flow	L = -dt*(EmptyL)

aux	EmptyL = PULSEIF(TIMEIS(2), L)

This model tries to empty the contents of L when time becomes equal to 2. The time graph below illustrates the actual behavior of L when simulated using the five different integration methods:

	1 Euler 2 Runge Kutta 1 3 Runge Kutta 2 4 Runge Kutta 3 5 Runge Kutta 4, variable step
As we can see, only Euler brings the level down to zero (during the time interval from 2 to 3). The reason for this is that the other methods use the value of the flow during the time step when computing the net flow of the entire step. Since the PULSE is only on at the beginning of the step, the net flow will be less than the value of L at time 2.

If necessary, it is possible to use the EULER function to overcome this behavior of the higher order integration methods. The definition of EmptyL would then have to be modified in the following manner:

aux	EmptyL = EULER(PULSEIF(TIMEIS(2), L))

Another way of emptying a level is by using the ASSIGN function (or SHIFTLIF when the level is an array).


Speed

In order to be accurate, the Euler method usually requires very small time steps. This implies that the simulation will run more slowly. Higher order methods will give more accurate results than lower order methods using the same time step. Normally the time step may be increased more than the increase in the order, for example, going from Euler to RK4 implies that the time step may be increased by a factor of at least four, without any loss of accuracy.


Time Step And Accuracy

The time step may not be made indefinitely small, as numerical round-off errors grow rapidly when the time step gets very small. You should observe your model as the time step gets smaller, and stop reducing the time step if it starts diverging.


Oscillation

A common problem with the Euler integration method is that it may cause an oscillating model to diverge - not because of model structure, but because of inaccurate integration.

The time graph above displays two simulations (generations) of an oscillating system. Observe how the Euler generation (1) diverges, while the RK4-Var Step generation (2) retains its amplitude.


Comparing Integration Methods Using Generations

Comparing the results of simulations with different integration methods may be done using the generations feature of the time table and time graph objects.

To compare integration methods using generations

1	Create a time graph object and open its definition dialog box

a	Select the variable to be observed into the Parameters list box

b	Switch on Generations Simulation Starts New Generation

c	Switch on Display Add New Generation to Display List

2	Choose integration method and time step

3	Simulate

4	Repeat steps 2 and 3 as many times as necessary

The above steps will display the values of the selected variable during the different runs in the same time graph. You may have to adjust the scale of the Y-axis in order to get the desired view of the results. This may be done either by setting the variable's scale by opening Scale from the Edit menu, or by scaling the Y-axis from the Define Time Graph dialog box.


Concurrent Independent Simulations

Powersim is a true multi-document application. Not only in the sense that multiple documents (models) may be edited in the same session, but even simulations may be performed concurrently.

At any time you may work with several model documents on the Powersim desk top. Each document may be either iconized or open (as a window). The contents of the menus and the status bar reflect the state of the topmost (active) document window. This multiple document interface (MDI) makes it easy to work with several models at the same time, for example, in order to copy and paste information between models or compare models to each other.

See also

  Performing a Background Simulation


Performing a Background Simulation

Some models may be run in the background while others are edited in the foreground.

Note	A model that is simulating may not be edited, even if it is opened in a new window or a new instance.

To perform a background simulation

Let us say you have a lengthy simulation, A.SIM, which you want to run while continuing your work on another model, B.SIM.

1	Open A and B

2	Make A's window active and press the Run button

3	Iconize A's window (for example, by using the Minimize command of the window's system menu)

4	Now you may go on editing B, while A is silently simulating in its iconized state. (A's window may be left open during the entire simulation if you like, but this will reduce simulation speed, and of course occupy space on the desktop.)


Co-Models

Powersim provides means of synchronizing individual models during simulation. This is done by hooking co-models up to a main model. A co-model is basically an independent model that may be edited and simulated in the normal way. By using the Simulation Setup dialog box, other models may be connected to the current model, which becomes the main model.

Note	A model which already has co-models may not be used as a co-model of another model.

See

  Synchronizing Co-Models

  Co-models and Integration Methods

  Using Different Integration Methods for Different Parts of a Model

  Communication Between Models

  Chaining Variables Across Models

  Restrictions on Chained Variables

  How Chains Are Updated

  Potential Problems Using Co-Models

  Several Instances of a Model

  Overview

  Opening the Main Instance of a Model

  Opening a Co-Model Instance of a Model

  Using the Same Model Several Times as a Co-Model

  Alternative Interfaces to a Model

  Troubleshooting


Synchronizing Co-Models

The main model controls the simulation process of its co-models. When the main model starts simulating, the co-models are automatically simulated as well. The simulation times of the co-models are mapped to the time interval specified for the main model. This ensures that the main model and all of its co-models will start and stop simulating at the same time.

Step	Main model	Co-model
0	0	10.0
1	1	10.1
2	2	10.2
...	...	...
50	50	15.0
...	...	...
100	100	20.0
As an example, you may have a main model which is simulating from time 0 to 100 and a co-model with time specifications of 10 to 20. When simulating, the two models will be run at different speed, with times synchronized as shown in the table above.

The times of the main model and the co-models may be set from the Simulation Setup dialog box by making selections in the Parallel Simulation list box, and entering values in the Times group.

By selecting several models in the Parallel Simulation list box, the simulation times and integration methods of the selected models may be set in one operation.


Co-models and Integration Methods

A possible reason for splitting a model into a main model and a set of co-models is the need for different integration methods for different parts of the model. One small part of the model may, for example, require a high integration order and a very small time step. If the entire model is very large, it may cause problems if the time-consuming integration method of the smaller model is used for the whole model.

In some cases the above problem may be solved by splitting the big model into a part that uses a higher order integration method with a small time step, and a part that uses a less accurate (but faster) integration method.


Using Different Integration Methods for Different Parts of a Model

To use different integration methods for different parts of a model

1	Split your model into two parts, say MAIN.SIM and CO.SIM

2	Open the MAIN model and make its window active (on top)

3	Open the Simulation Setup dialog box

4	Add CO.SIM as a co-model of MAIN by using the Add button

5	Select MAIN in the Parallel Simulation list box and define integration method (for example, Euler with a time step of 1)

6	Select CO in the Parallel Simulation list box and define integration method (for example, RK4-Var Step with a time step of 0.025)

7	Close the Simulation Setup dialog box and run the simulation


Communication Between Models

The above example works only if there is no information being transferred between the two models, MAIN and CO. This of course, is rarely the case. We therefore need a means of transferring data between the main model and its co-models (and between co-models directly).

This is done by adding chain objects. The chain object will connect a variable in one model to a variable of another model. Both source and destination variable may be chosen from either the main model or one of the co-models.

Hint	Co-models may be used to ease the process of synthetic data analysis, for example, by extracting a decision making or data input process from the rest of the system, and putting it in a co-model.

See

  Chaining Variables Across Models

  Restrictions on Chained Variables

  How Chains Are Updated

  Potential Problems Using Co-Models


Chaining Variables Across Models

To chain variables across models

Let us assume there is a variable, CO_X, in our co-model, and that we want the value of this variable to control the variable MAIN_X of our main model. In order to make a chain from CO_X to MAIN_X we do the following:

1	Make MAIN's window active

2	Select the Chain tool and place a chain object in the diagram of MAIN

3	Double-click on the chain object and select CO into the Models combo box in the Source group. Click on CO.CO_X in the Variables list box of the Source group. Main is already selected into the Models combo box of the Destination group. Click on MAIN_X in the Variables list box of the Destination group. The Source and Destination parameters should now be defined as CO.CO_X and MAIN_X, respectively.

4	Close the Define Chain dialog box (using the OK button).

Now you may simulate the models, and observe that the value of CO.CO_X is copied to MAIN_X during each simulation step.


Restrictions on Chained Variables

The destination variable (parameter) of a chain must be a constant variable or a level which is not initialized using an expression.

It is not possible to use the same variable more than once as a destination variable of a chain.

Variables that are used as input parameters to input objects, may not be destinations of chains.


How Chains Are Updated

Since the main model and every co-model may be simulated using different time intervals, time steps, and integration methods, the transfer of information through chains is synchronized by the main model. Powersim's algorithm for simulation and transfer of information is as follows:

1	Simulate all co-models to the point in time that corresponds to the next simulation step of the main model

2	Simulate the main model one step

3	Update the values of all chains by copying the value of the source parameter to the destination parameter

4	Repeat from step 1


Potential Problems Using Co-Models

The delay of one time step which is involved in transferring information through chains may cause problems in some models. If there is a feedback through the chain structure, for example, this may cause the same kind of oscillation problems as described for the Euler integration (see Comparing the Integration Methods ).

The delay between the update of the source and the destination variable is visualized in the diagram below. Observe that the chained variable (dotted line) is skewed one time step to the right compared to its source (solid line).


Several Instances of a Model

See

  Overview

  Opening the Main Instance of a Model

  Opening a Co-Model Instance of a Model

  Using the Same Model Several Times as a Co-Model


Model Class and Instance

A model is a "class" describing the structure of a system. When simulated, the model becomes an instance of this class. The instance carries out the computations described by the model equations. The same model may exist in several instances at the same time; as a main model, and as co-model of other main models.

Each instance of a model has its own data, meaning that variable values, variable scaling, integration method, etc. may vary among instances.

When working with co-models it is important to know the difference between the main instance of a model and a co-model instance of the model. The main instance may be simulated as a stand-alone model, displaying simulation results etc. according to its own definition. A co-model instance will be simulated along with its main model, displaying simulation results in the context of the main model and any other co-models which are part of the simulation.

The above figure illustrates how model instances are named in the caption (title) of the model windows. In the figure, two windows are opened on the model COMOD.SIM. The windows are numbered 1 and 2. For the left-most window (number 1) the text MAIN.COMOD is written inside angle brackets. This means that the window displays an instance of the co-model COMOD.SIM used by the model MAIN. In short, the title line is interpreted like this:

For main model instances:

For co-model instances:


Opening the Main Instance of a Model

The main instance of a model is opened using the File Open command (or the Open button in the commandbar).


Opening a Co-Model Instance of a Model

To open a co-model instance of a model

1	Make the main model current (activate window)

2	Open the Simulation Setup dialog box (from the Simulate menu)

3	Select the desired co-model from the Parallel Simulation list box

4	Press the Open button. A new window displaying the co-model instance will open (under the dialog box)

5	Close the dialog box using the OK button


Using the Same Model Several Times as a Co-Model

Suppose you have a generic model of a sub-system which exists in several copies in your target systems. The model of the sub-system may then be instantiated several times as a co-model of the bigger system.

Examples are competing factories; the finance sector of a generic company; etc. Another example may be a co-model which is performing analysis of an on-going simulation. Such a model may be hooked up in multiple copies, and linked to different variables of the system in each instance. In this way the same generic analysis may be performed on several variables, using several instances of the same model class.

Connecting the same model several times to a main model is done by using the Add button of the Simulation Setup dialog box. Each co-model instance may be opened using the Open button of the same dialog box. Information may be transferred between any model in the Parallel Simulation list box by adding Chain objects to the main model diagram.


Alternative Interfaces to a Model

The co-model feature may be used to create different interfaces to a model. This may be done by creating several main models that share a common co-model (class), in which the actual simulation takes place. In each main model, different dynamic objects may be created and connected to the variables of the co-model. The set of graphs, tables, sliders, etc. that are presented in the different main models may be freely chosen, independent on the co-model and the other main models. The above figure illustrates this way of using co-models. Note that the two main models will operate on different instances of the co-model.


Multiple Runs

This section describes how the data of a simulation run may be stored for later use, and how a series of simulation runs may be set up, for example, in order to perform a sensitivity analysis of a model.

See

  Generations - The Results of Previous Simulations

  Sensitivity Analysis

  Performing a Sensitivity Analysis

  Generating Test Input Data

  Examples of Test Data Distributions

  Generating Test Data within the Model

  Generating Test Data in a Co-Model


Generations - The Results of Previous Simulations

The time table and time graph objects operate on time series data, i.e., a set of parameter values corresponding to different points in time. During a simulation, a time series is created for each parameter of a time table or time graph object.

Creating a Generation - Saving the Result of a Simulation

By using the Generations dialog box of the time graph or time table object, current simulation results may be saved in a list of generations.

Displaying the Results of Previous Generations

The Display dialog box of the time table or time graph object is used to pick time series from the current simulation run, and from saved generations.

Example	The time graph displayed in Comparing Integration Methods Using Generations displays five generations of data from the same variable.

Clearing the Results of Previous Generations

The command Simulate Clear Results may be used to clear all generations of all time tables and time graphs from the current model. Individual generations may be removed by using the Remove button of the Generations dialog box (which is opened from the Define Time Table dialog box or the Define time graph dialog box).


Sensitivity Analysis

From the Run Setup dialog box it is possible to specify that a series of simulations be performed in a row. This feature is used mainly for testing the behavior of a model when given varying inputs.

The input of selected variables for each run may be defined as a function of the RUN function, which returns the current run number (counting from one).

See also

  Performing a Sensitivity Analysis


Performing a Sensitivity Analysis

To perform a sensitivity analysis

1	Make one or more time tables or time graphs where key variables are going to be compared for various input values to the simulation

2	Open each time graph/table definition dialog box, and:

a	Select the variables to be observed into the Parameters list box

b	Switch on Generations Simulation Starts New Generation

c	Switch on Display Add New Generation to Display List

3	Create the input function(s) that will generate test data for the model

4	Select the number of runs to be performed from the Run Setup dialog box

5	Start simulating by selecting Simulate Run or by pressing the Run button

6	If necessary, adjust the Y-axis of the time graphs to display the generated graphs in the desired scale


Generating Test Input Data

Test input data may be generated either by equations in the model to be tested, or by connecting the test model to a co-model supplying test-data.

See

  Examples of Test Data Distributions

  Generating Test Data within the Model

  Generating Test Data in a Co-Model


Examples of Test Data Distributions

Test data may be generated in an unlimited number of ways. The idea is that the data are going to vary according to some criteria between successive runs. Below, some common variations are illustrated:

Ad Hoc Variation

Here test data are taken from a list of values. The selection is based on the current run number. A convenient way to do this is using the GRAPH function. The values to be used for testing are stored in a vector which is passed as argument to GRAPH. Below is an example:

aux	AdHocVari = INIT(GRAPH(4*(RUN -1)/(RUNCOUNT -1), 0, 1, [1,5,3,9]))

If the number of runs is 4, the value of AdHocVari will be 1, 5, 3, and 9, respectively during the four runs.

Incremental Variation

This means that the input value is incremented in a linear fashion from an initial value which is used during the first run, to a final value for the last run. The example below will produce values from 4 to 13 during the runs:

aux	IncrVari = INIT(4+(13-4)*(RUN -1)/(RUNCOUNT -1))

Normal Variation

A variation according to the normal distribution is achieved like this (the mean of 0 and standard deviation of 1 may be changed according to needs):

aux	NormVari = INITINIT_Initial_Value>func (NORMALNORMAL_Normal_Distribution>func (0, 1))

Random Variation

A uniform random distribution between two limits is achieved in the following way (here min is set to 2 and max to 7):

aux	RandomVariation = INIT(RANDOM (2, 7))


Generating Test Data within the Model

Test inputs may be generated within a model by putting definitions, as described above, into the model. This way of testing may be sufficient if your model is small, and the number of tests is limited.


Generating Test Data in a Co-Model

Putting the test generation into the model which is being tested has the disadvantage that it requires modifications to the model during testing. It is also more difficult to save the test input specifications for later use if they are put into a model and removed later (when the model is found to be OK).

The test functions described above may readily be put into a separate model that may be linked to other models in order to produce test data. Using this approach, a model may be tested without modification. One way of doing this is to create a model in which the model to be tested and the test generation model are co-models. By creating chain objects in the main model, information from the test input model may be routed to variables in the model being tested. Test reports may be created in the main model by adding time graph and/or time table objects. This is illustrated in the figure below.

Making Test Data Model Read-Only

The model generating the test data may be made read-only, and put in a model library shared by several users. A model is made read-only by switching off the Allow For Edit attribute in the Access dialog box, which is opened by the File Properties Access command.


Terminology

This topic gives you a glossary of Powersim terms and definitions.

-A-

Accumulator

Anchor

API - Application Programming Interface

Area

Array

Array functions

Asymmetric game

Auto report

Auxiliary

-B-

Behavior

Bézier curve

Binary operator

Boolean values

Built-in functions

-C-

Causal-Loop Diagram

Choose

Click

Clipboard

Cloud symbol

Co-model

Command

Commandbar

Complex number

Computational parameter

Conditional functions

Constant

Constant expression

Constant function

Continuous systems

Control functions

Conversion functions

Cut

-D-

DDE

Decision file

Delay

Delay functions

Delayed Link

Delayed parameter

Dimension

Discrete delay

Discrete systems

DLL

Document

Double-click

Drag

Dt

Dynamic object

Dynamic scaling

-E-

Edit

Editing mode

Enumeration

Enumeration subrange

Exponential delay

Expression

-F-

Feedback

Feedback - Balancing (Negative)

Feedback - Reinforcing (Positive)

Field

Fixed scaling

Financial functions

Flow

Flow diagram

Focus

Function

Function indicator

Function group

-G-

Game file

Generation

Graph functions

Guard list

Guard

-H-

History functions

-I-

Index variable

Inflow

Initialization link

Input object

Instance

Instantiate

Integer number

Integration method

Interactive simulation

Internal level

-J-

-K-

-L-

Legend

Level

Link

Literal

Logical functions

-M-

Main model

Mathematical functions

MDI

Menu

Menubar

MFS

Miscellaneous functions

Model

Model object

-N-

Network game

Number object

Numeric picture

Numeric subrange

-O-

Object

OLE

Operational mode

Option

Optional parameter

Operator

Order

Outflow

Output object

-P-

Parameter

Pause mode

Pipeline delay

Player file

Postfix

POWERSIM.INI

-Q-

-R-

Random functions

Range

Rate

Real number

-S-

Scalar

Select

Simulating mode

Simulation

Side effect functions

Snapshot

Source/Sink

Start-up parameter

Static object

Statistical functions

Statusbar

Steady state

Strategic mode

Structure

Subrange

Subscript

Symmetric game

System

-T-

Time series

Time

Time-related functions

Time step

Text box

Toolbar

Transfer object

Trigonometric functions

-U-

Unary operator

Unit

Unit expression

-V-

Variable

Vector

View

-W-

Workspace

-X-

-Y-

-Z-


Accumulator

See level


Anchor

A variable object or an external object can be the anchor object of a selection. A variable object is the anchor if its name is highlighted; an external object is the anchor if its handles are filled (not hollow). The anchor is of importance, for example, in an align operation where all the selected objects are aligned with the anchor object.


API - Application Programming Interface

Interface to Powersim that lets another program access Powersim. This can be used, for example, to create simulator interfaces on Powersim models.


Area

A rectangular selection in a diagram, accomplished by pressing the right mouse button while dragging. Leaves a dotted frame that shows the extent of the area. The contents of the area may be copied to the clipboard, allowing for export of OLE objects, bitmaps, or pictures to other programs.


Array

An indexed model variable that represents a set of related values. Each array element holds one value. A double-framed level, auxiliary, or constant symbol in a flow diagram indicates an array variable. (Contrast with scalar.)


Array functions

A group of functions that utilize one or more arguments which are arrays. Note that Powersim also has functions that return arrays.


Asymmetric game

A network game where the players have different roles. A game where a factory, a distributor, a wholesaler, and a retailer are played by different players is an example of an asymmetric game. If all the players play the role of a distributor, the game is symmetric.


Auto report

Auto reports are presentations of simulation results automatically displayed within or next to variable symbols in a diagram.


Auxiliary

A variable type and a model object in Powersim models.


Behavior

How a model or certain variables of a model develop(s) over time. For example, the Population level of the demo model POPSIMPL.SIM shows a behavior characterized by exponential growth. According to the system dynamics paradigm, a system's structure is responsible for its behavior.


Bezier curve

A particular spline curve named after the engineer Pierre Bézier. It takes four points to determine a Bézier curve: two end points and two control points. The control points influence the line's curvature. Editing a Bézier curve is done by moving the "handles" that appear when the curve is selected (see figure below).

Link arrow with handles


Binary operator

An operator that takes two operands, for example "*" (multiplication). In the expression "50 * 2", "50" and "2"are the operands and "*" is a binary operator. Contrast with: Unary operator


Boolean values

Either True or False. In Powersim the value 1 represents True and 0 represents False. The condition of a conditional function is boolean, meaning that the only significant values of the conditional parameter is True or False.


Built-in functions

A group of functions that are part of the simulation language itself. All other functions are external to the system, and are loaded from DLLs  during system initialization. The list of function DLLs is stored in the POWERSIM.INI file.


Causal-Loop Diagram

A diagram containing variables and the influence links between them. Focuses on the principal causal-loops in a model and does usually not distinguish between the different types of variables (levels, rates) and connections (links, flows) as does the flow diagram. A causal-loop diagram therefore typically contains less information than a flow diagram.


Choose

To use a mouse or key combination to pick an item that begins an action in Powersim.


Click

To quickly press and release the mouse button.


Clipboard

The Windows clipboard provides temporary storage for information you want to transfer. You can cut or copy information from an application onto the clipboard and then transfer (paste) that information from the clipboard into other applications. The clipboard holds its current information until you perform a new cut or copy operation.


Cloud symbol

Indicates that the sink or source of the connected flow lies outside the boundaries of the model.


Co-model

Powersim provides means of synchronizing individual models during simulation (concurrent simulation). This is done by hooking co-models up to a main model, which then controls the simulation process of its co-models.


Command

A command is an instruction that tells Powersim to do something. You can choose a command by:

•	Clicking a toolbar button with the mouse

•	Choosing a command from a menu

•	Using a shortcut menu

•	Using shortcut keys

A command name in a menu or dialog box followed by an ellipsis (...) indicates that a dialog box exists so you can set the options you want.


Commandbar

The commandbar is located below the menubar, and contains a set of buttons for performing the most frequently used commands in Powersim.


Complex number

A complex number is represented in Powersim as in Cartesian format as a vector with two elements. The first element holds the real part, and the second element holds the imaginary part of the complex number.


Computational parameter

A parameter that is evaluated by its function.


Conditional functions

A group of functions that perform different tasks, based on conditions which are passed as arguments to the functions. A condition is considered to be true if its rounded value is not zero.


Constant

A variable type and a model object in Powersim models, used to hold constant values. Typically used as parameters for tuning a model and receiving user input during a simulation run.


Constant expression

Expressions that will be constant during a simulation run.


Constant function

A function whose values will not change during a simulation run.


Constrained expression

Array variables may be defined in terms of constrained expressions. That is an expression followed by a constraint which specifies which part of the array the expression defines.


Constraint

A constraint is part of a constrained expression, specifying the index range(s) for which the preceding expression is going to be used. A constraint consists of one or more list of guards, preceded by the guard operators, vertical bar (|) or WHEN.


Control functions

A group of functions used to control a simulation run.


Continuous systems

Systems where variables change in a continuous manner, for example, the movement of planets, temperature changes, population growth, etc. (Contrast with Discrete systems )


Conversion functions

A group of functions converting a value from one type to another. The group includes conversions between different angular measurements, i.e., degrees, radians, and gradients. Functions for converting floating point numbers to integers are also included.


Cut

To remove selected text or objects from a document so that you can place, or paste, it in another location in the active document or in another document.

Powersim places the cut and copied information in a temporary storage area called the clipboard.


DDE

DDE stands for Dynamic Data Exchange, which is a standard Windows approach to data exchange between applications. If you for example wish to run a Powersim model as part of another application the DDE source capabilities of Powersim let you establish a DDE link from this application to Powersim. Indeed this module opens new horizons for the creation of games and management flight simulators.

Using the DDE transfer object, Powersim acts as a DDE client, sending and receiving data. Powersim may also act as a DDE server, allowing other applications to start and control Powersim using DDE commands .


Decision File

Each network game players decisions are stored in a separate file on the common network drive (extension TXT). Before a game starts, the game administrator will normally delete old decision files.


Delay

When an influence from a variable A to another variable B does not take effect immediately (i.e. within the same time step) the influence is said to be delayed. In other words the value of B at a particular point in time is based on A's value at an earlier point in time. Delayed influences may be achieved in two ways: 1) By using rate-to-level connections, and 2) By using Delay functions.


Delay function

A group of functions that imply a delayed influence. The group contains material delay, information delay, and "infinite order" pipeline delay. Delay functions imply one or more "hidden" rate-to-level connections, i.e., Powersim generates internal levels.


Delayed Link

An object type in Powersim models. Represents a delayed relationship (defined by a Powersim equation containing a delay function) between two variables connected by the link.


Delayed parameter

The value of the parameter is not used by its function until the next step of the simulation.

aux	B = DELAYINF(A, 1)	"A is a delayed parameter"

aux	B = SQRT(A)	"A is not a delayed parameter"


Dimension

In Powersim, array variables can be of one or more dimensions. Each dimension is an indexed axis containing storage cells for variable values. The declaration of the dimensions of an array is done in the Dimension box of the Define Variable dialog box.

A one-dimensional array (also called a vector) can be depicted as a one-column, multi-row table of values, where each row has an index number. A two-dimensional array (also called a matrix) can be depicted as a multi-column and multi-row table where a certain cell (value) can be accessed by using the index pair: (column-index, row-index).


Discrete delay

See Pipeline delay


Discrete systems

Systems where variables change in steps at specified points of time, for example, bank deposits and withdrawals, serving queue systems, etc. (Contrast with Continuous systems )


DLL

Dynamic Link Library. Dynamic linking is a mechanism provided by Windows to allow linking of a program with the routines of a library at run time (contrast with static linking). In Powersim, the functions and the external objects are contained in DLLs, so that new functions and objects can be added without changing the application itself.


Document

In Powersim, there is only one document type. A document contains structure objects (model objects) and behavior objects (external objects), and is saved on a file with the SIM extension. Since Powersim is a multiple document interface (MDI) application, the user is allowed to have multiple documents open at the same time.


Double-click

To click the mouse button twice in rapid succession.


Drag

To hold down the mouse button while you slide the mouse.


Dt

An acronym for "delta time", which means a certain addition or increment to time. In Powersim the term dt appears only in the definition of level variables. Example:

level Population = 100 +dt*Births -dt*Deaths

In this context it represents the integration interval used by Powersim when computing the values of the flows that change a level each time step in a simulation. The time step is defined by the setting of Time Step in the Simulation Setup  dialog box. Provided that Euler is chosen as the integration method, dt may be considered equal to the time step (See also time step.)


Dynamic object

Dynamic objects are used to display simulation results and to adjust model parameters.They present the simulated values of selected variables as time emerges.


Dynamic scaling

The variable's min/max values are automatically set to the lowest/highest simulated value whenever a simulation run is stopped or paused.


Edit

Editing a Powersim object means to make changes to the object's definition. Examples are changing the expression defining a variable, changing the selection of variables being presented by a dynamic objects, and changing style, size, and position of any object.


Editing mode

When a model is not being simulated (the Run button is not pressed), all the documents' associated windows are in editing mode. In this mode it is possible to edit objects and change simulation settings, ranges, units, etc.

When a model is in editing mode, it can be put in simulating mode by choosing Simulate Run , by choosing Simulate Pause  and Simulate Run  in sequence, or by choosing Simulate Run Step .


Enumeration

A Powersim range type which is an ordered set of text elements, for example: North, South, East, West. One of three range types that can be chosen in the Define Range dialog box.


Enumeration subrange

A Powersim range type which is a subset of an enumeration.  One of three range types that can be chosen in the Define Range dialog box.You use element names of an enumeration range to define the bounds of an enumeration subrange. In the example below, Area is an enumeration range, and Area2 is a subrange:

range	Area = North, South, East, West

range	Area2 = North..East


Exponential delay

A delay process where the input flows through one or more levels. The number of levels is the order of the delay. As the order increases the result approaches that of a pipeline delay. DELAYINF and DELAYMTR are exponential functions.


Expression

Expressions may contain parentheses, literal numbers and arrays, variable names, functions, and operators.


Feedback

Feedback occurs when a change in one part of a system produces changes in the whole system which then "feed back" through the system and affect the original part again. Feedback processes can be modeled using Powersim, e.g., by letting a level be influenced by a flow which is controlled by an auxiliary that is influenced by the level.

In the figure above the level Population is influenced by its input flow which is controlled by the auxiliary Births which is in turn influenced by Population. (Demo POPSIMPL.SIM)

Generally, there are two classes of feedback loops: 1) balancing or negative loops., and 2) reinforcing or positive loops


Feedback - Balancing (Negative)

When a change is reduced or dampened through a feedback loop and thereby causing the changed variable to be changed in the opposite direction.

Example: A rising population causes the number of annual deaths to rise, which reduces the population and causes the numer of deaths to decrease. When dominating this type of loop will stabilize the system, i.e., the system level (in this example Population) will seek an equilibrium state. (Demo: POPSIMPL.SIM)


Feedback - Reinforcing (Positive)

When a change is reinforced through a feedback loop and thereby causing the changed variable to be further changed in the same direction.

Example: A rising population causes the number of annual birhs to rise, which further increases the population and causes the numer of births to increase even more, and so on... When dominating this type of loop will destabilize the system, i.e., the system level (in this example Population) will show an exponential growth. (Demo: POPSIMPL.SIM)


Field

A field is a set of codes that can be used in the definition of Page Setup and some Powersim object types to retrieve and display various information from a document or from the computer's internal clock and calendar. For example, the TIMESTEP field retrieves and displays the current value of the simulation time step.


Financial functions

A group of functions covering computations of present value, future value, and periodic payments.


Fixed scaling

The variable's min or max value is fixed to the value defined in the Scale dialog box. It is not affected by the simulation results.


Flow

An object type in Powersim models. A flow represents the idea of quantities being transported between level variables. Levels are changed by adding the values of inflows and subtracting the values of outflows from their current values. Since flows are added to or subtracted from levels, flows must have the same unit of measure as the connected levels. The value of a flow is therefore defined as the associated rate variable multiplied by the time step. When referring to the time-relative values of flows into or out of levels, we recommend the term flow rate (or simply rate).


Flow diagram

A model diagram containing variable symbols (levels, auxiliaries, and constants), flows, and links. Such diagrams are sometimes also referred to as accumulator-and-flow diagrams (AFD) or stock-and-flow diagrams. A flow diagram typically contains more information than a causal-loop diagram.


Focus

A focused variable object has its variable name selected, while other focused objects have filled handles.


Function

Functions are used to describe the relationship between variables in a model. If, for example, one variable is to be the square root of another variable, the SQRT function may be used. Since functions are stored in DLL-files, your Powersim system may be extended with new functions by adding new function libraries to the system.


Function group

The functions of Powersim are organized into groups. Some functions are assigned to more than one group. This makes it easier to select the correct group when searching for a function, for example in the Functions list of the Define Variable  dialog box.


Function indicator

A function indicator shows that an auxiliary is defined by means of a function that may require special attention. For example, it may be convenient to quickly be able to spot all the variables that use stochastic (random) functions in a diagram, without having to examine each one in turn. In Powersim there are six categories of such "special attention" functions, each having their own function indicator symbol. The Function Indicator Table  lists all standard functions in each of the categories.


Game File

The purpose of a game file is to define a mode in which a network game can be played, e.g., one player against the computer, three players against each other, etc. Game files should be shared by all participating games (the files should be located at the shared network disk drive). By convention, game files have the extension PSS (Powersim Server).


Generation

A time series of values produced by a simulation run. When multiple runs are performed, the time table and time graph objects can be used to show the results of several generations for comparison purposes.


Graph functions

A group of functions whose results are tabulated for given input values. These tabulated values are sometimes called samples or fix points. When an input to a graph function does not correspond to any of the tabulated values, various kinds of interpolation and/or extrapolation are used to determine the value of the function.


Guard

A guard is used to constrain the definition of an array based on the value of and index variable.


Guard list

A sequence of guards, separated by AND. If there are more than one guard list for a constraint, they are separated by OR .


History functions

A group of functions where past values of arguments are used in computing the value of the function.


Index variable

A local integer variable defined and used inside the definition of an array variable in order to index a dimension. By testing on index variables we may assign different values to different parts of an array. An index variable is defined in the Dimension box of Define Variable  (and in the SUM function) and may be used in the Definition box. Since index variables are local to the definition of a single variable it is possible to use the same name for index variables in defining different variables. Index variables are not visible in a model diagram.


Inflow

A flow which is running into a level, i.e. the value of the flow variable multiplied by dt  is added to the level each time step in a simulation. Note that a flow may be both an inflow and an outflow at the same time.


Initialization link

Information link connected to a level or a constant, used to compute the initial step of the simulation. An initialization link is depicted by a dotted arrow. To create an initialization link, you select the ordinary link tool and the arrow becomes dotted once Powersim detects that it is an initialization link.

To initialize a level or a constant analytically, as a function of other variables, you must create an initialization link from each of these variables to the level or constant.


Input object

A dynamic object type that may receive user input before or during a simulation run.


Instance

A model is a "class" describing a structure of a system. When simulated, the model becomes an instance of its model class. Multiple instances of a model may exist at the same time (for example, when a model is both a main model and a co-model of another main model). Each instance has its own set of data, allowing concurrent simulation to take place.


Instantiate

When a new instance of a class is made, we say that the class is instantiated.


Integer number

A whole number, with no decimals, for example 5. Index variables in Powersim are always integers. Contrast with real number.


Integration method

Integration is the process of adding the sum of the levels' rates of flow to the current value of the levels each time step during a simulation. There are several methods, or algorithms, available for performing the integration in Powersim. The simplest, and most commonly used, is the Euler method.


Interactive simulation

By this we mean that you can adjust a model's parameters during a simulation run. It may be accomplished using any of the input objects of Powersim.


Internal level

Delays may be modeled in Powersim using flows that run through levels. To simplify your flow diagrams you may also represent delays using special delay functions. These functions generate and use internal or "hidden" levels to compute the delayed values.


Legend

A legend is a key that identifies the series markers in a graph plot. The legend includes each color, pattern, number, or symbol used as a marker, followed by the corresponding variable name.


Level

A variable type and a model object in Powersim models, used to represent the state variables of a system. Levels accumulate connected flows.


Link

An object type in Powersim models. Represents a relationship (defined by a Powersim equation) between two variables connected by the link. Establishes a permanent influence (also called information link) from a variable of any type to an auxiliary variable, or establishes an initialization influence from a variable of any type to a level or a constant variable.


Literal

By the term literal we mean literal numbers, for example 123, and literal arrays, for example [1,2,3].


Logical functions

A group of functions returning a logical value representing True or False. Powersim does not treat logical values as a separate data type. Instead the number zero is used to represent logical False. All other scalar values are considered to be True when treated as logical values. Logical values are rounded to the nearest integer before comparing.

The logical functions are closely related to Conditional functions. Also, some Time Related functions return boolean values.


Main model

A model which controls the concurrent simulation of its co-model. A model that has no co-models, may also be considered a main model.


Mathematical functions

A function group containing all kinds of mathematical calculations.


MDI

Multiple Document Interface. An MDI application is able to manage multiple documents, or multiple views of the same document, within the main application window.


Menu

A list of items. Most menu items are Powersim commands.


Menubar

The menubar is located below the title bar at the top of the application window and contains all the Powersim commands. To view all the commands in a menu, do one of the following:

•	Click the menu name

•	Press Alt + N , where N is the underlined letter in the menu name

For example, press Alt + F to open the File menu.


MFS

Management flight simulator. Simulation model with gaming interface for communicating the results of simulations to managers who were not involved in the modeling process.


Miscellaneous functions

A function group containing a variety of functions that do not fit well into other groups.


Model

A structural description, or representation, of an imaginary or real system. A Powersim model is described in terms of a diagram, which in turn consists of interconnected variables. A Powersim model can be simulated, and the resulting behavior may be used to make assumptions about the behavior of the real system.


Model object

Model objects are used to specify a model's structure. That is, the variables and the links and flows that influence the variables. Basically, there are six model object types: levels, auxiliaries, constants, flows, links, and delayed links.


Network game

Multi-user simulation game based on a Powersim model. May be created and run in Powersim using the network game object.


Number object

A dynamic object type in Powersim. See: Number Object


Numeric picture

A numeric picture describes how numbers will be output. See Number Formatting


Numeric subrange

A Powersim range type which is an interval of numbers, for example:

range	Area = 1..3

This is one of three range types that can be chosen in the Define Range dialog box.


Object

The term "object" have several meanings. In this documentation we normally speak of Powersim objects.

Powersim object

A Powersim document may contain objects of various types. Powersim objects fall into four categories: model objects, dynamic objects, static objects, and transfer objects.

Linked object

An entire Powersim document may appear inside another application as a linked object. It will then be regarded a Powersim Diagram object which can be edited from within this application.


OLE

Stands for Object Linking and Embedding. In short, this means that entities from one application may be included in another application. For example, a Powersim diagram may be included in an Excel spreadsheet document.


Operational mode

When accepting decisions using the Accept Decisions button of the game control dialog box in a network game, the simulator uses actual decisions of both player and competitors to control the decision variables of the game.


Operator

Operators are mathematical symbols, such as *, +, /, etc., used in the definition of Powersim variables. Operators may be unary or binary.


Option

Preference that can be set by the user, usually in the Options  dialog box. One example is, whether to show question marks in undefined variables or not.


Optional parameter

A function parameter that is optional, i.e., it may be left out.


Order

The order of an integration method determines the number of calculations that are performed in estimating the changes in level variables during a time step .

The order of a delay determines the number of levels that the delayed flow will run through.


Outflow

A flow which is running out of a level, i.e. the value of the flow variable (multiplied by dt ) is subtracted from the level each time step in a simulation. Note that a flow may be both an inflow and an outflow at the same time.


Output object

A dynamic object type that presents simulation results using a visual or audible presentation method.


Parameter

1	If the value of a variable is to be presented or adjusted by a dynamic object or a transfer object, the variable is said to be a parameter to this object. The parameters of an object is chosen in the object's definition dialog box.

2	A parameter also means an argument to a function.

3	A constant that is used to tune the behavior of a model, is also referred to as a parameter of the model.


Paste

To insert cut or copied text or objects into a document at the insertion point from the temporary storage area called the clipboard.


Pause mode

When a running simulation is being paused (both the Run button and the Pause button are pressed), Powersim is said to be in pause mode. The pause mode may be looked upon as a "sub-state" of the simulating mode, since the same editing limitations go for the pause mode as for the simulating mode. One difference is that the simulation is not actually running. Another is that some dynamic objects allow input only in pause mode.

When a model is in pause mode, it can be put in simulating mode by hitting the down-pressed Pause button or choosing the checked Pause entry in the Simulate menu. It can be put in editing mode by choosing Simulate Stop


Pipeline delay

The delayed quantity is exactly replicated after the delay time has elapsed. (Also called "discrete delay".) To represent a pipeline delay in your model, use a DELAYPPL function.


Player file

A file type used by Network Game objects. Each network game must have a network game object referring to a local player file (extension PSN for Powersim Node). The player file lists the different game set-ups that are available to this player, along with the associated player numbers.


Postfix

Postfix means that the operator is put behind the operand it is working on. For example % is a postfix operator converting a value from per cent to a regular number, e.g. 7% = 7/100 =  0.07.


POWERSIM.INI

POWERSIM.INI is the name of a system file which holds information about system setup, user preferences, etc. See also: POWERSIM.INI - Search Order and POWERSIM.INI - List of Sections


Random functions

A function group containing functions that depend on the random number generator of Powersim. Successive calls to these functions do not normally produce the same result. Instead the values are distributed according to various criteria given by the particular function.


Range

The limits between which an index is allowed to vary. An example of a numeric range is 1..3. Powersim allows you to define named ranges, which can then be used to define the dimension of an array variable.


Rate

A variable that controls a flow. In Powersim all three variable types (auxiliaries, constants, and levels) may control flows. In other words, the term rate is not used to denote a variable type, since a variable of any type may be used as a rate.

A rate will always have a unit of measure relative to time. E.g., if the time unit is "Week", and a rate is controlling a level with "Products", the rate's unit should be "Products/Week".


Real number

A decimal number, for example 1.25. All simulated values of Powersim variables are expressed in real numbers. Contrast with integer number.


Scalar

A variable that represents a single value.

Contrast with: array


Select

To mark an item by highlighting it with key combinations or by clicking it with the mouse. Selection does not initiate an action. After selecting an item you choose the action you want to affect the item. For example, you might select an item in a list box and then choose Remove to remove the item from the list.


Simulating mode

When a model is being simulated (the Run button is pressed), all the documents' associated windows are in simulating mode. In this mode, editing is prohibited. When a model is in simulating mode it can be put in editing mode by choosing Simulate Stop, or by letting a simulation run till it reaches the stop time.


Simulation

The process of conducting experiments on a model instead of attempting the experiments with the real system. Technically, simulation portrays the development of the variables of a system over time. The simulation time is divided into small steps, and mathematical techniques from integral calculations are used to update the current state of the system for each step.


Side effect functions

The definition of a Powersim variable may contain functions, such as the STEP function in the example below:

A = B + STEP(10, 2)

Some of the standard functions in Powersim also influence other variables than the one to the left-hand side of the equal sign. In the example below, the function ASSIGN influence both A and B.

A = ASSIGN(B, 2)

In the diagram view of the above equation (see above), there is no visual link from A to B in spite of the fact that the definition of A indeed influences B. We therefore say that the ASSIGN function has side effects.


Snapshot

A variable symbol with an extra set of corners to indicate that it is a picture or a copy of another variable. Snapshots are useful for linking variables located in different parts of a model. You create a snapshot by using the Camera tool.


Source/Sink

When a flow in a model have a source or a destination which lies outside the modeled system, this is illustrated by putting cloud symbols (sources/sinks) at one or both ends of the flow arrow.


Start-up parameter

When a function uses a start-up parameter the initial value of the parameter is used for the rest of the simulation.


Static object

Static objects are used to customize model diagrams, draw causal-loop diagrams, and to provide various kinds of information using text and graphics. The term "static" indicates that the appearance of the objects are not affected by simulation results, in contrast to dynamic objects.


Statistical functions

A group of functions that perform computations on a set of data provided as arguments to the functions.


Statusbar

If visible, the statusbar is displayed at the bottom of the Powersim application window. It contains different kinds of status information, for example, context-sensitive menu help and the current simulation time.


Strategic mode

When running a network game, the user may try out decisions by selecting the Try Decisions button of the game control panel. The game is then assumed to run off-line, using the player's assumptions about his competitors' decisions instead of the competitors' actual decisions as the values of the decision variables of the competitors.


Steady state

A condition where all inflows and outflows, and the level(s) between them, are constant.


Structure

A collection of system components (variables) and the relationships between them (flows and links). As an example, the variables Population and Births in the demo model POPSIMPL.SIM form a structural relationship called a self-reinforcing feedback loop. The intrinsic behavior of such a structure is exponential growth.


Subrange

A range variable which is defined in terms of another range variable. A numeric subrange is a subrange of all positive integers. An enumeration subrange is an interval inside the interval of its "super-range".


Subscript

When using an array variable in the definition of another variable, you may select elements from the array by adding a parenthesized list to the variable name. In the example below, "(Young, North)" is a subscript:

aux	YoungNorthernPeople = Population(Young, North).

If a subscript contains a range, the result of the subscribed array will itself be an array. Example:

aux	YoungPeople = Population(Young, North..South).


Symmetric game

A network game where all participants of the game are playing similar roles, meaning that all players have the same decisions to make. If the players have different roles the game is said to be asymmetricAsymmetric_game.


System

A collection of parts which interact with each other to function as a whole. The variables of a Powersim model can represent parts of a real world or imaginary system. According to the system dynamics paradigm, there is a close connection between a system's structure and a system's behavior.

In some contexts a computer program, such as Powersim, is also referred to as a system.


Time series

A list of values at different points in time for a variable. A time series expresses a variable's behavior.


Time

The current time of a simulation, starting at Start Time and ending at Stop Time as specified in the Simulation Setup  dialog box. The function TIME can be used to make time dependent expressions.

Time Unit = 1/Timestep


Time-related functions

A function group that contains functions utilizing parameters or returning values that are expressed in the time unit of the simulation.


Time step

The time increment for each step of the simulation, as specified in the Time Step text box of the Simulation Setup  dialog box. The function TIMESTEP returns the time step chosen for the model.


Text box

An editor for entering textual or numerical input in a dialog box.


Toolbar

The toolbar is located below the commandbar and contains a set of buttons for creating and editing objects.


Transfer object

Transfer objects facilitate transfer of information between model variables and variables of other models, external files, and other applictions.


Trigonometric functions

A group of functions for trigonometric operations.


Unary operator

An operator that takes only one operand, for example "%" (percent). In the expression "50 %", "50" is the operand and "%" is a unary operator. Contrast to: Binary operator


Unit

A specified amount of a quantity, by comparison with which another quantity of the same kind is measured; for example, meter to measure length. Powersim allows you to define units, and assign a unit of measure to each variable of a model.


Unit expression

A unit expression can be either a single unit name or a mathematical expression involving one or more unit names.


Variable

A named component of a model representing some quantity in the modeled system. Examples of variables in a demographic model (see demo model POPSIMPL.SIM) may be Population, Births, and Deaths. Each variable in a model has its own numerical value which may change during a simulation run. The development of a variable's value is determined by the variable definition, which is normally a mathematical expression.


Vector

A one-dimensional array. Example:

const	Age_Groups(Young, Adult, Old) = [200,650,508]

The example shows the definition of a vector that holds the number of people in three different age groups.


View

The way a document is presented to the user. In Powersim there are two: diagram view and equations view. The diagram view is the view for building and viewing models. It displays a model's structure using flow diagram symbols. The equations view displays a textual representation of the model.


Workspace

The workspace is the place where you build your causal-loop and flow diagram models and create and define various objects.

Each object type has its own definition editor, named "Define <object type>", for example Define Time Graph. The definition editors are dialog boxes that open when you double click on an instance of their corresponding object type.

The workspace can present a model in two views: diagram view and equations view.


Using the Powersim API

Introduction

Overview of Powersim API

Powersim Connections

Using C/C++

Using The Powersim Connection OCXs

Using The Powersim Connection Delphi Component

Advanced Topics


Introduction

Although Powersim has many advanced input and output capabilities (such as the multimedia object), there are limits to what you can do within the user interface of Powersim alone. Some projects simply require highly specialized interfaces to the underlying model. To build such interfaces you will need generic development tools like Visual Basic, Visual C++ or Delphi. However, you still need the powerful simulation engine of Powersim to run the model for you behind the scenes. So far, the only possibility to access Powersim programmatically has been through DDE connections. Although this has been considered quite powerful compared to competitors, there has been a growing demand for other ways to access the functionality of Powersim. Therefore we introduce Powersim API with Powersim 2.5.

Powersim API (or PSAPI for short) consists of a set of different interfaces that allow you to connect to a Powersim model from another application. No matter which interface you choose, Powersim must be run as a separate server application to handle requests from your client application. Normally, the Powersim application will be minimized and all user interactions will be performed in the client application.


Overview of Powersim API

The following components are described below:

PSAPI16(32)/PSXOAPI

PSAPI.H, PSAPI16(32).LIB, CONNECT.H and CONNECT.CPP

Powersim Connection OCXs

Powersim Connection Delphi Component


PSAPI(32)/PSXOAPI
PSAPI16(32)/PSXOAPI

The communication between Powersim and a client application, is handled by a pair of DLLs, PSAPI16.DLL and PSXOAPI.DLL. The client connects to PSAPI16.DLL which interacts with PSXOAPI.DLL on the server side. PSXOAPI.DLL is specified in POWERSIM.INI as an external Powersim object DLL. If the client is a 32-bit application, it must use PSAPI32.DLL instead of PSAPI16.DLL. PSAPI32.DLL communicates with the same PSXOAPI.DLL as does the 16-bit version. These DLLs are installed with every copy of Powersim, PSAPI16(32).DLL in the system directory and PSXOAPI.DLL in the directory where Powersim is installed. This means that all copies of Powersim are ready to facilitate communication with a client application. You will, however need a professional version of Powersim to be able to build client applications.


PSAPI.H, PSAPI(32).LIB, CONNECT.H and CONNECT.CPP
PSAPI.H, PSAPI16(32).LIB, CONNECT.H and CONNECT.CPP

Client applications developed in C or C++ can use the C-style API of PSAPI16(32) directly. PSAPI.H specifies the interface of PSAPI and can be included in both 16-bit and 32-bit C/C++ files. The library files PSAPI16.LIB and PSAPI32.LIB are used when linking. There are also two accompanying C++ files, CONNECT.H and CONNECT.CPP, which provide a C++ class, CPsConnection, built on PSAPI. This class is invaluable when building C++ applications that interact with Powersim (also used to implement the Powersim connection OCXs, see below).


Powersim Connection OCXs

The Powersim Connection OCX (housed in PSCNCT16.OCX) is a 16-bit OLE control interface to the functionality of PSAPI. PSCNCT32.OCX is the 32-bit variant. The OCXs offer a number of properties, methods and events that make it easy to access Powersim models in OLE control containers like Visual Basic 4.0, Access 7.0 and Visual C++ 4.0.


Powersim Connection Delphi Component

The Powersim Connection Delphi component offers the same functionality as the Powersim Connection OCXs, i.e. it is a Delphi interface to PSAPI. The component makes it easy to access Powersim models from 16-bit Delphi projects.


Powersim Connections

No matter which interface you choose for connecting to a Powersim model, there are some general principles that apply.

Opening and Closing Connections

Parameter Lists

Simulation Control

Notifications


Opening and Closing Connections

Before you can do anything else, a connection to a Powersim model must be opened. When opening a connection, you specify the name of the model and you receive a connection handle which is used in all further operations on the connection. The specified model will be loaded into Powersim. If Powersim was not running prior to opening the connection, it will be started.

When the connection is no longer needed, it must be closed. If the corresponding model in Powersim was not changed, it will also be closed. Furthermore, if Powersim was started to serve this connection, and there are no other connections or separately loaded models, it will shut down as a consequence of the closed connection.

If you use the OCX or the Delphi component to establish a connection to Powersim, many of the details concerning connection handles and opening and closing of connections will be handled internally in the control/component.


Parameter Lists

Opening a connection to a Powersim model is of little or no use if you cannot access the variables of the Powersim model.

A Powersim connection has an associated parameter list that the client application builds. The parameters in this list are linked to variables in the Powersim model. If a client application wants to set or get a value of a variable in the model, it must add a new parameter to the parameter list. When adding a parameter you specify the name of the corresponding Powersim variable and receive a parameter index which is then used to identify the parameter in subsequent operations. Normally, only a small subset of the variables in a model will be of interest in a connected client application. Besides retrieving and setting parameter values, you can obtain units and min and max scales for parameters.

Once again, some of the details are hidden under the hood if you use the OCX or the Delphi component.


Simulation Control

The Powersim connection also provides functions to control the simulation. It is possible to start, stop and pause the simulation. The client application may also observe or set the time specifications of the simulation (start time, stop time, time step and delay time).


Notifications

A client application will be notified about important events in Powersim, e.g., that the simulation has started or terminated or that the values of Powersim variables have been updated. Use these notifications to do necessary processing at an appropriate time. For example, when a client is notified that values have been changed, it should update all controls (like graphs or gauges) that show parameter values.

During handling of notification messages, the client application is not allowed to yield control to the operating system by calling Yield, PeekMessage, GetMessage or by using DDEML for synchronous DDE. Violating this rule may jeopardize the entire system.


Using C/C++

Using PSAPI directly through the C-style interface is the traditional way of accessing a service in Windows. It is a bit more cumbersome than using the OCXs or the Delphi component, but on the other hand it gives you full flexibility.

Installed Files

Using C

Using C++

Samples


Installed Files

The following files are installed to \powersim\psapi\cpp:

File	Description
PSAPI.H	Header file containing the interface to PSAPI16.DLL and PSAPI32.DLL.
PSAPI.HLP	Help file describing the PSAPI interface as well as the CPsConnection class
PSAPI16.LIB	Library file to be used in 16-bit projects
PSAPI32.LIB	Library file to be used in 32-bit projects
CONNECT.H	Contains the header file for the CPsConnection class built on top of PSAPI
CONNECT.CPP	Contains the source file for the CPsConnection class built on top of PSAPI


Using C

If you choose to build a client application using plain C, you will find information about PSAPI in PSAPI.HLP. See also comments in the PSAPI.H header file.

Note that PSAPI.H is used both for 16-bit and 32-bit applications. In 32-bit projects, the WIN32 preprocessor definition must be set prior to including PSAPI.H. This is probably done automatically by your development system.


Using C++

When developing a client application in C++, you can of course use the C-style interface defined in PSAPI.H, but we recommend the overlay class CPsConnection defined in CONNECT.H and CONNECT.CPP.

CPsConnection relieves you of some of the dreary details of handling notifications by giving you suitable notification member functions to override. It also hides the concept of connection handles and gives you a number of member functions for simulation control (hiding PSAPI_SetControlValue calls with different control identifiers).

The help file PSAPI.HLP also describes CPsConnection. Comments in CONNECT.H and CONNECT.CPP will give you further information. CONNECT.H and CONNECT.CPP are written for Visual C++ (which is used to implement both 16 and 32-bit Powersim connection OCXs), but should be very easily adapted to other development tools.


Samples

The \powersim\psapi\cpp\samples directory contains a very simple Visual C++ 4.0 example of how to use CPsConnection in a 32-bit project. Although not much worth as a stand-alone application, this small example will give you a flying start if you insist on using C++ as your development platform.


Using The Powersim Connection OCXs

The Powersim connection OLE controls can be used to access Powersim models from development tools supporting the OLE control container interface, e.g., Microsoft Visual Basic 4.0, Microsoft Access 7.0, Microsoft Visual C++ 4.0 and Borland Delphi 2.0.

Installed Files

Registering and Licensing

Getting Help

Samples


Installed Files

The following files are installed to \powersim\psapi\ocx16:

File	Description
PSCNCT16.OCX	The 16-bit Powersim connection OLE control
PSCNCT16.LIC	The license file for the 16-bit OCX
PSCNCT16.HLP	The help file for the 16-bit OCX
OC25.DLL	A Microsoft provided DLL that needs to be in the system directory to run PSCNCT16.OCX
The following files are installed to \powersim\psapi\ocx32:

File	Description
PSCNCT32.OCX	The 32-bit Powersim connection OLE control
PSCNCT32.LIC	The license file for the 32-bit OCX
PSCNCT32.HLP	The help file for the 32-bit OCX
MFC40.DLL	A Microsoft provided DLL that needs to be in the system directory to run PSCNCT32.OCX
MSVCRT40.DLL	A Microsoft provided DLL that needs to be in the system directory to run PSCNCT32.OCX


Registering and Licensing

As a purchaser of a professional Powersim version, you are allowed to use the OCXs in any development project. You only need to have the installed license file (PSCNCT16.LIC or PSCNCT32.LIC) in the same directory as the OCX. You are of course allowed to redistribute the OCX with your application. You are, however, not allowed to redistribute the license file. This means that your customers are only entitled to use the Powersim connection OLE control for run-time purposes; they cannot use it as a building block in new applications.

Both the 16 and the 32-bit OCX need certain Microsoft provided DLLs to be present in the system directory. These files are not copied to the system directory during Powersim setup, so you will have to do this manually if you want to use the Powersim connection OLE controls. These DLLs are also needed at run-time, and can be freely distributed with your application.

Refer to the documentation of your development system for how to register the Powersim OCXs with the system. In Visual Basic, for example, you can use the Custom Controls Dialog box to register an OCX and place it in the toolbox ready for insertion into a form.


Getting Help

In the two help files PSCNCT16.HLP and PSCNCT32.HLP, all properties, methods and events defined in the two OCXs are described in detail.


Samples

The \powersim\psapi\ocx32\samples\vb40 directory contains a Visual Basic 4.0 example of how to use the 32-bit OCX. A relatively simple user interface is built on top of a market growth model. Nevertheless, this sample demonstrates the most important mechanisms involved in building a tailored user interface to a Powersim model. If you plan to use Visual Basic as a development tool, you are advised to take a look at this sample. Even if you want to employ a different development tool, you can probably find a lot of useful information by examining the Visual Basic example. After all, Visual Basic code is relatively easy to understand, and sometimes a good example is worth more than a thousand lines of documentation.

The \powersim\psapi\ocx32\samples\msvc40 directory contains a very simple Visual C++ 4.0 example of how to use the 32-bit OCX. The user interface is quite silly, but this small example will head you in the right direction if you contemplate using the OCX interface within Visual C++.


Using The Powersim Connection Delphi Component

TPsConnection is a Delphi component built on top of PSAPI. It can be used to add Powersim connections to Delphi projects.

Installed Files

Installing the Component in Delphi

Licensing

Getting Help

Samples


Installed Files

The following files are installed to \powersim\ psapi\delphi:

File	Description
PSCNCT.DCU	Delphi compiled unit containing part of the TPsConnection component. Used for installing the component with the Delphi system.
PSAPI.DCU	Delphi compiled unit containing part of the TPsConnection component
PSCONST.DCU	Delphi compiled unit containing part of the TPsConnection component
PSCNCT.DCR	Dynamic component resource file containing the palette bitmap for the TPsConnection component
PSCNCT.RES	Resource file for TPsConnection.
PSCNCT.HLP	The help file for the TPsConnection component
PSCNCT.KWF	Keyword file for PSCNCT.HLP. Can be used to integrate the TPsConnection help with the rest of the Delphi help system.
PSAPI.PAS	Contains a PASCAL-syntax interface file for accessing PSAPI.DLL directly from a Delphi program. Can be used if you want to use Delphi, but don't want to use the TPsConnection component.
INSTALL.TXT	A description of how to install the TPsConnection component with the Delphi system


Installing the Component in Delphi

The TPsConnection is not registered with the Delphi system during setup of Powersim. You need to install the Powersim connection component from within Delphi before you can use it. If you want to integrate the component's help with the rest of the Delphi help system, you must also do this manually. Both operations are described in detail in INSTALL.TXT in the \powersim\psapi\delphi directory.


Licensing

The Powersim connection Delphi component will be compiled into your Delphi application. This means you only have to ship the executable file to your customers (who must have a legal copy of Powersim of course). You are not allowed to redistribute the Powersim connection component to your customers in order for them to use it in Delphi projects of their own.


Getting Help

In the help file PSCNCT.HLP, all properties, methods and events defined in the Delphi component are described in detail. If you integrate this help file with the Delphi help system, you can get context sensitive help by pressing F1 in either the Object Inspector or in the Delphi editor.


Samples

The \powersim\psapi\delphi\samples directory contains an example of how to use the Powersim connection Delphi component. A relatively simple user interface is built on top of a market growth model. Nevertheless, this sample demonstrates the most important mechanisms involved in building a tailored user interface to a Powersim model. If you plan to use Delphi as a development tool, you are advised to take a look at this sample.


Advanced Topics

This section deals with some of the more advanced features of the Powersim API.

Vectorizing a Powersim Model

Controlling the Pause State of a Powersim Model


Vectorizing a Powersim Model

So far we have dealt with connections to Powersim models that have a pre-defined number of variables. With the functions PSAPI_BeginChangeRanges, PSAPI_SetRange and PSAPI_EndChangeRanges (or their equivalents in CPsConnection, OCX or Delphi component) we can have connected models that exhibit a more dynamic nature. The client application will dynamically build a model from a set of building blocks or sub-models defined in the Powersim model.

To allow such behavior, the connected model must be vectorized. The model must contain all sub-modules and the connections between them. All variables in a sub-module must be vectorized using the same numeric range. The client application determines how may instances there will be of each sub-module by using the functions for changing numeric ranges.

In this way the end-user can change the model through the user interface of your client application. This technique has for example been used to build a quite sophisticated simulator for gas logistics in the North Sea. If all this seems a bit mysterious, I think a number of points will be clarified if you examine the example of vectorizing found in PSAPI.HLP.


Controlling the Pause State of a Powersim Model

Controlling the pause state is an important aspect of building customized user interfaces to Powersim models. You probably want to include a pause button like the one in Powersim in your application. The functionality of this button can be programmed with the PSAPI_SetControlValue and the PSAPI_GetControlValue functions using the PSAPI_CTL_PAUSE identifier. A control value of 1.0 means that the simulation is paused, while 0.0 means that the simulation is not paused. In CPsConnection, the OCXs, and in the Delphi component, you can use the Pause method and the Paused property to achieve the same thing.

Sometimes you will want to set the connected model to pause state because of a condition in the model or a condition internal to your application or even a combination of the both. One example could be the implementation of an auto pause scheme like the one in Powersim. In that case, you should enable WantPause notifications by calling PSAPI_EnableWantPauseNotifications (or the equivalent EnableWantPauseEvents). WantPause notifications (disabled by default) allow a connected application to request pause state at an appropriate time. The application must return TRUE if it wants pause, FALSE otherwise. You should use this notification rather than the UpdateValues notification, to check for conditions that could cause a pause state transition. Since the WantPause notifications will slow down the simulation, you should disable them if you don't need them.

If you know the exact time the simulation should enter pause state, there is another possibility. With PSAPI_SetControlValue and the PSAPI_CTL_PAUSEATTIME identifier, you can set the next time the simulation will be paused. In CPsConnection, the OCXs, and the Delphi component you have the corresponding PauseAtTime property. After the requested pause has occurred, this property can be set to a new time (a client application will be notified when there is a change in a connected model's pause state).


Using Powersim Objects

  Using Dynamic Objects

  Interactive Simulation

  Working with the Slider/Bar

  Working with the Gauge object

  Working with the Multimedia object

  Using Static Objects

  Working with hexagons

  Working with causal loops

  Using Transfer Objects

  Connecting models using the chain object

  Using the DDE object


Dynamic Objects
Using Dynamic Objects

  Interactive Simulation

  Working with the Slider/Bar

  Working with the Gauge object

  Working with the multimedia object

  Adding a new presentation

  Removing existing presentations

  Editing a presentation

  Determining priority

  Determining input parameter

  Determining output parameter

  Giving a presentation at the beginning of a simulation

  Giving a presentation when the user presses a button


Interactive Simulation

Since the dynamic objects are updated along with a simulation run, they let you follow the development of the selected variables as the simulation emerges. Furthermore, the use of input/output dynamic objects enables you to adjust parameters during a simulation run, thereby giving you immediate responses to your actions. This capability is useful for both gaming purposes and modeling testing.


Working with the Slider/Bar

Powersim has various output and input objects, one of which is the slider/bar object. A slider/bar, as its name infers, has the capability of showing the values of variables as slider buttons and/or bars along a horizontal or vertical axis. Specifically, the slider button allows you to initialize and change the value of a constant during the simulation run, while the bar displays the value of a variable during a simulation.

The slider/bar object below contains the value of the constant Inventory_Adjustment_Time as a slider button and the value of the variable Orders_Received as a bar.

Slider/Bar Example

Using the slider/bar


Using the slider/bar

To define and use a slider/bar object

1	Select the slider/bar object on the toolbar [image] and place the object anywhere on the screen.

2	To define the slider/bar object, double-click on it. At this point, you will see the Define Slider/Bar Dialog box, as shown in the figure below.

The Define Slider/Bar dialog box

3	In the Models box of the Define Dynamic Data Exchange dialog box, select the model whose variable(s) you want to export. The Models list includes the main model and all co-models. We'll choose Main.

4	In the Variables box choose the variable(s) you want to display. Variables displays all variables names (scalars) and variable elements (arrays) of the selected model. We'll pick Inventory_Adjustment_Time and Orders_Received.

5	Although Powersim automatically defines the slider and bar attributes, we will customize them. To customize the slider, select it in the parameter list. We'll only change the axis values by going into Bar Axis. As you can see in the figure below, Powersim has already defined the scale. We'll change Minimum to 1.00 and Maximum to 3.00.

The Bar Axis and Scale Dialog Box

6	Select OK to go back to the Define Slider/Bar Dialog Box. Although we could change the orientation of the this object to Vertical, we'll keep the Orientation of the bar at the default setting of Horizontal.

7	Decide on displaying the exact numerical value of the variable or not. We'll choose to display the value by clicking on the Number Present box.

8	Select OK and run the model.


Working with the Gauge object

Editing or adding a new gauge sector


Editing or adding a new gauge sector
Working with the Gauge object

To edit or add a new gauge sector

1	Double-click on a gauge object to open the Define Gauge dialog box.

2	Click Shape and then Sectors to open the Gauge Sector dialog box

3	Enter lower value in the From box, upper value in the To box (To must be greater than From)

4	Click the Edit-button

5	You will then enter a standard dialog box for defining a color/pattern. If this is a new sector click Insert, else click Set. The newly defined sector will then be shown in the listbox.


Working with the multimedia object

The Multimedia object object can define several presentations.

  Adding a new presentation

  Removing existing presentations

  Editing a presentation

  Determining priority

  Determining input parameter

  Determining output parameter

  Giving a presentation at the beginning of a simulation

  Giving a presentation when the user presses a button

See also

  Multimedia Object


Adding a new presentation

To build a new presentation from scratch

1	Create a new multimedia object and double-click on it to open the Define Multimedia dialog box.

2	Fill in name, type, model, parameter, etc.

3	Click either the Insert button or the Append button to add a presentation. The Append button will insert the presentation after the current position in the Presentations list, while Insert will insert the presentation before the current one.

To build a new presentation on an existing presentation

1	Create a new multimedia object and double-click on it to open the Define Multimedia dialog box.

2	Select the original presentation in the Presentations list.

3	Make the necessary changes to Name and other fields.

4	Click either Insert or Append.


Removing existing presentations

To remove existing presentations

1	Make selections in the Presentations list of the Define Multimedia dialog box

2	Click the Remove button


Editing a presentation

When you make a selection in the Presentations list of the Define Multimedia dialog box, the current settings for the selected presentations are displayed in the controls below the Presentations list.

You can change all the settings of a presentation, except for the Type setting, which is determined at the time you click Insert or Append.

When you make changes to Name, Type, Model, Parameter, Condition, or one of the check marks in the dialog, click Set to update the selected presentation(s) with the new values. You can also press Return, as the Set button becomes the default button after a change to a setting.

You can use the Edit button to open a dialog box for setting options that are special to each presentation type; for example, selecting which video to be played for a video presentation. You can also double click on an entry in the Presentations list to open the dialog box associated with the Edit button.


Determining priority

The ordering of the presentations in the Presentations list determine each presentations' priority. The topmost presentation has highest priority, with decreasing priorities for successive entries. Use the Up and Down buttons to move selected entries in the list, and thereby change their priorities.


Determining input parameter

Each presentation is controlled by an input parameter. The parameter is selected by picking a model from the Model list and a parameter from the Parameter list.


Determining output parameter

An optional output parameter can be associated with each presentation, feeding information back to the model about the status of the presentation. The output parameter is selected from the dialog box that open when you click the Edit button.


Giving a presentation at the beginning of a simulation

When a simulation starts, you may want to inform the user about basic concepts in your model and the way it is operated. You can, for example, ask the user to set values of certain parameters by moving slider bars that you have put in the diagram window. As an example, we will create a presentation where a message box is displayed when the simulation starts. When the user clicks on OK the simulation continues.

To create a presentation where a message box is displayed when the simulation starts

1	Choose the multimedia tool  from the toolbar [image] or the Tools menu.

2	Deposit a new multimedia object in the diagram by clicking with the mouse.

3	Double click on the new object to open the Define Multimedia dialog box.

4	Type Introduction in the Name field.

5	Choose Message Box in the Type field.

6	Choose Control as the Model and Control.Play as the Parameter.

7	Check on Pause while Presenting. This will hold the simulation as long as the message box is open.

8	In the Condition group choose > as Operator and 0 as Value. This condition will be true whenever Control.Play is greater than zero, i.e., the simulation is running (Play is true, even if Pause is on).

9	Click on Append (or Insert) to add the presentation you just have described to the list of presentations.

10	Type in a message to the user in the Text field and fill in the Window Title.

11	Choose OK in the Buttons list.

12	The Return Value will not be used in this example. Therefore we leave the Output group empty and the Return Value group unchanged.

13	Choose an icon from the Icon list box.

14	Click OK two times to close both open dialogs.

15	Run the model by clicking run [image]. A message box will appear immediately, and pause the simulation.

16	When you click OK, the simulation continues.

Note	The described model is stored in the file MED_STAR.SIM that comes with Powersim.


Giving a presentation when the user presses a button

In interactive multimedia, the user should be the active part in the communication. One way to give the user control, is to provide means of getting information on request, for example by presenting buttons that the user can click on. Below we link a text presentation to a push button in the diagram.

To create a constant that will be controlled by a push button

1	Create a new model by clicking the new file button [image] .

2	Choose the constant tool [image] from the toolbar of the Tools menu.

3	Deposit a new constant in the diagram by clicking with the mouse.

4	Type ShowInfo as the name of the constant and press Return.

5	Double click on ShowInfo and set the Definition equal to 0 and click OK.

To create a push button that will control a variable

1	Choose the button tool [image] from the toolbar of the Tools menu.

2	Deposit a new button in the diagram using the mouse.

3	Drag-and-drop the constant ShowInfo into the newly created button.

To create a multimedia presentation linked to a variable

1	Choose the multimedia tool [image] from the toolbar or the Tools menu.

2	Deposit a new multimedia object in the diagram by clicking with the mouse.

3	Double click on the new object to open the Define Multimedia dialog box.

4	Type Show Information in the Name field.

5	Choose Text in the Type field.

6	Leave Main as the Model and ShowInfo as the Parameter.

7	In the Condition group choose <> as Operator and 0 as Value. This condition will be true whenever ShowInfo is different from zero, i.e. after the uses presses the button that we have associated with ShowInfo above.

8	Click on Append (or Insert) to add the presentation you just have described to the list of presentations.

9	Type in a message to the user in the Text field and fill in the Window Title.

10	Enter a value of 4 seconds in the Duration field. This will cause the text presentation to be removed after four seconds.

11	Click OK two times to close both open dialogs.

12	You can now run the model by clicking run step [image] . When you click on the button labeled ShowInfo, a text window will be displayed.

After four seconds the message goes away.

Note	The described model is stored in the file MED_BTN.SIM that comes with Powersim.


Static Objects
Using Static Objects

  Working with hexagons

  Introduction to hexagons

  Creating hexagons in Powersim

  Creating a hexagon with the Fat Arrow 2 shape

  Creating more hexagons

  Aligning hexagons perfectly

  Working with causal loops

  Introduction to causal loops

  Creating a causal loop variable

  Creating more texts representing causal loop variables

  Creating a causal loop arrow

  Creating more causal loop arrows


Working with hexagons

  Introduction to hexagons

  Creating hexagons in Powersim

  Creating a hexagon with the Fat Arrow 2 shape

  Creating more hexagons

  Aligning hexagons perfectly


Introduction to hexagons

The process of making mental models explicit and suitable for simulation, is an iterative and stepwise undertaking. Many modellers start out with an issue generation process, trying to identify relevant aspects of a problem. This process often involves several people, with different perspectives on the problem that is studied. In order to keep track of issues that come to mind when breaking a problem down, notes can be taken and put on individual sheets of paper  or as text objects in a computer program like Powersim. Each sheet or object should contain only one issue, as this will allow sheets to be grouped later on to form subsystems or groups of related issues. Hexagon shaped objects have the nice property that they fit well together when clustered. Hexagons also allow for more objects to be grouped around a central object than any other shape, without leaving gaps. This makes hexagons both visually appealing and functional for the sake of representing high level issues concerning a problem.

Hexagons allow for easy grouping of shapes into clusters


Creating a hexagon in Powersim
Creating hexagons in Powersim

Hint	Before you start creating hexagons, it can be a good idea to turn on a grid for positioning objects. (See Using the Grid).

All dynamic objects in Powersim can have different shapes, including the hexagon shape. In particular, the text object, is perfect for hexagon modeling. Two of the available object shapes look like hexagons, namely the Hexagon shape and the Fat Arrow 2. There is a small difference in that the shape labeled Hexagon has sides of equal length, while the Fat Arrow 2 puts the sides at the ends at 45 degrees angle relative to the base lines.

Both Hexagon and Fat Arrow 2 have six sides.

If objects can vary in length, the Fat Arrow 2 is the preferred shape, as objects will fit tightly together despite of varying lengths.

Fat Arrow 2 shapes fit well together, even if the lengths vary


Creating a hexagon with the Fat Arrow 2 shape

To create a hexagon with the Fat Arrow 2 shape

1	Choose the text object from the toolbar or the Tools menu.

2	Place the object in the diagram.

3	Double click on the frame of the text object to open the Define Text dialog box.

4	Choose Fat Arrow 2 in the Shape combo box.

5	Click on the Layout button.

6	Observe that text will be centered both horizontally and vertically inside the object, which is the desired setting when editing hexagons.

7	Click on OK.

8	Type in a text to be displayed in the hexagon, for example: Price.

9	Click OK.

The display should now contain the following hexagon object:

If the text (here Price) does not show inside the object, just make the object bigger to make room for the text.


Creating more hexagons

To create more hexagons

Once you have made one hexagon, it is easy to make more just by copying and pasting the existing hexagon any number of times. Below we create a hexagon labeled Demand.

1	Choose the Price hexagon by clicking on it with the mouse.

2	Choose the Edit Copy command (or type CTRL+C).

3	Choose the Edit Paste command (or type CTRL+V).

4	Position the new object by dragging it with the mouse.

5	Make sure the new object is selected, and then click inside the label, which is now Price.

6	You can now type the text Demand directly into the new object.

7	Click outside the text to end editing


Aligning hexagons perfectly

If your objects do not align well, this can have to do with the height of the objects relative to the grid setting. Try to increase the objects' height with one grid step, and see if this makes it easier to align the objects.

Alignment problem.

If your display looks like the figure above (gap between the hexagons), do the following:

1	Select Price.

2	Drag bottom line one grid unit down.

3	Select Demand.

4	Drag bottom line one grid unit down.

The object should now be perfectly aligned, as displayed in the figure below.

Solved by increasing the height by one grid unit.

Hint	Also be aware of the Align, Even Spacing and Same Size commands of Powersim's Format menu. Especially Same Size can be useful in making a number of hexagons the same size. (This will normally require some repositioning afterwards.)


Working with causal loops

  Introduction to causal loops

  Creating a causal loop variable

  Creating more texts representing causal loop variables

  Creating a causal loop arrow

  Creating more causal loop arrows


Introduction to causal loops

While hexagons can be used to depict high level issues related to a model, causal loop diagrams go one step further. In a causal loop diagram, model elements (variables) are identified, and influences between variables are indicated using labeled arrows. Variables that form a loop are particularly interesting, as system behavior is closely linked to the nature of the causal loops in the system. This is way the diagrams are called causal loop diagrams, and not just cause effect diagrams.

Below is an example of a causal loop diagram, where price and demand are variables, and each arrow represents an influence of one variable upon another.

Some causal loop diagram symbol conventions are listed in the table below.

Symbol	Meaning
	Balancing loop
	Reinforcing loop
	Change in the Same direction
	Change in the Opposite direction
	Delayed influence
The double lines crossing the arrows in the above example indicate that there are a delays involved in the influences. Arrows representing immediate effects are drawn without delay marks.

The label S on an arrow says that a change in the element at the tail effects the element at the head in the same direction. The S is also used when the element at the tail accumulates values of the tail element.

Correspondingly, an arrow labeled with an O, means opposite effect. An O is also used when the element at the tail drains values from the head element.

There are several slightly different conventions for writing causal loop diagrams, in that labels are sometime labeled with + and - instead of S and O. In Powersim the labels can be entered as text, so you can freely choose chat convention to follow.

It is beyond the scope of this guide to describe nature of loops and their relationship to system behavior and problem solving.


Creating a causal loop variable

In this chapter we use causal loops to describe model structure, without doing simulation. We therefore can use a text object to represent a variable. We can also use picture objects, or video animation, if we want to make our presentations look extra good.

To create causal loop variable using a text object

1	Choose the text object from the toolbar or the Tools menu.

2	Place the object in the diagram.

3	Double click on the frame of the text object to open the Define Text dialog box, or just press Return if the object is selected.

4	Choose None in the Style combo box.

5	Check on the Adjust object size to fit text check mark.

6	Type in a name for the causal loop variable, for example: "Price".

7	Click OK.


Creating more texts representing causal loop variables

To create more texts representing causal loop variables

The easiest way of creating more "variables" is to use copy and paste, like this:

1	Select the variable Price by clicking on it with the mouse.

2	Choose the Edit Copy command, or press CTRL+C.

3	Choose the Edit Paste command, or press CTRL+V. A copy of Price appears on the screen.

4	Move the new object to the desired position using the mouse.

5	Click inside the text and type the name of the new causal loop element, for example Demand.


Creating a causal loop arrow

To create a causal loop arrow

The line tool can be used to create lines and curves with optional labels, arrows and delay marks. To create an arrow from Price to Demand, do this:

1	Choose the line object from the toolbar or the Tools menu.

2	Point with the mouse below Price.

3	Press and keep the left mouse button down.

4	While holding down the mouse button, move the mouse to a point below Demand.

5	Release the mouse button.

A straight line should now be displayed in your diagram, like this:

To make the line into an arrow, and define the delay mark and the O label

1	Double-click on the line object to open the Define Line dialog box.

2	Choose the right arrow in the Arrow Heads combo box.

3	Choose Curved Line in the Shape combo box.

4	Check on the Delay Mark check mark.

5	Click Head to define the label at the head of the arrow.

6	Type S in the Text box.

7	Choose None in the Style combo box (leave it as it is if you want to have a border around the label).

8	Click OK.

9	Click OK in the Define Line dialog box.

10	Use the curve handles to shape the arrow the way you like.

The resulting display should look something like this:

Hint	When editing curves it can be helpful to switch on angular grid. Open up the Format Options dialog box and choose the Diagram Editing tab. Type in a number, for example 15, in the Angle box. Make sure Snap to Grid is checked on before you click OK.


Creating more causal loop arrows

To create more causal loop arrows

As with hexagons and causal loop element names, it is the easiest to use Copy and Paste to create more causal loop arrows. To create an arrow from Demand to Price follow the steps below:

1	Choose the arrow from Price to Demand by clicking on it with the mouse.

2	Choose the Edit Copy command, or press CTRL+C.

3	Choose the Edit Paste command, or press CTRL+V

4	Drag the rightmost handle of the new arrow object to a place above Price.

5	Drag the handle at the other end of the arrow to a place above Demand.

6	Click inside the label (O) of the arrow and type an S.

7	Click outside the text box to end text editing.

The display should now look like this:


Transfer Objects
Using Transfer Objects

  Connecting models using the chain object

  Using the DDE object


Working with the chain object

  Connecting models


Connecting models

To establish a connection between a main- and a co-model

1	Add one or more co-models using the Simulation Setup dialog box.

2	Create a Chain object and put it in the diagram.

3	Open the Define Chain dialog box, choose the source and target variable, and hit OK.

When simulating the main model, the destination variable will now have its value transferred from the source variable.


Using Powersim Functions

The following topics contain guidelines and examples on how to use a number of functions found in Powersim's library. All functions mentioned here are used in demo models found under the Samples\UserGuid directory of your Powersim system.

  Overview of Functions and Demo models

How to use the functions:

  Built-in Functions

  Array Functions

  Complex Functions

  Miscellaneous Functions

  Financial Functions

  History Functions

  Conditional Functions

  Control Functions

See also

  Functions


Overview of Functions
Overview of Functions and Demo models

The following table lists all functions covered by demo models and descriptions in the following topics. For more information about the functions, see Functions.

Functions	Demo models
ABSC	ABSC.SIM
ADDCR	ADDCR.SIM
ADDRC	ADDRC.SIM
ADD	ADD.SIM
AND	AND.SIM
ANGLEC	ANGLEC.SIM
ARRAVG	ARRAVG.SIM
ARRMAX	ARRMAX.SIM
ARRMIN	ARRMIN.SIM
ARRPROD	ARRPROD.SIM
ARRSTDDEV	ARRSTDEV.SIM
ARRSUM	ARRSUM.SIM
ASSIGN	ASSIGN.SIM
BUT	GUARDFUN.SIM and CONSTRAI.SIM
COUNT	GUARDFUN.SIM and CONSTRAI.SIM
DEFAULT	GUARDFUN.SIM and CONSTRAI.SIM
FIRST	GUARDFUN.SIM and CONSTRAI.SIM
FORECAST	FORECAST.SIM
FV	FINANCES.SIM
IF	IF.SIM
INDEX	INDEX.SIM
LAST	GUARDFUN.SIM and CONSTRAI.SIM
NPV	FINANCES.SIM
OR	OR.SIM
OTHERWISE	GUARDFUN.SIM and CONSTRAI.SIM
PAUSEIF	PAUSEIF.SIM
PAUSEWHILE	PAUSEWHL.SIM
PMT	FINANCES.SIM
PV	FINANCES.SIM
SAMPLEIF	SAMPLEIF.SIM
SAMPLE	SAMPLE.SIM
SHIFTCIF	SHIFTCIF.SIM
SHIFTLIF	SHIFTLIF.SIM
SUM	SUM.SIM
WHEN	GUARDFUN.SIM and CONSTRAI.SIM


Working with Complex Functions

Using the function:

  ABSC

  ADD

  ADDCR

  ADDRC

  ANGLEC

See also

  When to use Complex functions

  Complex Functions


When to use the Complex functions
When to use Complex functions

The demand of the complex functions will normally arise in problems related to engineering or scientific questions. When the actual problems imply solutions to sets of differential equations or polynomial equations for instance, which often involves complex numbers, this function group might be useful. Regarding electrical and electronic engineering, this function might be especially valuable because of the extensive use of complex numbers in electrical network analysis and signal analysis.


Using the ABSC function
The ABSC function

The ABSC function computes the absolute value(s) (magnitude) of a complex number or an array of complex numbers given in Cartesian format. Note that the ABSC function only accepts one argument. This means that isolated complex numbers have to be passed one by one to the ABSC function or they have to be collected and transformed into one array.

Using the ABSC demo model

1	Open ABSC.SIM in Powersim.

2	Double-click on the variable Absolute_values_of_complex_numbers_in_array and notice the dimension declaration. In this case there are two complex numbers which absolute values (magnitudes) are computed.

3	Double-click on the variable Array_of_complex_numbers and recognize the dimension declaration. This variable transforms two complex numbers into a 2x2 matrix. This is necessary because the ABSC-function only accepts one argument.

4	Initialize the simulation by the Run Step button [image].

5	By operating one of the three slider bars below the model diagram, the corresponding complex numbers imaginary and real parts respectively, are set.

6	The output numbers above the model diagram immediately show the result of the computed absolute values of the complex numbers, performed by the ABSC-function.


Using the ADD function
The ADD function

The ADD function computes the sum of two complex numbers or computes the sum of two arrays consisting of complex numbers. The complex numbers are supposed to exist in Cartesian format. Arrays of complex numbers are represented by matrices with dimensions 2 x N. Nevertheless this function accepts matrices with other dimensions than 2 x N as input, but the results might appear meaningless. Therefore it is not recommended to use this function for any other purposes than complex functions.

Using the ADD demo model

1	Open ADD.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Press the right mouse button on each input variable to the ADD function variable in the Correct application of ADD function section and observe the current values. Confirm the result in the Sum_of_Complex_numbers variable in the same manner.

4	Do the same in the Incorrect application of ADD function section and notify the meaningless result in Probably_wrong_result_matrix.


Using the ADDCR function
The ADDCR function

The ADDCR function computes the sum of a complex number or an array of complex numbers in Cartesian format and a real number or an array of real numbers. The name ADDCR indicates that the complex number is the first argument in the function.

Using the ADDCR demo model

1	Open ADDCR.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Press the right mouse button on each input variable to the ADDCR function variable and observe the current values. Confirm the result in the Sum_of_Complex_Numbers_and_Real_Numbers variable in the same manner.


Using the ADDRC function
The ADDRC function

The ADDRC function computes the sum of a real number, an array of real numbers and a complex number, or an array of complex numbers in Cartesian format. The name ADDRC indicates that the real number is the first argument in the function.

Using the ADDRC demo model

1	Open ADDRC.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Press the right mouse button on each input variable to the ADDRC function variable and observe the current values. Confirm the result in the Sum_of_Real_Numbers_and_Complex_Numbers variable in the same manner.


Using the ANGLEC function
The ANGLEC function

The ANGLEC function computes the angle between the abscissa and the vector associated with the complex number, given in Cartesian format. The input might be an array of complex numbers as well. This angle constitutes the polar representation of the complex number in addition to the length of vector.

Using the ANGLEC demo model

1	Open ANGLEC.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Press the right mouse button on each input variable to the ANGLEC function variable and observe the current values. Confirm the result in the Angle_of_Complex_Number variable in the same manner.


Working with Array Functions

Using the function:

  ARRAVG

  ARRMAX

  ARRMIN

  ARRPROD

  ARRSTDDEV

  ARRSUM

  SHIFTCIF

  SHIFTLIF

See also

  Array Functions


Using the ARRAVG function
The ARRAVG function

The ARRAVG function computes the average value of the elements in an array. In many cases you need information about both the details within the system and the overall conditions of the system. The detailed information is preserved by the array concept. Whenever you want to pay attention to the performance of general tendencies occurring in a system, the ARRAVG function may become an appropriate function to derive such information.

Using the ARRAVG demo model

1	Open ARRAVG.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Below the model diagram there are two output objects showing the instant specific values of an array and its corresponding instant average value respectively. The object to the left shows the state of Support_Requests_of_different_types_Pending and that one to the right shows the state of Average_Support_Requests_Pending. Press the Run Step button [image] and observe the change in the average value due to changes in the value of the array elements.


Using the ARRMAX function
The ARRMAX function

The ARRMAX function computes the maximum value of the elements in an array. In many cases you need information about some specific values. Extreme values may tell something about a systems range. The ARRMAX function provide the upper limit for the system at a given moment.

Using the ARRMAX demo model

1	Open ARRMAX.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Below the model diagram there are two output objects showing the instant specific values of an array and its corresponding instant maximum value respectively. The object to the left shows the state of Support_Requests_of_different_types_Pending and that one to the right shows the state of Maximum_Support_Requests_Pending. Press the Run Step button [image] and observe the change in the maximum value due to changes in the value of the array elements.


Using the ARRMIN function
The ARRMIN function

The ARRMIN function computes the minimum value of the elements in an array. In many cases you need information about some specific values. Extreme values may tell something about a systems range. The ARRMIN function provide the lower limit for the system at a given moment.

Using the ARRMIN demo model

1	Open ARRMIN.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Below the model diagram there are two output objects showing the instant specific values of an array and its corresponding instant minimum value respectively. The object to the left shows the state of Support_Requests_of_different_types_Pending and that one to the right shows the state of Minimum_Support_Requests_Pending. Press the Run Step button [image] and observe the change in the minimum value due to changes in the value of the array elements.


Using the ARRPROD function
The ARRPROD function

The ARRPROD function computes the product of the value of the elements in an array. Aggregated information provided by the ARRPROD function are of interest when the considerations and decisions are supposed to be executed on a higher level. The detailed information contained in an array by the value of its elements is sometimes of minor importance.

A typical application of the ARRPROD function might appear in computations of total probabilities from an array containing probabilities representing independent events.

Using the ARRPROD demo model

1	Open ARRPROD.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Below the model diagram there are two input objects. That one to the left enable the specification of the through-put, in tons pr week, in a crude-oil refinery according to a production plan. The source of such a production plan may be results from a forecast investigation. In this case the time aspect cover three years ahead. Press and drag the cursor/pointer in the diagram to manipulate the production graph values. The other input object enable different settings of the interval between maintenance operations by moving the slider.

4	Below the input objects there is an output time graph object showing different failure probabilities time variation. The failure probabilities represents the chance of limited fatal errors in a section or more sections of a crude-oil refinery. Increasing failure probabilities are mainly caused by the equipments degree of load over time. This in turn, depends on the wanted production volume. If a service is performed, these probabilities will normally be reset to approximately the same value as before.

5	In the time graph object the short name Pr_f_all refers to the variable Probability_of_failure_in_-all_sections, and the short name Pr_f_1or_more refers to the variable Probability_of_one_or_-more_failures. Both these variables apply the ARRPROD function to derive the actual probability values from an array containing probability values of failure in five different essential refinery sections. This may be confirmed by inspection of the variables definition.

6	By changing the production plan and the time interval between services, corresponding variations in probability values of failure may be studied, doing several simulation runs.


Using the ARRSTDDEV function
The ARRSTDDEV function

The ARRSTDDEV function computes the standard deviation of the elements in an array. The standard deviation is a common way to characterize the degree of dispersion within a group of data. In statistics the standard deviation of N elements in a group of data is defined as :

where [image] denote the specific data in the group, [image] is the mean value of the data and S is the standard deviation. This expression may also be rearranged and written:

in which the computation is a direct function of the actual data.

 In many cases you need information about both the details within the system and the overall conditions of the system. The detailed information is preserved by the array concept. Whenever you want to pay attention to the performance of general tendencies occurring in a system, the ARRSTDDEV function may become an appropriate function to derive such information. Especially when you are dealing with variables that are characterized by stochastic behavior the ARRSTDDEV function may serve as a very useful function.

Using the ARRSTDDEV demo model

1	Open ARRSTDEV.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	This model computes the growth in a salmon population of 200 individuals (or groups). To provide information about the variation in weights at any time, the ARRSTDDEV function is applied to the array containing the weights. By inspection of the variable Standarddeviation_x_2_for_weights the use of the function may be studied. This variable is also applied to two output variables to depict the dispersion of weights around the average weight at any moment, refer the time graph object below the model. Press run button to study this.


Using the ARRSUM function
The ARRSUM function

The ARRSUM function computes the sum of the value of the elements in an array. Aggregated information provided by the ARRSUM function are of interest when the considerations and decisions are supposed to be executed on a higher level. The detailed information contained in an array by the value of its elements is sometimes of minor importance.

Using the ARRSUM demo model

1	Open ARRSUM.SIM in Powersim.

2	Initialize simulation by clicking the Run Step button [image].

3	Below the model diagram there are two output objects showing the instant specific values of an array and its corresponding instant total value respectively. The object to the left shows the state of Support_Requests_of_different_types_Pending and that one to the right shows the state of Total_Support_Requests_Pending. Press the Run Step button [image] and observe the change in the total value due to changes in the value of the array elements.


Using the SHIFTCIF function
The SHIFTCIF function

The SHIFTCIF (circular shift if) function, like the SHIFLIF function, is a conditional array function that is executed when a specified condition is satisfied. But unlike the SHIFLIF function, it is executed by moving vector elements each time step by one step forward as they go around. When the model is run by one time step, the element in vector 1 replaces that in 2 and the one in 2 replaces the one in 3, and so on; with the element in vector N (the last element) replacing that of 1. The process continues until the elements are output.

The SHIFTCIF function can be used in problems related to movements in an automated production line, where components need to be moved around through stages to enable manual or robotics fixing of additional components, for example, computer, radio, or vehicle assembly lines. It could also be applied to a quality control line where inspection needs to be done more than once before the inputs go out as output. (Compare this with the linear shift function).

Using the SHIFTCIF demo model

1	Open SHIFTCIF.SIM in Powersim.

2	Press the right mouse button while pointing at the variable CircularShiftOutput and watch the definition of the variable as displayed in the statusbar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	First, put Powersim in simulating mode by hitting the Run Step button [image] and observe the settings.

4	Then, try running the model, again using the Run Step and observe how the time table output object is being updated.


Using the SHIFTLIF function
The SHIFTLIF function

The SHIFTLIF (linear shift if) function is a conditional array function that is executed when a specified condition is satisfied. The function is executed by moving vector elements one step forward or to the right. When the model is run by one time step, the elements are moved in such a manner that vector[N] becomes N-1, the element in 2 moves to vector 3, that in 1 moves to 2 and vector becomes empty. The SHIFTLIF function can be used in problems related to queuing or promotions with or without delays, to specify when the output of a particular input should be discharged. This could be queues in ordering, production processes, provision of services etc. (Compare this with the circular shift function).

Using the SHIFTLIF demo model

1	Open SHIFTLIF.SIM in Powersim.

2	Press the right mouse button while pointing at the DepartureFromCounter variable and then notice the definition of the variable as displayed in the statusbar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	First, put Powersim in simulating mode by hitting the Run Step button [image] and observe the settings.

4	Then, try running the model, again using the Run Step and observe how the time table output object is being updated.


Working with Miscellaneous Functions

Using the function:

  ASSIGN

See also

  Miscellaneous Functions


Using the ASSIGN function
The ASSIGN function

The ASSIGN function can be used in when you need to let one variable assign a value to another variable directly. Note that when you use the ASSIGN function, the result may easily become quite different from what you believe when you look at the flow diagram structure. The information link will go from the influenced to the influencing variable, which is not usual. We do not generally recommend to use this function unless you have very good reasons to do so, because it intervenes in the normal simulation procedure by updating a variables value at the end of each simulation step. This is a function for the technical/programmer oriented modeler.

Using the ASSIGN demo model

1	Open ASSIGN.SIM in Powersim.

2	Press the right mouse button while pointing at the Assign_Value variable.

3	Notice the definition of the variable as displayed in the statusbar. The definition means that Parameter will be assigned the value of Auto_Value if Auto_Switch is true (1).

4	Put Powersim in simulating mode by hitting the Run Step button [image].

5	Hit the Manual button on the Control Panel and notice that the value of Parameter changes to the current value of Default Manual Value. Notice also that you may not type a new value into the Parameter input object at this point. This is because the initial definition of Parameter is an expression. To change the default manual value to be used you must use the input object labeled Default Manual Value.

6	Note also that whenever you hit the Automatic button on the Control Panel, the value of Parameter is set back to 12. This is because of the first part of the initial definition of Parameter, which says: "INIT(Auto_Switch) * INIT(Auto_Value)". Since the ASSIGN function performs the specified assignment at the end of each simulation step it can not be used in for initializing a variable before a simulation run is actually started.

7	Choose Run Step again. The model is no longer in the initial state. Therefore Parameter now acts like a constant, which allows you to manipulate its current value directly. Its initial definition has no effect. Notice that whenever Manual is chosen and you adjust the value of Parameter, the value reported by the Time Table is immediately updated.

8	Choose Automatic on the Control Panel and choose Run Step again. Note that whenever Automatic is chosen, Parameter is not assigned the value of Auto_Value before the next simulation step. This illustrates the one time step delay that results from using the ASSIGN function.


Using Built-in functions

The Built-in functions are a group of functions that are part of the simulation language itself. Unlike all other functions, they are not external to the system or loaded from DLLs during initialization. These functions include

•	Guard Operators (I and WHEN)

•	Constraint Operators (; and BUT)

•	Default Guard Operators (DEFAULT {default guard of constrained expression} and OTHERWISE)

•	Conjunction and Logical Operators (AND, OR )

•	Base Range of Indices (COUNT, FIRST, and LAST)

•	Convert Index Variable to Scalar (INDEX)

•	Sum of Expressions Over Indices (SUM)

Most of these functions are generally applicable to arrays or in the combination of arrays and scalars. Particularly where there is the need to refer to some and not all elements of an array or to consider the values of the elements of an array in a scalar.

Using the Built-in demo models

1	The built-in function models are located in separate files under the function names.

 2	For each of the sub group of functions, for example, guard or constraint, open for example, GUARDFUN.SIM or CONSTRAI.SIM in Powersim.

3	Double click to open to the variable definition box where the functions definition is located.

4	If the variable is a level as is the case for most of the built-in functions, check the Flow radio button in the definition box to see how the functions have been defined.

5	Try running the model to see the result produced by each function definition.


Working with Financial Functions

The Financial functions are a group of functions covering the computations of

•	Future Value (FV)

•	Net Present Value (NPV)

•	Periodic Payments (PMT)

•	Present Value (PV)

  Using the Finance demo model

See also

  Financial Functions


Using the Finance demo model

1	Open FINANCES.SIM in Powersim.

2	Put Powersim in simulating mode by hitting the Run Step button [image] and observe the parameter settings and the computed results.

3	You can also try out your own scenarios by resetting the parameter values using the slide bars while in a simulation mode, that is clicking on the Run Step button [image] or Ctrl+U.


Working with History Functions

Using the function:

  FORECAST

  SAMPLE

  SAMPLEIF

See also

  History Functions


Using the Forecast function
The FORECAST function

The FORECAST function is a historical function that extrapolates into the future, the trend in the value of an input variable. The result of the forecast is largely influenced by the given past and future time horizons (for averaging the input and forecasting into the future respectively).

The function is very useful in all modeling situations that require a look into the future. In this example, the FORECAST is made based on the trend (rise and fall) in demand, which is randomly fluctuating by 10%. The averaging (past) time can be varied between 1 and 10 weeks and the future horizon (time) can also be varied between 1 and 12 weeks.

Using the FORECAST demo model

1	Open FORECAST.SIM in Powersim.

2	Press the right mouse button while pointing at the variable ForecastDemand and follow the definition of the variable as displayed in the status bar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	Put Powersim in simulating mode by hitting the Run Step button [image] and observe the initial parameter settings.

4	You can also try out your own scenarios by resetting the parameter values using the slide bars while in a simulation mode, that is clicking on the Run Step button [image] or Ctrl+U.


Using the SAMPLE function
The SAMPLE function

The SAMPLE function is also one of Powersims conditional functions that is executed periodically when the specified condition is satisfied. The function takes as input any numeric expression and performs the first sampling when the first time specified is met. The value obtained is retained until the next sampling takes place at the specified time intervals.

Sampling is an important part of our daily activities. It is usually necessary to provide us with a statistical basis for drawing conclusions about large populations. Areas of the functions application are therefore very broad. In our example model, it has been applied to sample defective products from a manufacturing line. It can also find expression in transportation problems, forecasting of election results, etc.

Using the SAMPLE demo model

1	Open SAMPLE.SIM in Powersim.

2	Press the right mouse button while pointing at the variable Sample_Defective_Items and then notice the definition of the variable as displayed in the statusbar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	First, put Powersim in simulating mode by hitting the Run Step button [image] and observe the settings.

4	Then, try running the model, again using the Run Step and observe how the sapling is done over time.


Using the SAMPLEIF function
The SAMPLEIF function

The SAMPLEIF function is another of Powersims conditional functions that is executed whenever when the specified condition is satisfied. The function first evaluates the stated condition and if it is true it performs the sampling, otherwise it maintains its previous or its initial value, if any is given else it has a value of 0 before the first condition is satisfied. Its input may be any numeric expression.

Sampling is an important part of our daily activities. It is usually necessary to provide us with a statistical basis for drawing conclusions about large populations. Areas of the functions application are therefore very broad. In our example model, it has been used to signal whenever actual exceed budgetary expenditures. It can also find expression in transportation problems, forecasting of election results, etc.

Using the SAMPLEIF demo model

1	Open SAMPLEIF.SIM in Powersim.

2	Press the right mouse button while pointing at the variable SampleIf_Actual_Exceed_Budgeted_Expenditure and then notice the definition of the variable as displayed in the statusbar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	First, put Powersim in simulating mode by hitting the Run Step button [image] and observe the settings.

4	Then, try running the model, again using the Run Step and observe how the sampling is done over time.


Working with Conditional Functions

Using the function:

  IF

  SAMPLEIF

  SHIFTCIF

  SHIFTLIF

See also

  Conditional Functions


Using the IF function
The IF function

The IF  function is a conditional function that is executed when one of the specified conditions is satisfied. The function is executed by first evaluating the stated condition and if found to be true, the first specified action is performed otherwise the second action is performed. The IF function is the commonest of all the conditional functions and constitutes the basis of most logical or conditional evaluations. Its areas of application are therefore unlimited.

Using the IF demo model

1	Open IF.SIM in Powersim.

2	Press the right mouse button while pointing at the variable Repay_Loan_If and then notice the definition of the variable as displayed in the status bar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	First, put Powersim in simulating mode by hitting the Run Step button [image] and observe the settings.

4	Then, try running the model, again using the Run Step and observe how the sampling is done over time.

5	You can also try out your own scenarios by resetting the parameter values using the slide bars while in a simulation mode, that is clicking on the Run Step button [image] or Ctrl+U.

Note	The Control.StopTime can only be reset outside the simulation mode, that is before clicking on the Run Step button [image] or Ctrl+U keys.


Working with Control Functions

Using the function:

  PAUSEIF

  PAUSEWHILE

See also

  Control Functions


Using the PAUSEIF function
The PAUSEIF function

PAUSEIF is a control function used to temporarily halt a simulation when the stated argument becomes True. The simulation can be resumed by releasing the pause-button even if the Condition is still True.

The function is useful in all situations where one might need to interrupt the simulation in order to either adjust parameters or observe the effects of a particular action. In this particular example, both income and expenditure are randomly generated and the simulation is interrupted (paused) when they are equal.

The variable containing the PAUSEIF-function has a default value of 0 until the condition is satisfied when it takes the value 1.

Using the PAUSEIF demo model

1	Open PAUSEIF.SIM in Powersim.

2	Press the right mouse button while pointing at the Pause_if_Income_Equals_Expenditure variable and then notice the definition of the variable as displayed in the statusbar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	The definition means that the Parameter will be assigned the value 1 and the simulation paused when income and expenditure are equal.

4	First, put Powersim in simulating mode by hitting the Run Step button [image].

5	Then, try running the model and observe when and how the condition is satisfied and what happens.


Using the PAUSEWHILE function
The PAUSEWHILE function

PAUSEWHILE is a control function used to permanently halt a simulation when the stated argument becomes True. Unlike in the case of PAUSEIF, the simulation cannot be resumed by releasing the pause-button once the specified condition is satisfied.

The function is useful in all situations where one might need to terminate a process in order to prevent a possible disaster or discontinue a process which may no longer be useful once the specified condition is met. In this particular example, both income and expenditure are randomly generated and the simulation is terminated when the two are equal.

The default value of the of the variable containing the PAUSEWHILE-function is 0 until the condition is satisfied when it takes the value 1.

Using the PAUSEWHILE demo model

1	Open PAUSEWHL.SIM in Powersim.

2	Press the right mouse button while pointing at the Pause_While_Income_Equals_Expenditure variable and then notice the definition of the variable as displayed in the statusbar or follow the instruction provided in the oval dialogue box and click to open the variable to see the definition in the define variable box.

3	The definition means that the Parameter will be assigned the value 1 and the simulation terminated when income and expenditure are equal.

4	First, put Powersim in simulating mode by hitting the Run Step button [image] and observe the settings.

5	Then, try running the model and observe when and how the condition is satisfied and what happens.