Está en la página 1de 158

Table of Contents

Copyright 1998-2003 Ventana Systems, Inc. Revision Date: April 7, 2003 1 Introduction
Double Precision ..........................................................................................................8 Venapps .......................................................................................................................8 Command Scripts.........................................................................................................9 External Functions .......................................................................................................9 Dynamic Data Exchange..............................................................................................9 Compiled Simulations...................................................................................................9 Vensim DLL..................................................................................................................9 Distributing your Work ..................................................................................................9

2 Venapp Introduction
Purpose of a Venapp .................................................................................................10 Learning with Venapps...............................................................................................10
Two Main Types of Interface 10 Two General Methods for Presenting Models 10

10

Building Venapps .......................................................................................................11


General Guidelines 11 Using the Text Editor Examining Screens 12 Simulation Interface 12 Game Interface 13 12

Logical Flow in Venapps ............................................................................................12 Screen-by-Screen Description ...................................................................................13


Display Screens 14 Opening 14 Menu and Button Screens Main Menu 14 Structure 14 Set Up a Simulation 14 Game Control 14 Input Screens 14 Running Screens 15 Output Screens 15 Analysis Screens 15 Conditional Branching 15 Conditional Controls 15 Vensim Custom Definitions Binary Venapp Files 16 SCREENFONT PIXELPOS 18 Loading 18 Setup 18 Painting 19 Reading 19 Take-Down Refreshing 17 14

Venapp Basics ...........................................................................................................15


16

Screens ......................................................................................................................16 Venapp Internal Activity..............................................................................................18

19 19

3 Venapp Editing
Starting the Venapp Editor .........................................................................................20 General Operation......................................................................................................20
Screen Controls 21 Screen Definition 21 Cutting and Pasting 21 Deleting 22 Loading and Saving 22

20

Control Definition Dialog.............................................................................................22 Command Definition Dialog........................................................................................23 Screen Definition Dialog.............................................................................................24 Testing the Venapp ....................................................................................................25
Test Screen 25

4 Venapp Controls
Output Controls Tool controls 27 Input Controls 27 Action Controls. 27 27

27

Control Anatomy ........................................................................................................28


Control Name or Type 28 Control Text 29 X,Y,Width,Height 29 Justification 29 Font 29 Accelerator/Range 30 Command 32 Shift to Screen 32 Long Lines and Quotes 32 Comments 33

Detailed Control Description.......................................................................................33


ANYKEY - com scr 33 BITMAP - txt pos 33 BRANCH - txt com scr 34 BUTTON - txt pos jst acc com scr 34 CALLBACK txt com scr 34 CLOSESCREEN - com scr 35 COLORCIRLE txt pos 35 COLORRECT txt pos 36 CONDITIONAL txt 36 COMMAND - com 36 DATEVAR - txt pos acc 37 EDATEVAR 37 GRAPHVAR txt pos jst acc 37 LINE - pos jst 37 LISTVAR - txt pos acc 37 MODRUNNAME - txt pos jst 38 MODTABLE - txt pos acc 38 MODVAR - txt pos acc 38 PASSWORD txt 39 PROMPT pos jst 39 RADIOVAR/RADIO1VAR - txt pos acc com RECTANGLE - pos jst 39 RUNNAME - txt pos jst 39 SETWB - com scr 40 SHOWCOMPANY pos jst 40 SHOWDATEVAR txt pos jst acc 40 SHOWEDATEVAR txt pos jst acc 40 SHOWUSER pos jst 40 SHOWVAR - txt pos jst 40 SKETCH - txt pos jst acc com 41 SLIDEVAR - txt pos jst acc 42 SLIDEVARTIE txt 42 SWITCHVAR - txt pos acc com 43 TEXTMENU - txt pos jst acc com scr 43 TEXTONLY - txt pos jst 43 TIMER txt pos jst acc com scr 43 TOOL - txt pos com 44 WBVAR - pos jst 44 WIPTOOL - txt pos com 44

39

5 Commands Descriptions
Overview 45 General Issues46 File Names 46

45

BRANCH ....................................................................................................................47 CANCEL.....................................................................................................................48 CUSTOM....................................................................................................................48


Letting the User Select a Graph 49

ERROR ......................................................................................................................49 EXPORT ....................................................................................................................49 FILE............................................................................................................................50


FILE>COPY|oldname|newname 50 FILE>CREATE|filename 50 FILE>DECRYPT|filename 50 FILE>DELETE|filename 50 FILE>ENCRYPT|filename 50 FILE>EXISTS|filename 50 FILE>MDL2VMF|filename 50 FILE>RENAME|oldname|newname 51 FILE>VCD2VCF|filename 51 FILE>VGD2VGF|filename 51

FILE>VMF2MDL|filename

51

GAME.........................................................................................................................51
GAME>BACKUP|totime 51 GAME>ENDGAME 51 GAME>GAMEINTERVAL|value 51 GAME>GAMEON 51 GAME>READGIN|filename 51 GAME>READVDF|filename|time 52 GAME>RELOAD 52 GAME>WRITEGIN|filename|savelist LOG>CREATE|filename 52 LOG>MESSAGE|filename|message LOG>TIMESTAMP|filename 53

52

IFTHENELSE .............................................................................................................52 LOG............................................................................................................................52


52

MENU.........................................................................................................................53
MENU>DAT2VDF|datafile|vdffile 53 MENU>EXIT 53 MENU>GAME 53 MENU>LOAD_RUN53 MENU>REDO_GRAPHS 53 MENU>RUN|o 53 MENU>RUN1|o 53 MENU>RUN_OPTIMIZE|o 53 MENU>RUN_SENSITIVITY|o 54 MENU>SENS2TAB|vdffile|tabfile|*![# 54 MENU>SYNTHESIM|o 54 Starts SyntheSim mode. Use O to overwrite the existing run without prompting. In SyntheSim mode all changes to model values will trigger simulations and Venapp sliders will simulate as they are moved, saving the results when they are released. If you display a sketch in SyntheSim mode the behavior graphs for each variable will be displayed, but the sliders will not be created. 54 To leave SyntheSim mode use SPECIAL>STOPSIM.MENU>TAB2VDF|tabfile|outfile|form 54 MENU>VDF2DAT|vdffile|datfile|savelist|+ 54 MENU>VDF2TAB|vdffile|tabfile|savelist|+[*!|frequency|start|end 54 MENU>VDF2WK1|vdffile|tabfile|savelist|+[*!number 55 MENU>VDF2XLS|vdffile|tabfile|savelist|+[*!number 55 MENU>WK12VDF|tabfile|outfile|form 55 MENU>XLS2VDF|tabfile|outfile|form 55

PRINT ........................................................................................................................55 SETTING....................................................................................................................55


SETTING>EURONUMBER|n 55 SETTING>EXPORTSIZE|n 55 Setting>EXTTERNALFUNCTION|dll name SETTING>HOVERCOM 56 SETTING>PRINTOPTQUERY|n 56 SETTING>SHOWINITIAL|n 56 SETTING>SHOWLOOKUP|n 56 SETTING>SHOWMACRO|n 56 SETTING>SHOWWARNING|n 56 SETTING>SIZEINCHES|n 56 55

SIMULATE .................................................................................................................56
SIMULATE>1TABCHG|varname 57 SIMULATE>ADDCIN|cinfile 57 SIMULATE>ADDDATA|vdffile 57 SIMULATE>BASED|oldrun 57 SIMULATE>CHGFILE|cinfile 57 SIMULATE>DATA|filelist 57 SIMULATE>GETCNSTCHG|varname 57 SIMULATE>GETTABCHG|varname 57 SIMULATE>MINMEM|n 58 SIMULATE>OPTPARM|optfile58 SIMULATE>PAYOFF|payfile 58 SIMULATE>POSTPROCESS|postfile 58 SIMULATE>READCIN|cinfile 58 SIMULATE>READRUNCHG|oldfile 58 SIMULATE>RESUME|n 58 SIMULATE>RUNNAME|filename|mode 58 SIMULATE>SAVELIST|list 58 SIMULATE>SENSITIVITY|sensfile 59 SIMULATE>SENSSAVELIST|list 59 SIMULATE>SETVAL|var=val or var((x1,y1)...(xn,yn)) or var :IS: literal 59 SIMULATE>SPREADALIAS|?alias=filename.xls 59 SIMULATE>WRITECIN|cinfile 59

SKETCH.....................................................................................................................59
SKETCH>CHOOSEVIEW|sketchname|prompt SKETCH>NEXTVIEW|sketchname 60 SKETCH>PREVVIEW|sketchname 60 SKETCH>ZOOM|sketchname|percent 60 60

SPECIAL ....................................................................................................................60

SPECIAL|ALIASSCREEN|aliasname|screenname 60 SPECIAL>ASKYESNO|question 60 SPECIAL>BUTTONFOCUS|n 61 SPECIAL>CLEARRUNS|n 61 SPECIAL>EXIT1 61 SPECIAL>EXTERNAL|funcname 61 SPECIAL>LOADAPPINT|appname@screen 61 SPECIAL>LOADDLL|dllfile 61 SPECIAL>LOADMODEL|mdlname 61 SPECIAL>LOADRUN|runname 62 SPECIAL>LOADTOOLSET|toolname 62 SPECIAL>MESSAGE|severe|title|string 62 SPECIAL>NOINTERACTION|n 62 SPECIAL>READCUSTOM|graphfile 62 SPECIAL>REFRESH 63 SPECIAL>RESETINPUT 63 SPECIAL>RUNCOMMAND|cmdfile 63 SPECIAL>SECONDCLICK|graph 63 SPECIAL>SETFOCUS|number 64 SPECIAL>SETTITLE|title 64 SPECIAL>SETWBITEM|varname 64 SPECIAL>STOP|message 64 SPECIAL>STOPSIM|option 64 SPECIAL>SUBSCRIPT|range|elem1|elem2 64 SPECIAL>VARSELECT|prompt 65 SPECIAL>WINHELP|helpfile|data 65 SYNTHESIM>AUTO|n (n is 0 or 1) 65 SYNTHESIM>GO|n (n is 0 or 1) 65

TEST ..........................................................................................................................65 TIMEAXIS ..................................................................................................................66


TIMEAXIS>RESET 66 TIMEAXIS>SPECIALTIME|value TIMEAXIS>STARTTIME|value TIMEAXIS>STOPTIME|value 66 66 66

WORKBENCH ...........................................................................................................67 Command Use Summary ...........................................................................................67

6 Venapp Examples
Template Application..................................................................................................71
Model Setup 71 Welcome Screen 71 Main Menu 72 Presenting Structure Scenario Setup 73 Simulating 75 Displaying Output 75 Gaming 76 Analysis 76 Demo Disk 78 Vensim Model Reader Multiplayer Games 79 Screen Updating 79 Dialog Based Changes

71

72

Other Examples .........................................................................................................78


79 79

Moving Beyond ..........................................................................................................79

7 Command Scripts
Command Files ..........................................................................................................80 Supported Commands ...............................................................................................80
FILE 81 MENU 81 SETTING 81 SIMULATE SPECIAL 81 TIMEAXIS

80

81 81

Preparing files for use with Vensim Application Runtime ...........................................81

8 External Functions
External Function Libraries.........................................................................................83 Defining External Functions .......................................................................................83
version_info 84 funcversion_info 84 set_gv 84 user_definition 85 vensim_external 86 Compiling and Linking

83

87

Calling External Function ...........................................................................................87

Literal Arguments Lookup Arguments Vector Arguments Constant Matrices Data Matrices 90 Modifying Values User Loops 91

87 87 88 89 90

Constant and Data Definition Functions.....................................................................92


Notes on Memory Alllocation 92

Global Variables.........................................................................................................93 Memory Management ................................................................................................94 Error Handling ............................................................................................................94 Startup and Terminate Routines ................................................................................95 External Function Library Files...................................................................................95 External Functions in Compiled Simulations ..............................................................96 External Functions and Venapps ...............................................................................96 External Functions and the Vensim DLL ....................................................................96

9 Dynamic Data Exchange


Using Vensim as a Server..........................................................................................97
Establishing a Link 97 Executing Command Getting Values 97 Hot Links 97 Excel Example 97 97

97

Using Vensim as a DDE Client...................................................................................98


int PASCAL vdde_execute(int dde_channel,char *ddecommand) ; 98 int PASCAL vdde_initiate(char *servname,char *topic) ; 99 int PASCAL vdde_poke(int dde_channel,char *item,char *value) ; 99 int PASCAL vdde_request(int dde_channel,char *item,char **buf,unsigned max_wait) ; 99 int PASCAL vdde_vrequest(int dde_channel,char **item,char **buf,int nitem,unsigned max_wait) ; int PASCAL vdde_terminate(int dde_channel) ; 100 void PASCAL vensim_transmit_dde(void) ; 100

99

10 Compiled Simulations
Vensim Interface ......................................................................................................101 Details of the Compilation Process ..........................................................................101 Compile Errors .........................................................................................................102 mdl.bat .....................................................................................................................103
Path 103 Compilation 103

101

Compiled Simulation for the Vensim Application Runtime........................................103 Compiled Simulations and the Vensim DLL .............................................................104 Compiled Simulation with Double Precision Vensim ................................................104 Compiled Simulation Files........................................................................................104
Other files 104

Compiled Simulations and External Functions .........................................................105

11 Vensim DLL Overview


Functionality .............................................................................................................106
Full DLL 106 Minimal DLL 106 vensim.ini 106

106

Redistribution ...........................................................................................................107
Commands and Output 107 Simulation Control 107 Data Access 107 Structure Access 107 Miscellaneous 108

Installation Notes......................................................................................................108
DLLs Installed Model Files Library Files Sample Uses 108 108 108 109

Visual Basic Example...............................................................................................109


General (Prototype & Global) Code 110 Form (Startup) Code 110 Simulating the Model 111 Retrieving Data 111 Plotting Results 111 VB Controlled Simulation 112 SyntheSim 112 Starting a Game 113 Continuing or Backing up a Game 113 Ending a Game 114 Speeding up a Game 114

Excel Example .........................................................................................................115


Getting Model Variables 115 Vensim Info 116 Other Info 116

Displaying and Printing Sketches and Tool Output ..................................................116

12 DLL Function Details


Language Notes.......................................................................................................118 vensim_be_quiet ......................................................................................................118 vensim_check_status ...............................................................................................119 vensim_command ....................................................................................................120 vensim_continue_simulation ....................................................................................120 vensim_finish_simulation .........................................................................................121 vensim_get_data......................................................................................................122 vensim_get_dpval ....................................................................................................123 vensim_get_dpvecvals .............................................................................................124 vensim_get_info .......................................................................................................124 vensim_get_sens_at_time........................................................................................126 vensim_get_substring ..............................................................................................126 vensim_get_val ........................................................................................................127 vensim_get_varattrib................................................................................................128 vensim_get_varnames .............................................................................................129 vensim_get_varoff....................................................................................................130 vensim_get_vecvals .................................................................................................130 vensim_set_parent_window .....................................................................................131 vensim_show_sketch ...............................................................................................132 vensim_start_simulation...........................................................................................133 vensim_synthesim_vals ...........................................................................................134 vensim_tool_command ............................................................................................135 VensimContextAdd ..................................................................................................136 VensimContextDrop .................................................................................................136

118

13 Distributing your Work


Vensim Model Reader..............................................................................................137 Vensim Runtime.......................................................................................................137 Vensim Application Runtime ....................................................................................137 Vensim Minimal DLL ................................................................................................138 Vensim DLL Runtime ...............................................................................................138 Vensim Application Distribution License...................................................................138 Venapp Install Builder ..............................................................................................139

137

14 Connecting to Databases with ODBC


Overview 140 Reading from a Database 140 Writing to a Database 141

140

Database Input/Output File Structure.......................................................................141


Action Keywords 141 Informational Keywords 142

Database Input Examples ........................................................................................145


Full Source Read 145 Using Variable IDs 145 Specific Variable Read 146 Different Time Fields 146 Data Stored by Time 146 Values by Scenario 147

Database Output Examples .....................................................................................147


Output using Delete and Insert Output Using Update 148 Simple Database Example 149 147

Database Notes .......................................................................................................148

Introduction
Vensim DSS is a powerful environment for developing high quality simulation models. The standard features to aid in this development are covered in the Tutorial, Reference Manual and Modeling Guide. In addition, Vensim DSS has a number of capabilities that go beyond simple model development. Vensim DSS allows you to extend the Vensim modeling language with your own functions, to build user interfaces for models, and to exercise control over Vensim from other applications or through batch processing. The DSS Reference Supplement covers these additional capabilities. Like the Reference Manual, this supplement is designed with reference in mind, although some of it is more discursive.

Double Precision
Vensim DSS is available in a double precision version that improves computational accuracy, while allowing nearly complete compatibility with the regular Vensim. The double precision version of Vensim can be installed by running the install program vdpdss32.exe contained in the Windows directory of the Vensim CD. (On the Mac use the Vensim DSS DP Installer.) This should be done after you have installed the regular Vensim DSS. The Vensim DLL corresponding to the double precision version (vdpdll32.dll and vdpdlm32.dll) will also be installed. The supporting library files will be installed as part of the regular Vensim installation. Note that the double precision version of Vensim DSS uses separate initialization information from the regular Vensim DSS. We created the double precision version of Vensim in response to requests for decreasing roundoff error. The simulation state is stored in a double precision format while all input and output is done in single precision. For large models the double precision version of Vensim essentially takes twice the memory, so it should be used with discretion. For most business models there seems little to be gained from the added precision. External functions and compiled simulations require special care with the double precision version of Vensim and this is discussed in Chapters 8 and 10.

Venapps
Venapps are special user interfaces that make it easier for people to interact with a model. Venapps are normally designed as button driven interfaces that simplify viewing the structure, examining the causality, and simulating and viewing the behavior in a model. Chapter 2 gives an overview of Venapps and includes some discussion of the theory behind building Venapps. It is a useful place to get started before you actually undertake the task of writing a Venapp. Venapps are made up of screens which, in turn, are made up of controls. Chapter 2 overviews this architecture and discusses different techniques for developing Venapps. Chapter 3 describes the Venapp Editor. The Venapp Editor is a configuration of the Sketch Editor that is used to edit Venapps. Chapter 4 details the different controls that are available for use in Venapps. This chapter will be mostly used for reference, although you might want to read through it to get a feel for the variety of things that can be done. Chapter 5 gives a detailed description of the commands that can be used to control Vensim from a Venapp. Commands are broken up into a number of classes, and Chapter 5 is arranged alphabetically by class.

Chapter 6 presents a sample Venapp. Working from an existing application is the most efficient way to develop your own Venapp, and the Template Venapp described in Chapter 6 is a useful starting point. While you are developing your applications, you might want to look through the section headings for hints on how to accomplish certain things.

Command Scripts
Command scripts are a method for essentially running batch processing from within Vensim. Chapter 7 describes how command scripts work and gives an example. The commands that can be used from a command script are a subset of the commands detailed in Chapter 5 (Venapps).

External Functions
External functions are functions you create that can be called from within a model during a simulation. External functions are not available on the Macintosh. Chapter 8 describes how to create and use external functions. Additional documentation is contained in the sample files that ship with Vensim.

Dynamic Data Exchange


Dynamics Data Exchange (DDE) is a mechanism that allows different applications to communicate with each other. Vensim DSS can serve both as a DDE server and a DDE client. Chapter 9 describes how to use Vensim as a DDE server and how to call another application during simulation to get data. Retrieving data using DDE requires the use of external functions.

Compiled Simulations
Compiled simulations can reduce simulation time (often to as little as one third of what it otherwise would be). Compiled simulations are not available on the Macintosh. Chapter 10 describes how to set up and use Vensim's compiled simulation capability.

Vensim DLL
In order to facilitate the development of custom applications, we have made Vensim available to run as a DLL. This allows you to use Vensim as part of an application written in another language such as Visual Basic. Chapter 11 gives an overview of the capabilities of Vensim's full and Minimal DLLs. It also provides an example of an application and describes briefly the other examples that come with Vensim. Chapter 12 documents the Application Programming Interface (API) used by Vensim DLL. There are a number of commands available, although much of the control of Vensim is done through the same commands Venapps use (as documented in Chapter 5).

Distributing your Work


Chapter 13 describes the different options that allow you to distribute your work to others.

Venapp Introduction
Vensim Applications (Venapps) are simplified, push button interfaces that allow users access to a Vensim model without going through the Vensim modeling environment. Other generic names for a Venapp are "Decision Support Systems," "Executive Support Systems," "Learning Environments," "Management Flight Simulators," "Games," "Menu Driven Interfaces," "Microworlds," "Packaged Applications," and "Scenario Generators." A Venapp uses a model and a set of rules for interacting with the model to give users simplified access to that model. To the user, the Venapp appears as a series of buttons, menus, or a sequence of screens allowing him or her to use and analyze the model in straightforward and meaningful way. The simplest way to understand Venapps and what you can do with them is to look at the examples. The templates and the Vensim Demonstration Disk Venapp can be run and the Venapp code examined. These are shipped with Vensim in the models directory. The Demonstration Disk Venapp can be accessed by loading C:\Program Files\vensim\models\intro.vcd (substituting the appropriate drive and directory if different) from the File>Open Model menu item.

Purpose of a Venapp
Give non-Vensim users easy access to models. Simplify scenario generation. Support interactive gaming. Provide on-line commentary on a model. Focus attention on specific aspects of a model. Provide control over what can be changed in making simulations of a model.

Learning with Venapps


The goal of interactive simulators is for the user to learn something valuable from the model. Users learn by examining structure, simulating the model then examining behavior, and discovering the impact of decisions on behavior.

Two Main Types of Interface


The simulation model interface imparts learning of the impacts of policies and decisions over a long time horizon (the full length of the model simulation time). The game interface imparts learning of current decisions on transient model behavior, and the cumulation of those decisions on overall outcome.

Two General Methods for Presenting Models


The overview approach. The detailed approach. Which of these you choose will depend on your goals for the user's learning. The simulation model interface combined with the overview approach gives the generalities of the model, the overall lessons. Editing boxes, sliders and switches alter a few key model assumptions and policy levers, and graphs and displays show a few select variables. The user might also choose in-depth analysis of the model behavior (looking at any or all model variables). The overview approach encourages users to make a

10

single important change (or experiment), or just a few changes, and observe these changes on the behavior of key variables. The old scientific maxim change one thing at once gives excellent insight into model behavior. The detailed approach is often more useful when the user wants the simulator to closely represent reality. The detailed approach can be useful while playing a game through the gaming interface. This high level of detail, mimicking reality, comes at a price. The user is essentially in the real world, though with an accelerated time span, and the outcomes generated in the model might not be traceable to actual individual policies (or even groups of policies) if many things were changed at once. In a simulation model, a highly detailed simulator can overwhelm the user and stifle the learning process, especially if the user is changing a lot of things together during each experiment (simulation run). Start simple, try it out on people, then move to detailed Building a Venapp often progresses iteratively. Starting simple allows you to get something up and running quickly, and allows users an introduction. Build the Venapp following the overview approach first, then move towards the detailed approach as users (or the builder) get comfortable with the Venapp.

Building Venapps
You can construct Venapps in any manner that you choose, and the process does tend to be iterative. The most important determinant of what is required in a Venapp are the needs of the user. Be sensitive to their needs and, if appropriate, include them in the construction process. When building a Venapp it is often desirable to start with the logical flow. Build the screens containing the menus and buttons you want so that you can test the usability of the Venapp. This is quick and can be done before a model is ready. Input screens can easily become overwhelming, and our experience is that it is best to break complicated input screens into a number of simpler components. Including more than ten distinct input concepts on a screen can be confusing. The best way to break things up depends on purpose, but there are usually some fairly natural hierarchies available. Output of the model can be limited to a small number of reports and graphs. However, there is a vast leap between prepackaged analysis (showing a small number of predetermined reports and graphs) and active analysis controlled by the user. For pedagogical reasons, we encourage you to give users access to the interactive analysis capabilities possible in a Venapp this should help to give the underlying model validity in the eyes of the user. See the section on Analysis Screens below. Venapp are defined using a scripted input file that can be created using a text editor or using Vensim's Venapp Editor which behaves much like it does when working with models (details on its use are presented in Chapter 3). Regardless of the tools you use the actual Venapp code is stored as a text file conforming to the specifications outlined in Chapters 4 and 5. You might wish to base your Venapp on the templates provided and customize it to your needs. You can also write all the code in a Venapp from scratch. However, usually you will find it quicker to copy code, either full screens or just selected lines, from existing Venapps and modify this code for your particular needs.

General Guidelines
Examine sample Venapps. Copy and modify relevant code. Keep track of what you've done. Change one thing at once.

11

Start simple, try it out on people, and move to detailed. Expect a lot of variance in how people use a Venapp, no single correct path guarantees success.

Using the Text Editor


The Text Editor contains some useful shortcut keys to speed cutting, copying, and pasting. With the Num Lock key OFF, The minus key ( - ) cuts the highlighted selection OR the line the cursor is placed at. The plus key ( + ) copies the highlighted selection OR the line the cursor is placed at. The Ins key ( 0 ) pastes the content of the clipboard at the current cursor placing. Holding the Shift key down and pressing the arrow keys highlights the selection (or use the mouse).

The status bar on the Text Editor also contains a >Ctrl button that can be used to edit Venapp Controls without having to count the number of commas. Just click on the line you want to change, make changes in the dialog and click on OK. Note that lines with continuation characters ( \ at the end of a line) will not work properly with this technique.

Examining Screens
When a screen has been created, it can be viewed by either of two methods: Run the application with menu File>Run Venapp, then move to the desired screen. In the Venapp Editor you can also click on "Run Venapp" in the Status Bar at the bottom. In the Venapp Editor Click on Test Screen in the status bar. In the Text Editor Text Editor place the cursor at the desired screen then select menu item View>View Screen. Running the application sets up the model and all relevant files, but often prevents quick access to a particular screen. Viewing the screen with View Screen will quickly display the screen as it currently appears, but unless you have the model open in the background and all relevant files loaded, certain controls on the screen might not work properly (such as output controls which require a model and a loaded dataset).

Logical Flow in Venapps


Because Venapps work by shifting from one screen to another, there are no real restrictions on logical flow. Both linear and hierarchical menu systems can be implemented. It is up to you to decide how you want to organize your application. The Vensim Demo, for example, has a linear logical flow describing the features and value of Vensim, with generally hierarchical control inside of the example applications. Most of the examples, however, break from the pure hierarchy by providing links from simulation to analysis and back again.

Simulation Interface
In general, you will want the user to be able to examine the model structure, to simulate the model, and to look at output data and compare this to earlier runs. This suggests something like the following structure:

12

Opening Screen

Model Structure

Main Menu

Detailed Analysis

Input Screens

Simulation

Output Screens

Game Interface
A simulation model played as a game needs to be set up differently. Typically you will want one or two Game Control screen where the user sets up decisions and steps forward in the game. Usually this screen will have some input controls, a forward step button, and some output controls: numbers or a graph. For a very detailed game, input controls and output numbers and graphs might need to be on separate screens that are accessed from the Game Control. The user could also have access to the structure before or after playing the game.

Opening Screen

Model Structure

Main Menu

Detailed Analysis

Game Control

Input or Output Screens Optional

Screen-by-Screen Description
Often you will need more screens than the minimal set described here. Sometimes you might have 2, 3 or even perhaps 30 different input screens to set up the model, output screens can also vary in number. For more information on particular screens, examine the code for the template screens provided with Vensim (see Chapter 5 of this supplement).

13

Display Screens
Display screens are displayed until a button is pressed or a key is hit. This is done using the BUTTON or the ANYKEY controls. Once a button or any key is pressed, another screen is moved to. You can use these screens to move step by step through a series of screens, or simply to display something and then return to a control screen.

Opening
The opening screen will perform two functions: load the model and all related files, and display text to the user about the simulator. The opening screen in a Venapp is normally a title page showing the name of the application, along with copyright information, and showing a Continue button or asking for any key to be pressed to continue. You might want to have a series of instructional screens following the opening if the simulator is presented to new people all the time.

Menu and Button Screens


Menu screens allow your user to choose a number of alternatives. Menu screens are most naturally hierarchical, but there is no requirement that you use such a format. Both TEXTMENU and BUTTON objects can be used to move from screen to screen.

Main Menu
This screen contains the main options for the user. These might include buttons for the user to examine the model structure, set up and perform a new simulation run, set up a game, examine previous simulation runs, access the on-line help, and exit the simulator.

Structure
The structure screen can be as simple as looking at the model's views, or allow interactive examination of a model, such as under the Analysis Screens (see below).

Set Up a Simulation
A simple Venapp might have one setup screen combining the naming of the simulation run and setting of model inputs. At a minimum, when the user clicks on a Set Up a Simulation button in the Main Menu, you need to set the name of the simulation run (name the dataset) then move to an Input screen to set Constants and Lookups. A more complex Venapp will have multiple options leading up to the actual simulation.

Game Control
The Game Control screen is accessed after naming a dataset and starting the game. The screen will include a Forward button and usually shows some output: either a graph or numbers. Sometimes Output screens or model analysis are accessed from the Game Control. Often you can fit all the input controls on this screen, although you might need to switch to Input Screens.

Input Screens
The Input screen is used to set up model inputs (Constants and Lookups), either prior to a simulation or during a game (see Game Control, above). If necessary, you might need additional Input screens to accommodate large numbers of inputs. Input controls include text editing boxes (MODVAR) and sliders (SLIDEVAR) which modify a variable's value, and radio buttons (RADIOVAR) and list boxes (LISTVAR) which force the user to choose one option from a set of options. Lookup input controls (MODTABLE) are used for modifying lookups. Checkboxes (SWITCHVAR) toggle between two values (often for ON or OFF). The Input screen also contains the Simulate button (or Forward button in a Game Control). Clicking on this sets the simulation in progress and will move the user to the Output screens.

14

Running Screens
A running screen comes up transiently during a simulation, showing the results as they unfold, and then disappears. This can be an effective visual device for displaying information in two formats such as time graphs and Gantt charts. A running screen is very similar to an Anykey screen, except that you don't need a key stroke. The last two controls in the screen must be a COMMAND control asking for a simulation, and a CLEARSCREEN control telling which screen to shift to at the end of the simulation.

Output Screens
Output screens (and the output section of a Game Control screen) show values for output, usually in the form of numbers or a graph. Numbers can be displayed with the SHOWVAR command, small graphs can be generated with the GRAPHVAR command. More extensive and tailored output comes from the use of the Workbench Analysis tools (Causes Tree, Document, Graph, Causes Strip Graph, Table, etc.). To use these, you need to set a workbench variable before activating the tool. Another way to display output is by using the Custom Graph, Custom Table and Custom Report tools. In these, you can specify the variable ahead of time and display the customized output.

Analysis Screens
The user might be interested in examining the model in depth to determine structure and understand behavior patterns. Provide the user unlimited access to the model through a set of Model Analysis screens. These can be accessed from the Main Menu. Once a simulation (or game) has been run, all the dataset analysis tools can be accessed for analyzing and tracking down model behavior. The structure of a model can be examined at any time with the structural analysis tools. These screens could be accessed from the Main Menu screen, or from within the Simulation Output screens, or from the Game Control. If multiple paths lead to a screen, multiple return paths must be included.

Conditional Branching
Often it is desirable to branch to different screens based on something other than the direct input of the user. For example, in an application requiring input of basic data in the initialization process you might want to check to see if the data are available and branch to the input screen if they are not. (As a design principle, you should always give the user the option of branching to the input screen even if all the data are in.) Venapp supports conditional branching through the use of the IFTHENELSE and BRANCH commands and the BRANCH control.

Conditional Controls
Venapps also allow the conditional display and suppression of controls. For example you might want to display one of three bitmaps depending on the current performance status during a gaming simulation. Conditional controls are very similar to Conditional Branching but allow you to change the appearance of part of a screen without having to make multiple copies of the common elements of the screen.

Venapp Basics
Venapps are intended to work in conjunction with a model or models. It is important that the correct model is loaded when using a Venapp (there is a LOADMODEL command to make sure this happens). Normally, when developing a Venapp, you should create and refine the model in Vensim before you begin working on the Venapp itself. A Venapp can be run with different models or different versions of a given model. If you are doing this, you need to be sure that the variable names referenced in the Venapp are present in all the models.

15

Vensim Custom Definitions


Venapps are created and controlled using .vcd or Vensim Custom Definition files. These files define the appearance and behavior of the Venapp using a simple scripting language that is outlined below. To build a Venapp, you create a .vcd file using the Venapp Editor, Vensim's Text Editor or another editor of your choice. To run a .vcd file, you load the file into the Text Editor, and select the Run Venapp item from the File menu. This item is available only on files having extension .vcd. When you execute the File>Run Venapp command, Vensim makes a copy of the model you are currently working with along with the associated settings (loaded runs, selected variables and so on). This makes it simple to work on a screen with a quick turnaround time. The fully developed Venapp should, however, load the appropriate model, runs, toolset and custom graph definition, as part of its setup process. Failure to do so may prevent the Venapp from working properly. You can exit from a Venapp by using an MENU>EXIT command inside the Venapp as detailed in Chapter 4, or by selecting the close option from the Venapp window menu (or double clicking on the upper left hand corner of the window or clicking the right hand corner under Windows). To start a Venapp from Windows without going through the workbench and an editor you can invoke Vensim with the name of a .vcd file (including the extension). Vensim will load an empty model in the directory you specify, then execute the .vcd file. To work properly, the .vcd file must have a LOADMODEL command. Note that when starting a Venapp in this manner it might be desirable to use an alternative vensim.ini file (for example to suppress warnings). To do this, just include the name of the alternative .ini file in the command used to start the Venapp (use quotes is there are spaces in directory names). For example c:\Program Files\vensim\vensim.exe "c:\My game\game.ini" "c:\My Game\pipeline.vcd" If you load a .vcd file using the Filel>Open Model command on the Workbench, an empty model in the appropriate directory will be loaded and the .vcd file will be executed. Again, you need to have a LOADMODEL command in the .vcd file.

Binary Venapp Files


You can store your Venapp scripts in a binary format. This is required for some of the redistribution options (see Chapter 13) but also makes modification difficult. To save a Venapp in Binary form open the Venapp script in the Venapp Editor or the Text Editor and select File>Save As, entering a file name with extension .vcf (Vensim Custom Format). The Venapp script saved in this format is not a text file. It can be run by opening from the File>Open Model command but cannot be modified. The binary format does not provide data security, but is some protection against accidental modification. If you have included any PASSWORD controls, these will be written in an encrypted format to an arbitrary location in the .vcf file. It is not possible to recover the password from the .vcf file, though the .vcf file will open the password protected model. You can load .vcf files with the File>Open Model command or when Vensim (or Vensim Application Runtime) is started, just as you can for .vcd files.

Screens
Venapps, in contrast with Vensim, are organized around a single main active window or screen. This is intended to simplify interaction, minimize clutter, and direct activity. When a Venapp starts it gets a new window that is, by default, maximized. The Vensim Workbench is hidden so that all interaction is with the one main window. The screens are designed to be resizable so that relative positions are maintained if the window is no longer maximized.

16

The contents of the Venapp window are built up from the different controls available. You can draw text and lines, show variable values and display the output of Vensim tools. Each screen is given a name, and referenced by that name in the .vcd file. Names can be up to 14 characters long, and can contain any letters of numbers, but not imbedded spaces. To define a screen, begin the line with :SCREEN and then the name you choose, as in: :SCREEN HELLO Nothing else may appear on this line. A Venapp always starts from the first screen in the definition file, although other than that, there is no restriction on the order screens are defined.

SCREENFONT
The screen font lets you specify the default font for the current screen. The SCREENFONT command should appear first after the screen definition as in: :SCREEN WELCOME SCREENFONT,Times New Roman|12||0-0-0| This will set the default font to 12 point Times New Roman in black. All partial font specifications that follow will use this font to determine the complete font specification. For example TEXTONLY,0,0,0,0,C||18|B| would give 18 point bold Times New Roman text in black. You can also use the SCREENFONT line to specify a background color for the screen. Just follow the font's color with the R-G-B color for the screen. For example: SCREENFONT,Times New Roman|12||255-255-255|255-0-0| would give a red background with white text. You can use the special color -1--1--1 to have Vensim use the window background color set from Windows and -2--2--2 to use the button face color. The latter of these is helpful when you are using RADIOVAR or CHECKVAR controls as in: :SCREEN CHTEST SCREENFONT,Arial|14|B|0-0-0|-2--2--2 TEXTONLY,"Base Quality",10,10,0,0,L RADIO1VAR,"base quality",40,10,0,0,,[.7],Low RADIOVAR,"base quality",60,10,0,0,,[.8],Medium RADIOVAR,"base quality",80,10,0,0,,[.9],High SWITCHVAR,"labor cap switch",10,40,0,0,,[0|1],\ Prevent any increase in labor late in the project.

You can specify one screen font for each screen. Or leave it out. If you do not specify a screen font in a screen the most recent screen font specified will be used. Thus, by specifying the screen font for the first screen, you can set it for the whole application. NOTE The BUTTON, CHECKVAR, LISTVAR and RADIOVAR controls will use the default Windows Font unless you specify a font for the individual controls.

17

PIXELPOS
You can specify screen positions using percentage or pixelpositions. If you use percentages the controls will adjust their position and size whenever the Venapp screen is resized. If you use pixel position the controls will always appear in the same position relative to the upper left hand corner of the Venapp screen. Like SCREENFONT, a PIXELPOS command applies to the current screen and all the screens that follow until another PIXELPOS command is encountered. It should appear right after the SCREENFONT command or, of there is no SCREENFONT command right after the name of the screen. It takes a value of 1 to indicate the positions are specified by PIXEL and 0 to indicate they are specified by percent. For example: :SCREEN BYPIXEL PIXELPOS,1 TEXTONLY,"Near Top Left",50,50,0,0,L, :SCREEN BYPERCENT PIXELPOS,0 TEXTONLY,"Centered",50,50,0,0,C,

Venapp Internal Activity


While you need not be overly concerned with how Vensim does things, there is some basic understanding that makes it easier to design and refine a Venapp.

Loading
When you select the Run Venapp command from the File menu (or Open a Venapp file), your application interface is read and loaded. Simple mistakes of a syntactic nature are reported if they exist, and the contents of your application are read in and converted to the internal format used by Vensim. After all of this is done, the first screen is setup.

Setup
When you shift to a new screen, the new screen must be set up. To do this, the different controls are checked in the order they appear in the .vcd file. COMMAND and TOOL controls are executed immediately, and never again referenced. WIPTOOL controls are executed, but the output they generate fills itself in only over the course of a simulation. NOTE To change the order of Control in the Venapp Editor use the View>Screen Definition command or Right-Click on an empty portion of the current screen. Other controls are read and converted for display appropriate to the current conditions. For example, the WBVAR control reads the current workbench variable name, and stores it for display when painting. Input and BUTTON controls create windows, and prepare those windows so they contain the proper information. Normally the controls are all processed then Vensim paints the window and waits for user input. This will not be the case if there is a COMMAND control calling for a simulation. In this case, the simulation is performed before any more controls are read. Because of this, COMMAND controls calling for a simulation should always appear last (or second last if there is a CLOSESCREEN control). Any controls appearing after a COMMAND control that calls for a simulation will give unpredictable results and may display the wrong information. The only exception to this are additional COMMAND controls that can be used to reset the simulation configuration with commands such as SIMULATE>PAYOFF|.

18

Painting
After the screens have been set up, they are filled in (painted). Painting also occurs in the order the controls are entered, and reordering controls can prevent one control from blocking out part of another.

Reading
Before executing any commands, or shifting screens, the current screen is read. If there are any input controls, these are checked and their contents recorded. If the contents are not valid, a warning message reporting this is presented, the offending input is highlighted, and any commands or screen shifts are ignored. If the screen has no input controls, then reading the screen has no effect. If the user invokes a TEXTMENU or BUTTON control in which the first command is CANCEL, then the current screen is not read before exiting. Note that you cannot use & to combine commands with a CANCEL command only the CANCEL command will be executed, and the appropriate new screen shifted to.

Take-Down
After a screen has been read, and before you shift to another screen, the screen is taken down. All windows on the screen disappear and any additional tools or error windows that were not placed in the screen are also deleted. Note that if you find an extra window appearing in a Venapp, it is because of a bad takedown. You will need to exit and restart Vensim to correct things.

Refreshing
During simulation the contents of work in progress graphs and controls displaying model values are refreshed. You can also force a refresh by explicitly invoking the refresh command. This is useful if you are changing values (with the SETVAL command) and want the new values displayed, but do not want to rewrite the entire screen.

19

Venapp Editing
The Vensim sketch Editor can be used to write Venapps and it is also possible to move back and forth between the text representation and the visual representation just as you can with Vensim models. The visual editing of Venapps has been designed so that commentary and layout placed in the Venapp source text are preserved. The editing of Venapps using Vensim's Text Editor is done just as the editing of any text file would be. The only difference is that there is a >Ctrl button on the bottom. This button will parse a line containing a Venapp Control and allow you to edit it using the Venapp Control dialog described later in this chapter. You do not need to highlight the line, Vensim will simply use the entire line the editor is currently positioned over.

Starting the Venapp Editor


The analysis toolset default2.vts contains a tool for editing .vcd files. It appears second from the bottom and is labeled (the label is displayed if you allow the mouse to stop moving while positioned over the tool) Venapp Editor. Click on this tool and then select the Venapp file you wish to edit from the list of files presented. If you wish to create a new file type in a name for the new file and you will be asked if you want to create the file. In either case the Venapp Editor will open. Alternatively, if you have a Venapp file open in the Text Editor just use the menu item View>As Sketch to view this in the Venapp Editor. You can also move back to the Text Editor using View>As Text just as you can with a model. Note that the analysis tool that opens the Venapp Editor is actually a Text Editor tool configured to open Venapp files in WYSIWYG mode. While, strictly speaking, the Venapp Editor is not the Text Editor the appearance of the button for editing Venapps is sufficiently different that there should not be any confusion.

General Operation
The Venapp Editor behaves much like the sketch editor. You move things around by dragging them, you size things by dragging the handle in the lower right hand corner and you delete things with the Delete subtool, or highlighting them and pressing the Del key. Just as with a model, some of the information relating to a Venapp is not visible. The Venapp Editor places comments and non visual controls in the upper left hand corner of the sketch and marks them as hidden. You can see these by using the View>Hidden Elements command, but there is little reason to do so. Editing of control order and nonvisual controls should be done using the Screen Definition dialog described below. The Venapp Editor mimics the layout of the running Venapp. Unlike the running Venapp all of the visible controls have a box around them that can be used to manage resizing. Also, the exact appearance of the controls is likely to differ somewhat from the running Venapp. For example, a SHOWVAR control will always display 1.234 not a value corresponding the variable it is representing, a TOOL or WIPTOOL control will display the command used to invoke the tool and a SKETCH control will display the word "Sketch." The screens in a Venapp are treated analogously with the views of a model. You can navigate through the different screens using the Page Up and Page down keys and also the bottom status bar. To create a new screen select *New* from the bottom or use the View>New command. You can reorder the screens using the View>Reorder command. When a Venapp is started it will start on the first screen in the list of screens.

20

When you have the Venapp Editor open there will be a command on the File Menu to Run Venapp which will allow you to run the Venapp to check its operation. A shortcut for this menu item appears along the bottom statusbar. You can also test the screen you are currently working on by clicking on the Test Screen button that appears along the bottom status bar.

Screen Controls
To add controls to a screen click on a subtool corresponding to the control you want to add then click on a blank portion of the screen. When you do this the Control Definition dialog opens and you can enter information about the control. This dialog also allows you to change the type of control so that if the control you want to add is not in the tool list you can easily change to that control. The tools list contains the common controls: TEXTONLY - add text to the screen. RECTANGLE - add a framing rectangle to the screen. SHOWVAR - show the value of a variable. TOOL - put up tool output or custom graph output including Graphs, Strip Graphs, Tables and Trees. BUTTON - place a button on the screen. MODVAR -allow the Venapp user to change the value of a variable by typing in a new value. SLIDEVAR - allow the Venapp user to change the value of a variable by dragging a slider. RADIOVAR - allow the Venapp user to set a variable by choosing among radio button selections. SWITCHVAR - allow the Venapp user to set a switch variable value. LISTVAR - allow the Venapp user to select a variable value from a dropdown list. Since it is possible to change the type of a control it is also possible to change it to a non visible control such as command. If you do this you will no longer be able to see the control, but it will still be in the screen. Use the Screen Definition dialog to manage such hidden controls. If you want to edit an existing control click on it with any of the control subtools selected. If you have the Lock or Move/Size tool selected you can modify an existing control by clicking on it with the right mouse button.

Screen Definition
A Venapp screen typically has controls and comments that are not visible when the Venapp is running. For example, there might be a command to load a model. In addition to this the order in which controls are defined is important in determining the operation of the Venapp with the user presses the Tab key. The screen definition dialog described below allows you to edit everything in the screen - including what is visible. To open this dialog you can select the View>Screen Definition command from the menu, click on the Screen Definition button appearing at the bottom or use the right mouse button to click on the screen at any position off of a visible control.

Cutting and Pasting


Cut and paste work just as they do for the Sketch editor. Select the Pointer subtool and highlight the controls you want to copy by dragging or shift clicking. Then use Edit>Copy (Ctrl+C) to copy what you have selected. You can then use Edit>Paste (Ctrl+V) to paste the controls into another screen or the same screen they were copied from. Unlike the regular sketch tool you will not be queried to see if you want to replicate structure since there is not any structure to replicate: the controls will simply be copied verbatim.

21

To copy an entire screen just use Edit>Select All (Ctrl+A) followed by Edit>Copy. All controls and comments, including all hidden elements, will be copied. Copying will also place a metafile in the clipboard which can be used by other applications. This is unlikely to be of any value however, because the screen does not appear completely the same as it will in the running Venapp.

Deleting
You can delete controls using the delete tool just as you can in a regular sketch. Selecting one or more controls and using the Del key, or Edit>Cut will also remove the controls from the screen.

Loading and Saving


You save the work in the Venapp editor with the File>Save or File>Save As command (Ctrl+S also works). When you save the file it will be written to disk as a plain text file. You can edit that file in a text editor and reopen it the Venapp editor at a later time. If you open a Venapp file that contains errors, such as controls that do not exist, the lines that are not recognized will be treated as comments, and will have an exclamation point ! prepended to them. If you want to make use of these they will need to be edited. When you open the Control Definition dialog on a comment the entire comment appears in the text field (no parsing is done).

Control Definition Dialog


The control definition dialog is used to edit controls. You can open it up by clicking on any visible control with the a control definition subtool selected or by right clicking with the pointing subtool selected. You can also open the Control Definition dialog from the Screen Definition dialog and from the text editor.

Type allows you to set the type of control. You can change from one type to another at any time. The dropdown list displays the available control types - select the one you want. Text is the control text. Most typically this is displayed text or a variable name. Details on this are contained in Chapter 3. Vensim will automatically add the surrounding quotation marks. The Var button allows you to select a model variable name to place into the Text field. Click on this button and select the variable you want. Position allow you to set the position and size of the control. In most cases this will be done by sizing and positioning the control on the screen so you can leave this alone. If you size a control in the screen and decide you would prefer the default sizing you can check the or default button for width or height.

22

Using a default height is useful for BUTTON and any editing controls. TEXTONLY controls are often best left with default width and height. Justification allows you to set the justification - usually L, R or C. Font if not empty the edit box indicates a font that will override the screen font. You can select the font to be used by clicking on the Font button. If the edit box is empty the screen font will be used. Accelerators specify the accelerators to be used for COMMAND and TEXTMENU controls and ranges on variable setting controls. See Chapter 3 for more details. Commands Shows the list of commands to be executed when the control is activated. If a command fails no further commands are executed. You can change the order of commands by dragging them around in the list. You can also use the buttons to add, remove and modify the commands in the list. Delete deletes the highlighted command in the list. If nothing is highlighted nothing happens. Edit opens the Command Definition dialog on the highlighted command. If no command is highlighted nothing happens. Double clicking on any command in the list is the same as clicking on the command then clicking on the Edit button. Add opens the Command Definition dialog with an empty command and, if you click OK, adds the command the bottom of the list. Shift to Screen shows the screen that should be shifted to if the commands execute successfully. This is blank if no screen is specified. You can select a screen from the dropdown list or type in a name. When the Control Definition dialog is opened from the Text Editor the list of available screens will be empty.

Command Definition Dialog


The Command Definition dialog is used to create commands. It can be invoked from the Control Definition dialog and the Screen Definition dialog.

Class is the command class. Choose one from those available. Details on command classes are available in Chapter 4. Command is the command itself. Once you have selected a class the list of command for that class is available in the dropdown. Again details are in Chapter 4. Some classes do not have a command. There are three edit boxes for command options. The labeling of these edit boxes changes to reflect the interpretation of the options for the different commands. There is also line at the bottom of the screen describing what the command does.

23

Var when clicked on brings up the Variable Selection dialog and places your choice from it in the first editing box.

Screen Definition Dialog


The Screen Definition dialog is used to manage the order of controls on a screen and any hidden controls. It can be opened by clicking on an empty part of the screen with the right mouse button or by selecting the Screen Definition command from the View menu or bottom status bar.

Name specifies the name for the screen. You can type in a different name to change it. Screen Font - ... specifies the screen font. This is the default font that will be used for controls that do not specify an alternate font. Coordinate Reference allows you to choose how position information will be interpreted. If you select Absolute then the position parameters for each control will be interpreted as pixels. If you select Screen Percent the position parameters will be interpreted as a percentage of the visible screen size. Screen Percent is the default and if you resize a window in this mode the controls will fit themselves to the new window size. If you use Absolute the controls will remain in the same position regardless of the size of the window. Background Color specifies the background color for the Venapp window. You can explicitly select a color by clicking on the color button inside the small rectangle. You can also select Standard Window to use the same background color that standard applications display (the default). The Standard Button selection uses the color that appears in the face of buttons. This is useful for windows containing lots of buttons and also is you are using any SWITCHVAR or RADIOVAR controls.

24

Screen Content Below the above options is the content of the screen. The contents are broken up into three parts, comments, commands that are executed when the screen is first entered, and the controls that appear on the screen. You move between the different components by clicking on the appropriate tab. Almost all screens will have controls, while only some of the screens are likely to have opening commands so the dialog opens with the controls listed. Whether or not there are comments is entirely up to you. One note on the opening commands. These are normally things like setting the title, loading a model, loading a graph sets and setting up some simulation control parameters. In some cases you might want to do something like load a dataset, but only if the dataset exists. This would be accomplished with the command pair: FILE>EXISTS|base.vdf&SPECIAL>LOADRUN|base.vdf For this command pair to work it has to appear just like it does above. The opening command each appear on a separate line in the Venapp definition and thus you cannot include the above example in the opening commands. To use paired command like those above you need to put a COMMAND control in the control list. Controls in order - drag to reorder is the list of controls, commands or comments. All work the same. Drag any element in the list to another location to change its position. Delete deletes the highlighted element in the list. If nothing is highlighted nothing happens. Edit edits the highlighted element in the list. If nothing is highlighted nothing happens. Double clicking on the element is the same as clicking on it then clicking on the Edit button. Add adds a new element to the end of the list.

Testing the Venapp


You can run the Venapp you are editing anytime by using the File>Run Venapp command. The Status Bar at the bottom also contains a shortcut for doing this.

The left hand portion of this works identically to the regular sketch editor, allowing you to navigate the different screens in the Venapp just as you would navigate different views in a model. The remainder of the Status Bar is Venapp Specific. Run Venapp is a shortcut to the File>Run Venapp command and it launches the Venapp opening on the first screen. This will allow you to test the behavior of the entire Venapp. Screen Definition is a shortcut to the View>Screen Definition command. This opens the Screen Definition dialog described above.

Test Screen
Test Screen allows you to check the behavior of the current screen. This will be done with the currently active model, toolset and graph set. It will also be done with the model in an idle mode (not in gaming or simulation setup). Because of this the current screen may behave differently than it would in the full Venapp. Usually, if you make sure you have the right model, graph set and toolset loaded you should get the same behavior. However, to put the Venapp into a gaming mode (which requires a Menu>Game command) you may need to open the Venapp on another screen that starts the gaming and, in the Venapp, switch to the screen with gaming controls. When you click on the Test Screen button Vensim puts the Venapp into a special mode so that you can use Page Up and Page Down to pass through the screens, while the navigation buttons . You will also

25

be given an option to suppress error messages that appear as you do this. What would normally appear as a message with an OK Button will be displayed

Click No to stop these messages from showing up.

26

Venapp Controls
As discussed in Chapter 2, Venapps are made up of screens. With the exception of the :SCREEN, SCREENFONT and PIXELPOS keywords these screens are made up of a number of controls which, in turn, are made up of a number of fields. It is useful to think of four categories of controls:

Output Controls
Output controls place information, possibly from a run or other data source, on the screen. COLORCIRCLE displays a circle with colors set from variable values by subscript. COLORRECT displays a rectangle with colors set from variable values by subscript. GRAPHVAR displays a small graph of a variable over time. LINE draws a line from one point to another. PROMPT displays the prompt specified for the input control that currently has the focus (is being used). RECTANGLE draws a rectangle. RUNNAME displays the name of a run. SHOWCOMPANY shows the name of the company that has registered Vensim (only useful in packaged applications). SHOWDATEVAR displays a variable value as a date. SHOWEDATEVAR displays a variable value as a date using the European date convention (day/month/year). SHOWUSER, displays the name of the user that has registered Vensim (only useful in packaged applications). SHOWVAR displays the value of a variable. TEXTONLY displays text. WBVAR displays the name of the Workbench variable (the variable on which tools will act).

Tool controls
Tool controls place sketch information and output from the Vensim Analysis tools on the screen. SKETCH displays sketch information on the screen. TOOL displays the output of an Analysis tool or Custom graph or report. WIPTOOL is like TOOL but starts a WIP graph.

Input Controls
Input controls allow the Venapp user to input information into the screen. DATEVAR allows the user to enter a date in order to change the value of a model Constant or Game variable. EDATEVAR is the same as DATEVAR with European day/month ordering. LISTVAR displays a dropdown combo box with a series of values that can be chosen to set a Constant or Game variable. MODRUNNAME allows the user to type in the name of the run to be made. MODTABLE displays an small graph of a Lookup which, when clicked on, allows the user to use the Graph Lookup Editor to modify a Lookup function. MODVAR allows the user to type in a value for a model Constant, String variable or Game variable. RADIO1VAR and RADIOVAR allow the user to click on radio buttons to set model Constants and Game variables to different values. SLIDEVAR displays a slider that allows the user to set the values of Constants and Game variables. SLIDEVARTIE allows a number of SLIDEVARs to be tied together so that all of them add up to or are less than a specified value. SWITCHVAR allows the user to click on a check box to toggle the value of a model Constant or Game variable.

Action Controls.
Action controls are used to execute commands and determine the logical flow from one screen to another. ANYKEY executes a command when any key or button is pressed. This is useful for opening screens, screen sequences and screens showing work in progress. BRANCH contains a set of commands that will be executed if the execution of another command results in the branch being chosen. BUTTON displays a standard Windows 3D button with commands that will be executed when the button is clicked. CALLBACK contains commands that will be executed when the associated MESSAGE function is triggered during a simulation. CLOSESCREEN causes the current screen to be closed without any user action. This is useful for transient screens. COMMAND causes

27

the command to be executed when the screen is first entered. SETWB contains commands that will be executed when the Workbench variable is changed. TEXTMENU displays a line of text and contains a series of commands that will be performed when the line of text is clicked on or selected with the keyboard. TIMER displays a countdown time and contains a series of commands that are executed when the countdown reaches 0.

Control Anatomy
All controls are defined using the same format, but not all controls use all information. The "fields" or "components" of the control are separated by commas. The format for a control definition is:

Or, as it appears in the Control Definition dialog:

In source files control definitions can be broken so they continue on the next line by placing a backslash \ at the end of the line (where the break will occur). You may surround elements of a control in double quotes " " this is necessary if you have imbedded commas. The components of the control are described in detail below. NOTE If you are having problems with a control in a screen, check the number of components of the control and the number of commas. Incorrect number of commas are often causes of failure. Using the Control Definition dialog can prevent this type of error.

Control Name or Type


The control name specifies which control you want to use. A list of the available controls is included below. Depending on which control you name, some of the remaining components might not be used.

28

Control Text
The control text shows either what should appear on the screen, what variable should be accessed in the model or, for tool controls, what name the tool output should be given for printing. The control text must appear surrounded by double quotes ", and can contain anything except double quotes. To include a double quote within the control text precede the double quote by a backward slash \" as in BUTTON,"Start \"targeting\"",50,90,0,0,C,Ss,MENU>RUN If you are working with the Control Definition dialog you do not need to worry about quotes - Vensim will automatically put those in place. Just type in the exact string you want to use or have appear.

X,Y,Width,Height
Specifies the position and size of the control. The measurements are either in pixels or in percentage of the screen. If you specify a control to have a location that is off the visible screen it will not be visible, though it will exit. Only integers are supported. In percentage mode when the screen is resized, the different screen components will reposition and resize themselves relative to the new dimensions. When the screen is in pixel position model no change will be made when the window is resized. For many controls, you can set width or height to 0 and let Vensim choose an appropriate value. In the Control Definition dialog just click on the or default checkboxes. This is useful for BUTTON, TEXTMENU and TEXTONLY where it is difficult to know the width or height of the control in advance. For tool output, or RECTANGLE controls, a 0 width or height does not make sense.

Justification
Justification determines how the control is displayed relative to the specified position, and also the font and color used in the display. The first character is the justification L, l mean left justified. For a lower case l, the background around the text will be erased then the text is drawn. For an upper case L, the background will not be erased. Erasing the background can be useful for creating labeling effects. C,c means centered. Use lower case to erase background. R,r means right justified. Use lower case to erase background.

The justification occurs relative to the x position specified. If you use the default width the appropriate width will first be determined before the justification is done so that you should get the alignment you want. Justification does not affect the y position. The y coordinate specified is the coordinate of the top of the control. Not all controls use justification. The output controls and the RECTANGLE control do not use justification. For slider controls the justification entry is used to determine orientation with V for vertical and H for horizontal. This is discussed in more detail in "SLIDEVAR" below.

Font
Following the justification character you can name a font and color. The format for this is: |font name|font size|font attributes|red-green-blue| font name is the name of a font such as "Times New Roman". font size is the size of the font in points. font attributes can be any of

29

B for bold. I for italic U for underline S for strike-through

red-green-blue is the color specification as an RGB color. Each of red, green and blue should be a value between 0 and 255 inclusive.

If you do not specify all components of the fonts and color whatever SCREENFONT you may have set will be used to fill in the remaining components. Thus the definition: :SCREEN TEXT RECTANGLE,"",10,10,80,80 TEXTONLY," clear center ",50,5,0,10,C TEXTONLY," opaque bottom center ",50,85,0,10,c TEXTONLY,"right",90,50,0,0,R TEXTONLY,"left",10,50,0,0,L TEXTONLY,"big",40,20,0,0,L||22| TEXTONLY,"tiny",40,40,0,0,L||6| TEXTONLY,"bold",40,50,0,0,L|||B| TEXTONLY,"script",40,60,0,0,L|Symbol|14||0-0-0 Will generate the output:

NOTE You can specify a font by clicking on the Font button in the Control Definition dialog. The Text Editor also contains a function to insert font and color names so that you can choose the font you want more accurately. To use this type C| for justification and then invoke Edit>Insert>Font or click on the Font button on the status bar. A font selection dialog will appear. Select the font and click OK.

Accelerator/Range
This component is used for two purposes according to which control is being used. Accelerators allow keystrokes to be translated to menu selections. Ranges are used for setting the minimum and maximum values for a variable.

30

Accelerator Accelerators are used for TEXTMENU and BUTTON controls only. They invoke the command and new screen for the corresponding control in response to the corresponding key being typed. You can have any number of keys accelerate to the same command (for example Esc, X, x, E and e are all acceptable ending characters for the Vensim demo). To use button accelerators the Alt key must be held down. Note that accelerators are case sensitive. If you want both lower and upper case, then enter them. If you want to include the Esc key as an accelerator, use \027. In general \xxx will be read as a decimal ASCII code. Note that Tabs and Carriage returns are captured elsewhere and not available as accelerators. Range Ranges are used for input controls to test to see if the input value falls within a reasonable range. If it does not, the user will be given a message telling them what the range is. Range specification takes the form [min|max|missing] for example [0|100.0|999] where 0 is the minimum and 100 the maximum, and 999 indicates a missing value. The missing value would normally not be within the range. To specify only a minimum use a single number (as in [0]) to specify only a maximum use the form [|100]. To specify only a missing value use the form [||999]. The obvious combinations also work. The missing value is used to signal the input control to be left blank. Conversely, if the input control is blank when it is read, or contains NA the missing value is returned. If you do not specify a missing value an empty input control will return an error message. The missing value is only used for the MODVAR control. By default input controls display values using Vensim's pretty notation (1,000, 100M, etc.). To use scientific notation instead, you can put a percent % at the beginning of the Range field as in: %[0|10|999] Input controls all take numbers in Vensim's pretty format, or in scientific notation. Range for Axis Labels The MODTABLE and GRAPHVAR controls use the range field to determine whether or not to put labels on their output and how to scale those labels. In this case the range label should take the form: xl[xmin|xmax]yl[ymin|ymax] ALL LOWER CASE! x refers to the x-axis, y to the y-axis. The l (lower case L) refers to labeling. If you include l, the axis will be labeled, if not it will not be labeled. If you specify a maximum or minimum in square brackets after the axis name these will be used in setting up the scales for the axes. For example GRAPHVAR,"Inventory",10,10,20,80,,xlyl[0|1000] GRAPHVAR,"Inventory",40,10,20,80,,y[0|1000] GRAPHVAR,"Inventory",70,10,20,80,,xl would yield

31

If you follow x or y by a % then scientific notation will be used for the label numbers. This can be very useful for x axis in the range 1900-2100 as, for example: GRAPHVAR,"Population",40,10,20,80,,x%l[1900|2000]

Command
The command is invoked when a TEXTMENU or BUTTON control is selected or when a COMMAND or TOOL control is first encountered. The available commands and their syntax is discussed in detail in Chapter 5. For input controls the command field is used to input additional text. This is used for RADIOVAR, SWITCHVAR, DATEVAR and EDATEVAR as described below.

Shift to Screen
The shift to screen determines which screen is used after a command has been completed. For the example shown, the screen named SETUP would be entered. If this entry is empty, the current screen is maintained. If this entry names a screen that does not exist, the current screen is reentered. The way missing screen names is handled simplifies interface construction since partial interfaces can be used. Errors can occur if a CLOSECREEN control attempts to shift to an unknown screen and this condition should be caught by Vensim.

Long Lines and Quotes


If you use the Venapp Editor Vensim will manage both long lines and quotes without your intervention. If you are using a text editor you can manage long lines by using continuation lines. You can put control information on more than one line by ending a line in a backslash \. The next line is treated as if it were part of the previous line. You can, in this fashion, break a line anywhere including in the middle of a quoted string. Note that the backslash \ must not be followed by any spaces. Quotes can be put around any field in the control description and allow embedding of commas in this fashion. If you wish to include a quote inside of a quoted string then you must precede it with a backslash as in \". The following three control definitions are the same: BUTTON,"Quit",50,95,0,0,C,Qq,MENU>EXIT, BUTTON,"Quit",50,95,0,0,C,\ Qq,MENU>EXIT, BUTTON,"Quit",50,"95",0,0,C,Qq,"MENU>EXIT", The second control definition is broken into two lines. The third control definition puts quotes around 95 and MENU>EXIT. These quotes are superfluous, but quotes are necessary whenever a control element contains an embedded comma.

32

Comments
You can comment out part or all of a line by preceding it with an exclamation point ! or a left curly bracket {. Everything that follows the comment delimiter will be ignored. To comment out multiple lines you will need to put a delimiter at the beginning of each line.

Detailed Control Description


In the following description, the control is named, and the name is followed by those components of the control definition used. The components are: txt - The control text. pos - The position of the control including width and height. jst - Justification acc - Accelerators/Ranges com - Command/Add text scr - The screen to shift to.

Some comments are included for special usage of any of these components. The Controls are listed in alphabetical order. Note that for most input controls and a number of output controls you can name a variable using Subscript Ranges rather than Subscript Elements. If you do this the first selected Subscript Element within that range will be used. By combining this behavior with the SPECIAL>SUBSCRIPT command you can have a single screen that take in values or present results for a number of different variables.

ANYKEY - com scr


Execute the command and shift to the named screen when the user presses any key or clicks on the mouse. This is usually used to control liner movement through a set of screens. If a screen contains TEXTMENU or BUTTON controls the ANYKEY control should appear last, and will be activated for keys and button presses other than those trapped by the BUTTON and TEXTMENU controls. ANYKEY,"",0,0,0,0,j,a,,S2 ANYKEY,,,,,,,,,S2 The above are equivalent. filling in the fields makes it clearer which is which. Note that you cannot fill in the command field, except with valid commands.

BITMAP - txt pos


Displays the named bitmap in the designated location. This is simpler than placing the bitmap into a sketch view and displaying that view. BITMAP,"logo.bmp",10,10,0,0, Will place the bitmap contained in logo.bmp near the upper left corner. Use the size 0,0 to have the bitmap display at its natural size. If you specify a size the bitmap will be shrunk or stretched to fill that size (the results of shrinking or stretching a bitmap are not always that good). Note that the name of the bitmap can also be a string variable that will evaluate to a file name. This is useful if you have bitmaps associated with different subscripts and want to display one for the selected subscript. For example: product : glue, nails ~~| bitmap file[glue] :IS: 'glue.bmp' ~~| bitmap file[nails] :IS: 'nails.bmp' ~~|

33

BITMAP,"bitmap file[product]",5,5,0,0 BUTTON,"Glue",5,90,,,,,"SPECIAL>SUBSCRIPT|product|glue",BITMAP BUTTON,"Nails",15,90,,,,,"SPECIAL>SUBSCRIPT|product|nails",BITMAP

BRANCH - txt com scr


The BRANCH control does nothing until it is explicitly referenced by a BRANCH command. txt is used as a label which the BRANCH command should match. Once the BRANCH control is referenced it replaces the invoking command, adding additional commands and a new shift to screen. The commands are executed in order just as any other command sequence. For example: BUTTON,"Run the model",20,20,0,0,,,IFTHENELSE&TEST>TSUM=100&\ BRANCH>RUN&SPECIAL>STOP|Numbers must sum to 100, BRANCH,"RUN",0,0,0,0,,,,RUNNING Here the IFTHENELSE command causes TEST>TSUM=100 to be checked, if it is true (TSUM is equal to 100) then BRANCH>RUN is executed - sending control the BRANCH control with txt "RUN". The commands in this control (there are none) are executed and then the new screen RUNNING is shifted to. If the test failed (TSUM not equal to 100) a stop sign appears, and processing stops. The labels on BRANCH controls should be unique within a screen, but can repeat from screen to screen. Only the current screen is tested for the named branch when a BRANCH command is issued. See the IFTHENELSE, TEST and BRANCH commands for further discussion.

BUTTON - txt pos jst acc com scr


The BUTTON control allows you to put a button on the screen to execute commands and shift to other screens. The control is activated when the user clicks on the button, or presses the appropriate accelerator key. Button accelerators need the Alt key to be activated, even when there are no edit type input controls present. txt contains the name to appear on the button. com is executed when the button is pressed and, if successful, Venapp shifts to the new scr. If scr is empty, then the current screen is retained without change (no repaint will be done). Button,"Capacity",50,15,15,15,C,Ww,,OV_CAPACITY

CALLBACK txt com scr


The CALLBACK control contains commands that are executed in response to a MESSAGE function called during a simulation. The text field contains a string that is compared with the string passed to the MESSAGE function. For example consider the model equation: msg = SAMPLE IF TRUE(:NOT: msg,IF THEN ELSE(:NOT: msg :AND: Time >= 40,MESSAGE('PROB',5),0),0) ~~| If this is combined with the screen: :SCREEN SIMMER COMMAND,"SIMULATE",50,45,0,10,,,MENU>RUN CALLBACK,"PROB",0,0,0,0,,,SPECIAL>MESSAGE|You have grown too old&\ SPECIAL>ALIASSCREEN|OUTCOME|OLDSTER CLOSESCREEN,"",0,0,0,0,,,,OUTCOME This will put up the message at time 40 and alias the screen OLDSTER to the alias name OUTCOME. Thus, at the end of the simulation the Venapp will shift to the screen OLDSTER.

34

CLOSESCREEN - com scr


Close the screen. Only useful for temporary output display windows during a simulation. Like command, except the new screen is shifted to. :SCREEN RUNNING WIPTOOL,"GR1",0,0,100,100,,,CUSTOM>WIP COMMAND,"",0,0,0,0,,,MENU>RUN1|O, CLOSESCREEN,"",0,0,0,0,,,,RESULT

COLORCIRLE txt pos


Draws a circle (really an ellipse) of the designated size based on the variable named in txt. The circle is colored according to the value relabeling options, which are interpreted as RGB color definitions. For example COLORCIRCLE,"STOP VAL?0=0-256-0?1=256-256-0?2=256-0-0",10,10,20,20 Would draw a green circle if STOP VAL is 0, yellow is STOP VAL is 1 and red if STOP VAL is 2. If STOP VAL were to take on any other value the circle would be shown as black. For subscripted variables COLORCIRCLE uses the last subscript to divide up the circle into a series of equal sized pie wedges, and the second last subscripts to divide the circle into a series of radii. If there is only one subscript, the pie wedges will all start at the center and go to the edge. Consider the equations: rad : (r1-r2) ~~| arc: (a1-a2) ~~| color[rad,arc] = rad + .1*arc ~~| and the control COLORCIRCLE,"COLOR[rad,arc]?1.1=0-0-0?1.2=128-128-128?\ 2.1=192-192-192?2.2=256-256-256",10,10,80,80

The use of gray scale here is for the purposes of printed output only. In general you will want to use colors to see what is happening. The variable name is subscripted using Subscript Ranges. Vensim expands those subscript ranges to determine how many values there are. If you use a Subscript Constant it is treated literally. You can use the format var[subscript range, subscript constant] to get concentric circles. See the SHOWVAR command for more discussion on the conventions around specifying the time, run and so on for the variable's data. COLORCIRCLE and COLORRECT provide a novel and sometimes very powerful method for displaying three dimensional data. The COLORCIRCLE control is most powerful if there is a

35

reasonable physical interpretation of the circle (locations in a city for example). COLORRECT is appropriate for showing such things as the value of two parameters are they influence an output.

COLORRECT txt pos


The COLORRECT control functions exactly as the COLORCIRLCE control except that it draws color to a rectangle instead of a circle. The second last subscript is varied for each row, and the last subscript for each column.

CONDITIONAL txt
The CONDITIONAL control allows the conditional inclusion of different commands and controls within a Venapp screen. The control uses the format CONDITIONAL,"Test Var=1",, The final two commas are very important. The expression in quotes is any valid model variable comparison to a number or other model variable. If the statement contained in the CONDITIONAL control is false, each control following the CONDITIONAL control will be ignored. This will continue until another CONDITIONAL control is encountered. The second CONDITIONAL control may specify a new condition, or it may be blank to indicate the termination of the conditional test. This should be clear in the following example. :SCREEN CONDTEST CONDITIONAL,"product is active[p1]=1",, SLIDEVAR,"Price[p1]",10,10,15,6,H,%L[0|60|1] CONDITIONAL,"product is active[p2]=1",, SLIDEVAR,"Price[p2]",10,20,15,6,H,%L[0|60|1] CONDITIONAL,"product is active[p3]=1",, SLIDEVAR,"Price[p3]",10,30,15,6,H,%L[0|60|1] CONDITIONAL,"",, ! . . . other stuff CONDITIONAL,"product is active[p1]=0",, BUTTON,"Launch 1",10,10,15,6,,,SIMULATE>SETVAL|product is active[p1]=1,CONDTEST CONDITIONAL,"product is active[p2]=0",, BUTTON,"Launch 2",10,20,15,6,,,SIMULATE>SETVAL|product is active[p2]=1,CONDTEST CONDITIONAL,"product is active[p3]=0",, BUTTON,"Launch 3",10,30,15,6,,,SIMULATE>SETVAL|product is active[p3]=1,CONDTEST CONDITIONAL,"",, ! . . . This screen would either contain a launch button, or a slider to set price, for each product.

COMMAND - com
Executes the command. This is usually used in the prolog of a screen to set up conditions to the appropriate state, or to initiate a simulation. COMMAND controls are executed when the screen is set up in the order they are entered. The detailed list of commands is given in Chapter 5. :SCREEN WELCOME2 SCREENFONT,Times New Roman|12 COMMAND,"",0,0,0,0,,,"SPECIAL>SETTITLE|Test Only" COMMAND,"",0,0,0,0,,,SPECIAL>LOADMODEL|add.vmf

36

COMMAND,"",0,0,0,0,,,SPECIAL>READCUSTOM|add.vgd COMMAND,"",0,0,0,0,,,SPECIAL>CLEARRUNS COMMAND,"",0,0,0,0,,,SPECIAL>LOADRUN|base.vdf

DATEVAR - txt pos acc


Sets up an editable field to enter a date into. txt contains the name of the constant or game input with the prompt information following the |. The accelerator specifies the range for the model variable, the conversion units, and the 0 value. The conversion units must be Y, M, W or D for year, month, week and day respectively. The 0 value is specified as a date following this. For example DATEVAR,"FINAL TIME",10,10,10,0,,[10|50]Y1/1/50 would treat the input number as a year, with year 0 being January 1, 1950 and the value allowed to range from 1/1/60 to 1/1/2000. Note that if only two digits are specified for a year 1900 is added to the number. If you leave out a start date the 0 value is assumed to be 1/1/1900. If you leave out conversion units the dates are converted as yearly. The minimum and maximum values are measured in the units of the model variable not as dates and are optional (though recommended). Dates can range from 1/1/100 to 1/1/32000. NOTE Dates do not recognize leap years and for this reason may be inaccurate when converted to days or weeks.

EDATEVAR
EDATEVAR is the same as DATEVAR except it uses the European ordering (Day/Month/Year) instead of the American (Month/Day/Year) order.

GRAPHVAR txt pos jst acc


Draws a small graph of the variable named in txt. The graph will be shown for the first loaded run unless you specify a different run using & runname as in GRAPHVAR,"Inventory&strike",40,10,20,80,,y[0|500] You can put labels on the graph and specify range according to the rules discussed under range above. The GRAPHVAR command can be used to create many small graphs quickly. You can specify a font for the labels in the jst field.

LINE - pos jst


Draws a line from x,y to x+width,y+height. Only the color portion of justification is used, but you must include a valid justification letter as in: LINE,"",0,50,100,0,C||||255-0-0 This would draw a red line across the middle of the screen.

LISTVAR - txt pos acc


The LISTVAR control allows you to enter a list of values for selection. The list is shown as a dropdown combo box with a small downward pointing arrow to the right. txt contains the name of the variable to change with the prompt information following the |. acc contains the range specification along with a list of values. If you specify a range in acc the user will have the option of typing in a value for the LISTVAR. If no range is specified, the user will only be able to choose from the presented list.

37

The list follows the optional range as a series of numbers separated by bars |. You can also use description=number depending on purpose. For example LISTVAR,"TENSION",10,10,30,0,,[0|50]20|30|40|50 would show the choices 20, 30, 40 and 50 and allows the user to type in a number between 0 and 50 whereas LISTVAR,"TENSION",10,10,30,0,,Low=20|Medium=30|High=40|Maximum=50 would show the choices Low, Medium, High and Maximum (if a description is specified the number is hidden) and not allow the user to choose anything else. If you use LISTVAR and the current value of the Constant or Game input is not included in the list, the value will be added to the list, or entered into the edit field as a number if a range has been specified.

MODRUNNAME - txt pos jst


Set up an edit box to modify the run name. txt can contain a | followed by prompt information. This information will be displayed at the prompt line when the user enters the edit control box if the PROMPT control is used. MODRUNNAME,"|Enter the new name (<8 chars) for the run",25,29,20,0,L,

MODTABLE - txt pos acc


MODTABLE allows the user to change the shape of a Lookup table. txt contains the name of the lookup table. A | separates the name from prompt information. The Lookup table is displayed as a graph in the space allocated. When the user clicks in this area with the mouse the Lookup Editor is invoked allowing the user to modify the Lookup. You can use the acc field to specify labeling choices and scales for the displayed table. If you precede this information with an r, then the table is displayed as a read only Lookup table, and cannot be activated for editing. This is useful if you are offering choices among a number of alternative Lookups. MODTABLE,"EfficGrowthLow Lookup",40,12,12,8,C||8| |,rxlyl[0|.08] MODTABLE,"Effect Pop Poll Lookup",40,12,12,8,, The first of these is displayed, but not active. The second is active. The font in the first is used to set the labels.

MODVAR - txt pos acc


MODVAR allows the user to type in a new value for a variable. txt contains the name of the Constant or Game Input for gaming. A | separates the name from prompt information. acc, optionally, contains range information used in the validation of the user's input. MODVAR,"PERCENT BUDGET ADV",25,44,15,0,L,[0|10|6] Here the value 6 (the original model value) is used for missing to allow entry of only changed assumptions. When this variable takes on a value of 6 the editing box created for the modification of the variable will be left empty. If you ask to modify a variable that is not contained in the model you are working with MODVAR will display error in the editing window. If you ask to modify a Game variable and the game is not running MODVAR will display Game Over in the editing window. Note that for String Variables MODVAR will let the user set a string value for the variable. This can later be used with SHOWVAR to display the user defined label.

38

PASSWORD txt
Allows you to open a password protected model. The PASSWORD control should be set in the form PASSWORD,opensesame Do not use quotes! The password should be entered in the same way it was entered for the model (the same case as well). The PASSWORD control can be placed in any screen of the Venapp, and you can have up to four PASSWORD controls in one Venapp. When the Venapp requests that a new model be opened, the password for that model will be tested against all passwords entered into the Venapp. If you save your Venapp in .vcf format it is not possible to recover the password from the .vcf file. If you try to open a model from within a Venapp and have not specified the password for that model, the user will be queried for a password. This is true whether you have left out the PASSWORD control or used the PASSWORD control but with the wrong password for the model.

PROMPT pos jst


Displays a prompt at the specified location. The prompt specified for an input control is displayed when the user moves to that input control using either the mouse or the tab key. (technically when the input control gets the input focus). PROMPT,"",1,66,0,0,L||10 Displays a prompt left justified as 1 and 66 using a 10 point face size.

RADIOVAR/RADIO1VAR - txt pos acc com


The RADIOVAR control is used to select one among many (such as Low, Medium High). txt contains the name of the Constant (or Game Input for gaming). A | separates the name from prompt information. The accelerator field hold the value associated with that particular radio button, and the com field the text to be displayed. RADIO1VAR is used to begin a related group of radio buttons. A typical RADIOVAR use would be: RADIO1VAR,"PRICE SENSITIVITY|Enter the sensitivity of sales \ to price",50,36,14,0,,[3.0],High, RADIOVAR,"PRICE SENSITIVITY|Enter the sensitivity of sales \ to price",65,36,14,0,,[2.0],Medium, RADIOVAR,"PRICE SENSITIVITY|Enter the sensitivity of sales \ to price",80,36,14,0,,[1.0],Low, Here the user can choose between the values 3,2 or 1 using the names High, Medium and Low.

RECTANGLE - pos jst


Draws a rectangle from x,y to x+width, y+height. Only the color portion of justification is used. RECTANGLE,"",60,30,35,55,

RUNNAME - txt pos jst


Displays the name of the run at the specified location. RUNNAME,"*1",72,45,0,0,L This should be used with txt set to the wildcard runs *1, *2, and so on and is useful for labeling scenarios.

39

SETWB - com scr


Indicates a command to be invoked whenever a new variable is selected into the workbench. This allows feedback from double clicks on a variable to the new condition - enabling very quick causal tracing. A generic causal tracing screen is: :SCREEN CAUSE TEXTONLY,"Causal tracing -",0,2,50,0,R WBVAR,"",50,2,0,0,L TOOL,"TR1",2,6,96,42,,,WORKBENCH>CAUSES TREE BUTTON,"T - Trace on highlight",\ 5,50,0,0,L,Tt,SPECIAL>SECONDCLICK|TR1, BUTTON,"S - Select a new variable to trace"\ ,5,70,0,0,L,Ss,SPECIAL>VARSELECT|New variable for tracing SETWB,"",0,0,0,0,,,,CAUSE The last command causes the screen to be refreshed with the new workbench variable each time a new variable is selected into the workbench.

SHOWCOMPANY pos jst


Displays the name of the company that Vensim is registered to. It is intended primarily for the opening screen in packaged applications. See SHOWUSER.

SHOWDATEVAR txt pos jst acc


Displays the value of a variable in date format. txt contains the name of the variable to display. acc specifies the conversion units, and the 0 value. The conversion units must be Y, M, W or D for year, month, week and day respectively. The 0 value is specified as a date following this. For example SHOWDATEVAR,"TIME",10,10,10,0,,M1/1/2020 would output time as date where time is in months and Time 0 is January 1, 2020. If you leave out a start date the 0 value is assumed to be 1/1/1900. If you leave out conversion units the dates are converted as yearly. Dates can range from 1/1/100 to 1/1/32000. NOTE Dates do not recognize leap years and for this reason may be inaccurate when converted to days or weeks.

SHOWEDATEVAR txt pos jst acc


Is the same as SHOWDATEVAR except that the output is in the order Day/Month/Year.

SHOWUSER pos jst


Displays the name of the user that Vensim is registered to. It is intended primarily for the opening screen in packaged applications. For example: TEXTONLY,"Registered to -",50,90,0,0,R||14 SHOWUSER,"",50,90,0,0,L||10 SHOWCOMPANY,"",50,95,0,0,L||10

SHOWVAR - txt pos jst


Displays the value of a model variable. txt contains the variable name to be displayed. If the variable specified uses Subscript Ranges the first selected element in the range will be used. The name can also be followed by special delimiters as described in Chapter 14 of the Reference Manual. In brief those delimiters are:

40

@time - specifies the time at which the value is to be taken. Can have values SPECIAL, START, END or a number. If not specified this is SPECIAL. #time_base - names a Time Base to be used with the associated time. (It only makes sense to set #time_base if @time is used with a number). If not specified the Time Base currently selected in the Globals>Time Axis box is used. &dataset - names the dataset to be used. *1 name the first loaded dataset, *2 the second and so on. If not specified the first loaded dataset is assumed. %-3.3g etc. - specifies the format for the output number using C language formatting rules. If not specified the number is output in Vensim's pretty number format. ?value=label?value=label... - specifies that for the stated special values a label string is to be substituted. This is especially useful for switch variables. You can have as many ? labels as you want, but they must be contiguous. (The COLORCIRCLE and COLORRECT control interpret the labels as Red Green Blue value specifications).

These conventions are the same as those used in custom graphs and reports to determine the appropriate dataset and time. If just the variable name is used, the value at special time from the first loaded run will be used. For Gaming interfaces the use of just a variable name will give you that value at the current position in the game. SHOWVAR,"SwitchPSCSensitivit?0=Low?1=Medium?2=High",25,13,0,0,L Note that for String Variables SHOWVAR will show the string value of the variable. This can be useful in making labels.

SKETCH - txt pos jst acc com


Displays a view at the stated position. txt is used to name the view for printing or exporting. com determines which view to display with 1 for the first view, 2 for the second and so on. The names of the views (as shown in the sketch View menu) are not used here. Sketches are displayed with no borders. If you want to see a border create a RECTANGLE or use a LINE control slightly bigger than the sketch. acc should contain the scaling percentage to be used in displaying the sketch. If acc is empty the sketch is shown at 100%. NOTE Use a zoom value of 5 to fit the sketch to the screen. jst should contain S if you want scroll bars enabled, or B if you want the sketch to appear as background (this allows you to place other controls on top of the sketch). By default scroll bars are not shown on sketches displayed in Venapps. SKETCH,"SK1",0,0,100,80,,5,6, This displays the sixth view with no scroll bars and zoomed so that it will fit in the allocated area. SKETCH,"SK1",0,0,100,100,B,75,6, This displays the sixth View as background at 75%. You can place as many sketches on a screen as you want. You can place other controls on top of sketches, but controls that do not create a separate window (SHOWVAR, GRAPHVAR and so on) will not be visible. If you want to place a control on top of a sketch, the control should appear before the sketch in the screen definition. If you want to make all controls visible, use the sketch as a background sketch. You can only have one background sketch, and it will always start in the upper left hand corner regardless of the x,y settings.

41

SLIDEVAR - txt pos jst acc


SLIDEVAR allows the user to choose a value (within a range) by dragging a slider. txt contains the name of the Constant or Game Input for gaming. A | separates the name from prompt information. If the justification field contains a V the slider is displayed Vertically. If the justification is empty or contains an H the slider is displayed horizontally. The minimum and maximum value for the variable are specified in the accelerator/range field. SLIDEVAR,"low cost housing prog coeff",24,40,25,9,H,[0|.2] Putting a percent sign % at the beginning of the range will cause Vensim to use scientific notation. You can specify a sensitivity for SLIDEVAR. This is the minimum increment in value that will be realized when the user drags the slider. Enter this as the third argument to acc as in: SLIDEVAR,"low cost housing prog coeff",24,40,25,9,H,[0|.2|.01] Here the slider would change values only by .01 increments (i.e. it could take on only 21 value). When the SLIDEVAR is configured in this manner the user can still type in any number. You can also place labels on SLIDEVARs. To do this you should precede the range information with the letter L (upper or lower case both work). If you just have the L Vensim will create scales based on the range. You can replace these labels by custom labels if you follow the L by a vertical bar | as in: SLIDEVAR,"Final Time",24,40,35,9,H,%L|Soon|Late|[2140|2200|.5] will result in:

It is also possible to specify a broader range for the slider than the Constant or Game variable can be changed. This is done by following the min, max and increment with a slider min and slider as in: SLIDEVAR,"Final Time",24,40,35,9,H,%L[2140|2200|.5|2100|2200]

Setting different bounds on the variable and slider can be useful when you have a number of sliders you would like to keep on the same scale. NOTE The fonts for the editable number and the labels are set separately. The font for the labels should follow the range information while the font for the editable text is in the justification field. Thus the control SLIDEVAR,"Final Time",24,40,35,9,H||14|B,%L[2140|2200|.5|2100|2200]||6

SLIDEVARTIE txt
The SLIDEVARTIE control is used to connect a number of SLIDEVAR controls, forcing the sum of the value of the SLIDEVAR to add to a number. This is often useful if you want slidevars to be fractions of a number, e.g., fractions that sum to one. Only txt is significant. It must take the form count=x,search order1,search order2 ..., search order count

42

Where count is the number of SLIDEVAR controls that are being tied together. Vensim will search for the last count SLIDEVAR controls that precede the SLIDEVARTIE control. These controls do not have to be one after another, though this is the easiest way to use them. x is the number the different SLIDEVARS have to sum to. search order is used to determine the order in which the other SLIDEVAR controls will be adjusted in order to add to x. The search order begins by specifying the SLIDEVAR control that is being moved, then a greater than > and then the other SLIDEVAR controls that will move in order to keep the sum at one. The search order specification uses the greater than > to indicate that the SLIDEVARs should be adjusted sequentially, and a vertical bar to indicate that they should be adjusted in parallel. SLIDEVARs will be adjusted until they hit their own minimums or maximums. Once this happens the later SLIDEVARs in the sequence will be adjusted. When no more adjustments can be made the SLIDEVAR being adjusted will no longer move. SLIDEVAR adjustments can be grouped is appropriate. For example 1>2|3>4|5 would first adjust 2 and 3 when one is being moved and if both of these hit a bound would then adjust 4 and 5. The numbers always refer to the SLIDEVARs being tied together in the order they appear in the source file. A search order can be empty (as in 1,) indicating that the SLIDEVAR in question will only act as a residual. Every SLIDEVAR being tied together must have a search order specified. Consider the example: SLIDEVAR,"FRACTION IMMUNE",60,25,20,8,H,l[0.0|.4|0.01|0|1] SLIDEVAR,"FRACTION INFECTED",60,35,20,8,H,l[.01|.5|0.01|0|1] SLIDEVAR,"FRACTION UNAFFECTED",60,45,20,8,H,l[.4|1.0|0.01|0|1] SLIDEVARTIE,"3=1.0,1>2|3,2>3|1,3>1|2",0,0,0,0 This forces the 3 preceding SLIDEVARs to add to 1.0, and causes the two other SLIDEVARs to adjust in parallel when a SLIDEVAR is moved. Changing the SLIDEVARTIE control to SLIDEVARTIE,"3=1.0,1>2>3,2>3>1,3>1>2",0,0,0,0 Moves first the immediately following SLIDEVAR and then the remaining SLIDEVARs

SWITCHVAR - txt pos acc com


SWITCHVAR allows the user to toggle a switch on or off. txt contains the name of the Constant or Game Input for gaming. A | separates the name from prompt information. acc contains the off/on values for the switch (by default off is 0 and on 1). com appears on the screen. SWITCHVAR,"PREREQ REQ[TASK1,TASK2]",47,20,15,0,L,,Task 2 If the variable name you specify is not in the model SWITCHVAR will disable the check box and fill it with gray.

TEXTMENU - txt pos jst acc com scr


Displays a text menu that can be highlighted and selected. When the menu item is invoked, the command is executed and new screen shifted to. TEXTMENU,"Exit - return to analysis",5,75,0,0,L,EeXx,,ANALYZE

TEXTONLY - txt pos jst


Displays text on the screen in the stated position TEXTONLY,"Questions? Call 123-4567",0,82,100,0,C||6||0-0-255|,

TIMER txt pos jst acc com scr


Creates a countdown timer and displays it in the specified location and font. A Timer is used to wait a specific time before taking an action, such as closing a screen or putting up a message. txt names the

43

Timer. You can have as many different timers as you like, and all are referred to by name. acc contains the number of seconds the Timer should run for and the frequency with which the timer should tick. For example TEXTONLY,"Time Remaining",70,40,0,0,R|Arial|14 TIMER,"T1",66,36,20,10,C|Arial|24|B|0-0-0,60|1,SPECIAL>MESSAGE|Time to go! This would start a timer at 1 minute (60 seconds) and it would count down in 1 second intervals. The time will be displayed in the form Minutes:Seconds. It is necessary to specify a width and height that is at least as large as the largest displayed time. If you supply a 0 width or height the timer display will not change. Timers can also be created and managed with the TIMER commands discussed in Chapter 4. If you leave any of acc, com or scr blank and there is already a timer with the same name that timer will be used starting at its current time. This allows you to leave and reenter a screen without losing the Timer settings.

TOOL - txt pos com


Invokes an analysis tool and places the tool output at the specified position. txt contains a name for the tool output for printing purposes. com contains one of WORKBENCH>toolname (where toolname is the name of the analysis toolset tool), CUSTOM>toolname (where toolname is the name the custom tool) or ERROR>toolname (where toolname is arbitrary). TOOL,"SP1",0,60,100,40,,,CUSTOM>COMM1 ERROR is used to control the location of an error window that is expected to be generated as a consequence of simulation or optimization. The toolname you use after ERROR is arbitrary, but must not be left blank (only CANCEL can be used in isolation).

WBVAR - pos jst


Displays the name of the currently selected workbench variable. WBVAR,"",50,2,0,0,L WBVAR can be also used to display the first selected subscript using the Subscript Range name in its text field. This is useful if you want to use MODVAR with Subscript Range names. WBVAR,"SUB",10,10,0,0,L, Where SUB is the name of a Subscript Range.

WIPTOOL - txt pos com


Same as tool except it sets up a work in progress tool for display during simulation. This control must precede the command invoking simulation. You can put up to eight work in progress graphs on a screen. WIPTOOL,"GR1",0,0,100,100,,,CUSTOM>WIP

44

Commands Descriptions

Overview
Commands are actions that you can ask Vensim to take. Commands are used in Venapps, Command files and through the Vensim DLL. They can be given in response to user choices, or as part of setting things up. Each command is entered as a class, followed by the specific command and options in the form class>command|option1|option2.... Commands can be combined using an ampersand &. The classes are: BRANCH>BranchName will cause a Venapp to branch logical control to another location in the same screen. BranchName is defined using the BRANCH control. CANCEL is used to prevent the reading of inputs from the current screen (CANCEL is a class with no specific commands). CUSTOM>GraphName will create a custom graph or report. GraphName is the name of the custom graph or report. ERROR>placeholder places error output into a window - normally used in a TOOL control. EXPORT>GraphLab allows you to copy tool output or a sketch that is on the screen to the clipboard. Tool output is labeled when it is put up on the screen, and exporting uses this name. FILE>command allows you to manipulate files. The FILE commands are COPY, CREATE, DECRYPT, DELETE, ENCRYPT, EXISTS, MDL2VMF, RENAME, VCD2VCF, VGD2VGF and VMF2MDL. GAME>command allows you to control game activity. The GAME commands are BACKUP, ENDGAME, GAMEINTERVAL, GAMEON, READGIN, RELOAD and WRITEGIN. IFTHENELSE is used to initiate a logical branching sequence. It appears as a class with no specific command and must be followed by three more commands separated by &. LOG>command is used to log user actions. The LOG commands are CREATE, MESSAGE and TIMESTAMP. MENU>command is used for commands that could be executed from the main Vensim menu were it visible. The MENU commands are DAT2VDF, EXIT, GAME, LOAD_RUN, REDO_GRAPHS, RUN, RUN1, RUN_OPTIMIZE, RUN_SENSITIVITY, TAB2VDF, VDF2DAT, VDF2TAB, VDF2WK1, VDF2XLS, WK12VDF and XLS2VDF. PRINT>GraphLab allows you to print tool output or a sketch that is on the screen. Tool output is labeled when it is put up on the screen, and printing uses this name. You can also use this command to print the current screen. SETTING>command allows you to control setting in Vensim that would normally be accessible from the Options dialog. The SETTING commands are EURONUMBER, EXPORTSIZE, EXTERNALFUNCTION, HOVERCOM, PRINTOPTQUERY, SHOWINITIAL, SHOWLOOKUP, SHOWMACRO, SHOWWARNING and SIZEINCHES. SIMULATE>command allows you to control a simulation much like you could from the Simulation Control dialog. The SIMULATE commands are 1TABCHG, ADDCIN, ADDDATA, BASED, CHGFILE, DATA, GETCNSTCHG, GETTABCHG, MINMEN, OPTPARM, PAYOFF, READCIN, READRUNCHG, RESUME, RUNNAME, SAVELIST,

45

SENSSAVELIST, SENSITIVITY, SETVAL and WRITECIN. SPECIAL>command allows you to change things like those you could modify from the Control Panel. The SPECIAL commands are ALIASSCREEN, ASKYESNO, BUTTONFOCUS, CLEARRUNS, EXIT1, EXTERNAL, LOADAPPINT, LOADDLL, LOADMODEL, LOADRUN, LOADTOOLSET, MESSAGE, NOINTERACTION, READCUSTOM, READINI, REFRESH, RESETINPUT, SECONDCLICK, SETTITLE, SETWBITEM, STOP, STOPSIM, SUBSCRIPTS, VARSELECT and WINHELP. SKETCH> command allows you to manipulate a visible sketch. The SKETCH commands are CHOOSEVIEW, NEXTVIEW, PREVVIEW and ZOOM. TEST>condition is used to test input constants and computed model variables to be sure they meet specified conditions. This is normally used with IFTHENELSE. TIMEAXIS>command allows you to control the time axis used in graphs and tables. The TIMEAXIS commands are RESET, SPECIALTIME, STARTTIME and STOPTIME. WORKBENCH>ToolName allow you to put up workbench tool output.

NOTE CANCEL and IFTHENELSE always appear in isolation (no > or command name is used). The command classes and individual commands are discussed in more detail below. The are organized alphabetically first by class, and then by command.

General Issues
If a command takes options, the options follow the vertical bar. Options include prompt strings, numbers and other values, but cannot include imbedded commas unless the entire command field is enclosed in double quotes " ". You can put multiple commands together using an ampersand & between the commands. If a command fails, the commands following it are not invoked. This is especially useful for querying whether the user wants to end a session. If you combine commands and want to enclose a command in quotes, the quotes must surround all of the commands. Thus BUTTON,"Quit",25,95,0,0,C,Qq,"SPECIAL>ASKYESNO|Are you ready, \ and willing to stop&MENU>EXIT" is correct, while BUTTON,"Quit",25,95,0,0,C,Qq,"SPECIAL>ASKYESNO|Are you ready, \ and willing to stop"&MENU>EXIT will not execute the exit command.

File Names
For the commands that take file names, you can also specify a question mark ? to indicate that the user should be presented with a file selection dialog. Thus, for example, the command SIMULATE>RUNNAME|?Choose a new name for the simulation will result in the user seeing (under Windows 95) :

46

You can also use an exclamation mark ! to indicate that the current run name should be used. This is handy if you want to redo the current run as in: SIMULATE>READRUNCHG|! or even to copy the current run name to a different file as in: FILE>COPY|!|?Location to store archive of current run

BRANCH
Branches execution to another location in the current screen. The command must name a BRANCH control on the current screen (or the BRANCH command fails and returns 0). When a BRANCH command is executed, both the command and shift to screen at the BRANCH control branched to are used. BRANCH commands are normally used in conjunction with the IFTHENELSE command to test something and determine which way to proceed. :SCREEN AFTERSIM COMMAND,"",0,0,0,0,,,IFTHENELSE&TEST>Status Flag=0&BRANCH>BR1&BRANCH>BR1A BRANCH,"BR1",0,0,0,0,,,,DECISION BRANCH,"BR1A",0,0,0,0,,,IFTHENELSE&TEST>Status Flag=1&BRANCH>BR2&BRANCH>BR2A BRANCH,"BR2",0,0,0,0,,,SPECIAL>MESSAGE|0|Sorry|You are doing poorly,\ DECISION BRANCH,"BR2A",0,0,0,0,,,IFTHENELSE&TEST>Status Flag=2&BRANCH>BR3&BRANCH>BR3A BRANCH,"BR3",0,0,0,0,,,SPECIAL>MESSAGE|0|Congratulations|You are doing well,\ DECISION BRANCH,"BR3A",0,0,0,0,,,SPECIAL>MESSAGE|0|Wow|You are off the scale,DECISION In this case a different message is put up and the same screen is then shifted to. It would also be possible to shift to a different screen.

47

You can also use branch commands to simply supplement an existing command. For example, suppose that you wished to give the user three choices, but execute a common set of commands after the choices have been made. The following screen uses BRANCH to do this: :SCREEN DEFINE TEXTONLY,"New Scenario Setup",0,5,100,0,C||18|B|255-0-0 BUTTON,"Start a new scenario",25,15,50,0,L,Ss,\ SIMULATE>READRUNCHG&\ SIMULATE>RUNNAME|?Name for the new scenario&BRANCH>SETUP, BUTTON,"Build off of an existing scenario",25,25,50,0,L,Ss,\ SIMULATE>READRUNCHG|?Select scenario for basis&\ SIMULATE>RUNNAME|?Name for the new scenario&BRANCH>SETUP, BUTTON,"Modify and rerun an existing scenario",25,35,50,0,,Mm,\ SIMULATE>RUNNAME|?Select the scenario to work with|E&\ SIMULATE>READRUNCHG|!&BRANCH>SETUP BUTTON,"Exit back to main menu (cancel scenario \ creation)",20,68,60,0,L,EeXx,,MAIN BRANCH,"SETUP",0,0,0,0,,,SIMULATE>SETVAL|FINAL TIME=1&MENU>RUN|O&\ SIMULATE>READRUNCHG|!&SIMULATE>SETVAL|FINAL TIME=100,RUN In this case you get three choices, but regardless of what you choose, Vensim makes a short simulation that guarantees the existence of the run requested. Notice the READRUNCHG command after the simulate command. This is important because it guarantees that whatever conditions pertained in the run are restored for further modification. Finally, FINAL TIME is set to its normal value and the screen RUN is shifted to.

CANCEL
Cancel is used as a signal that the current screen should not be read. Normally, before any command is executed, Vensim will attempt to read any inputs the user might have made and issue an error message if unable to do so. By using the CANCEL command, this action will be prevented, allowing the user to continue without incorporating the changes made in the screen. For example: :SCREEN TEST TEXTONLY,"Final Time",1,16,0,0,L MODVAR,"FINAL TIME",20,16,10,0,L,[80|100] BUTTON,"Simulate",25,45,0,0,C,,MENU>RUN,RESULT BUTTON,"Cancel",75,45,0,0,C,,CANCEL,MAIN In this case entering a bad number in the MODVAR field will prevent the "Simulate" button from working, but the "Cancel" button will simply ignore the input and return to MAIN.

CUSTOM
Displays a custom report of graph. To work properly, the correct custom graph definitions must be loaded. See the SPECIAL>READCUSTOM command. The CUSTOM class is followed by the name of a custom tool. If part of a TOOL or WIPTOOL control this places the custom graph or report at the desired location, otherwise a new child window is created with the appearance of a Vensim tool output window. If part of a BUTTON or TEXTMENU control the custom graph name may be followed by a | and either the name of an existing graph output or an exclamation mark !. Using the name of an existing output the name that is specified in the name field of the TOOL or WIPTOOL control will cause that output to be replaced. Using an exclamation mark will cause the previous invocation of the same tool or custom graph to be replaced. This latter is useful in preventing screen clutter with multiple

48

copies of the same graph. Clicking twice on the same graph button will only cause a single graph to appear. The following allows you to choose among a number of different graphs on a single screen: :SCREEN OUTPUT COMMAND,"",0,0,0,0,,,SPECIAL>SETWBITEM|Morale RECTANGLE,"",67,1,32,91,L 7 TEXTONLY,"Important Graphs",73,4,0,0,l TEXTMENU,"1. Morale",68,11,0,0,L,, SPECIAL>SETWBITEM|Morale&CUSTOM>MORALE|GR1&WORKBENCH>TABLE|TAB TEXTMENU,"2. Overtime",68,18,0,0,L,,\ SPECIAL>SETWBITEM|Overtime&CUSTOM>OVERTIME|GR1&WORKBENCH>TABLE|TAB TEXTMENU,"3. Accidents",68,25,0,0,L,,\ SPECIAL>SETWBITEM|accidents&CUSTOM>ACCIDENT|GR1&WORKBENCH>TABLE TOOL,"GR1",1,1,65,62,,,CUSTOM>MORALE TOOL,"TAB",1,64,65,28,C 2,,WORKBENCH>TABLE BUTTON,"Return",12,93,30,5,L 2,,,SIMUL BUTTON,"Analysis",54,93,30,5,L 2,,,ANALYZE The screen first displays the graph for morale, and then allows you to switch between different graphs.

Letting the User Select a Graph


If you use a ? followed by a prompt instead of a graph name, the complete list of custom graphs and reports in the current graph set will be shown to the user. The user can then select one of these for display. For example CUSTOM>?Choose a graph to display|GR1 Would allow the user to choose a graph and have the chosen graph replace the graph GR1.

ERROR
This is used to control error output during simulation, and especially optimization. All error output is sent to a window of the specified size, at the specified location. The ERROR class must be followed by a > and an arbitrary command name. The ERROR command can only be used as part of a TOOL control. :SCREEN OPTIMIZING TEXTONLY,"Optimization in progress",0,25,100,0,C||18|B| COMMAND,"",0,0,0,0,,,SIMULATE>OPTIMIZE|1 TOOL,"SP1",0,50,100,50,,,ERROR>COMM7 COMMAND,"",0,0,0,0,,,MENU>RUN|O, COMMAND,"",0,0,0,0,,,SIMULATE>OPTIMIZE|0 TEXTONLY,"Press any key to return to main menu",0,30,100,0,C ANYKEY,"",0,0,0,0,0,,,MAIN

EXPORT
Export the tool output named in the command. For graphical output and sketches, this will go to the clipboard as a Windows Metafile (PICT file on the Mac). For text output, it will be sent to the clipboard as text. The tool output name must match the name field of the TOOL or WIPTOOL control.

49

:SCREEN TREE TOOL,"TR1",2,6,96,42,,,WORKBENCH>CAUSES TREE BUTTON,"Export the Tree",50,60,0,0,C,,EXPORT>TR1 You can have multiple output windows open on a screen and export them by name. If the name does not match an open graph, report, or sketch, nothing will be done. You can not use the EXPORT command to export graphs created using MENU or TEXTMENU commands. The graphs can only be exported if the user clicks on the Export button on the graphics titlebar. If you use an exclamation point ! instead of a graph label with the export command a bitmap image of the screen will be copied into the clipboard. BUTTON,"Snapshop",50,60,0,0,C,,EXPORT>!

FILE
The file commands allow you to manipulate files. Several of the File commands are only accessible from command scripts and these are noted.

FILE>COPY|oldname|newname
Copies the file from oldname to newname. This command will fail if you attempt to copy a file onto itself, ask to copy from a file that does not exist or specify an invalid file name. You must include the full name and extension when you specify the file names.

FILE>CREATE|filename
Creates the empty file named. This command is useful for creating marker files after an action has occurred.

FILE>DECRYPT|filename
This command is only available from command files and will only work if you have purchased the Vensim Application Distribution License. It will take a binary Vensim file that has been encrypted for redistribution and decrypt it.

FILE>DELETE|filename
This command deletes the named file.

FILE>ENCRYPT|filename
This command is only available from command files and will only work if you have purchased the Vensim Application Distribution License. It will take a binary Vensim file and encrypt it for redistribution.

FILE>EXISTS|filename
Tests to see whether or not a file exists. Returns 0 if it does not exist and 1 if it does. Useful for testing to see if an external operation has been completed.

FILE>MDL2VMF|filename
This command only works with command files. It converts a text format model to a binary format model. The .vmf (source) and .mdl (target)

50

FILE>RENAME|oldname|newname
Renames a file. This command will fail if the old name does not exist or the new name does exist or is invalid.

FILE>VCD2VCF|filename
This command only works with command files. It converts a file with extension .vcd to a binary form of the same information having extension .vcf. filename must be the filename only with no extension and no period. The .vcd and .vcf endings will be added automatically.

FILE>VGD2VGF|filename
This command only works with command files. It converts a file with extension .vgd to a binary form of the same information having extension .vgf. filename must be the filename only with no extension and no period. The .vgd and .vgf endings will be added automatically

FILE>VMF2MDL|filename
This command only works with command files. It converts a binary format model to a text format model. The .vmf (source) and .mdl (target).

GAME
The GAME class controls allow you to control game execution.

GAME>BACKUP|totime
Backs up a game to the time specified. If totime is not specified the game is backed up by whatever GAMEINTERVAL is set at. Note that it is not possible to back up a game for a model that contains any of the pure delay functions DELAY FIXED, MATERIAL or INFORMATION. Note that after executing a GAME>BACKUP it is probably best to force a reentry into the current screen so that any work in progress graphs will refresh themselves properly.

GAME>ENDGAME
Stops a game that is in progress or complete. This call will stop gaming activity and allow the user to exit or do post-game analysis on the output of the game.

GAME>GAMEINTERVAL|value
Sets the interval that will be covered by each GAME>GAMEON command. You can set the game interval at any time before or during a game. You can also set the game interval to a model constant before a game, or to any model variable during a game. Just use the name of the model variable in place of a value.

GAME>GAMEON
Continues forward in a game by the amount set by the GAME>GAMEINTERVAL command. This command will fail if there is not currently a game in progress.

GAME>READGIN|filename
Reads in a set of values for Game variables during a game. filename should be a fully specified file name including extension. This command is only valid during a game (after the SIMULATE>GAME command has been used). The format for a Gaming Input file is exactly the same as that for a .cin file.

51

GAME>READVDF|filename|time
Reads in the gaming decisions contained in another simulation or gaming run (.vdf). The file must be from the same model that is currently being used. You can, optionally, specify a time at which to read the decisions. If no time is specified the decisions for the time corresponding to the current game time will be read. You can use a series of GAME>READVDF commands to reproduce the decisions made in another game. This is one technique for backing up a game even with models that preclude backing up.

GAME>RELOAD
Specifies that when a game is started it will be reloaded from a game that has previously been created and gaming will continue from the end of that game. The GAME>RELOAD command must precede the MENU>GAME command. A common format would be: BUTTON,"Continue with old game",50,50,0,0,C,,\ SIMULATE>RUNNAME|?Name of game to continue|E&\ GAME>RELOAD&MENU>GAME,GAMEINP

GAME>WRITEGIN|filename|savelist
Writes all Game variables to a gaming input file whether they have changed in value or not. This is to be contrasted with SIMULATE>WRITECIN which only writes Constants and Lookups that have been changed. savelist is optional. If specified only those variables listed in savelist will be written. The format is that same as for other save lists see Chapter 10 of the reference manual.

IFTHENELSE
IFTHENELSE should appear by itself. It signals that the next three commands are for a logical branching sequence. The first command following IFTHENELSE is executed. If it returns a nonzero value (TRUE) then the second command following is executed, otherwise the third command is executed. IFTHENELSE is normally followed by a TEST command and then a BRANCH command as in: BUTTON,"Simulate",90,50,0,0,C,,IFTHENELSE&TEST>WSUM=100&BRANCH>OK&\ STOP|Weights must sum to 100 BRANCH,"OK",0,0,0,0,,,,RUN IFTHENELSE does not need to be the first command, but you will get an error message if IFTHENELSE is followed by any number of commands other than 3. If there is a shift to screen named on a line with ITTHENELSE that screen will be shifted to unless a BRANCH command is executed.

LOG
The LOG commands are used to record information about user actions during a Venapp session. They are intended aid in the analysis of the actions players make while using a model.

LOG>CREATE|filename
Creates an empty log file, deleting the old file if it exists.

LOG>MESSAGE|filename|message
Adds the message text (any text you wish) to the log. The existing contents of the log are appended to. If the log file does not exist it is created.

52

LOG>TIMESTAMP|filename
Places a time stamp into the log file. Placing time stamps around log messages allows you to determine when actions have happened.

MENU
The menu commands have essentially the same effect as selecting a command from the Vensim workbench menu. Not all menu commands are available, and some slight variations on existing commands exist.

MENU>DAT2VDF|datafile|vdffile
Converts .dat format date in datafile to a .vdf format file vdffile. If you leave off vdffile the data file name with the extension .vdf will be used and the user will be queried about overwriting this file if it exists.

MENU>EXIT
This will close Venapp and return you to Vensim proper. If the Venapp was started directly from windows (by giving the name of a .vcd file to launch Vensim) Vensim will close entirely. This mimics the behavior of a Vensim Application Runtime engine.

MENU>GAME
Initiates gaming. This is similar to the MENU>RUN command except that it returns after opening the output file for the game without processing the entire simulation. Model variables at the initial time for the simulation are accessible in this output file.

MENU>LOAD_RUN
This command brings up a popup version of the Datasets tab of the Control Panel. The user can use it to load, unload and delete datasets.

MENU>REDO_GRAPHS
This command causes all open custom graphs, tables and reports to be recreated. This is useful after a simulation game has progressed and you would like to update the information displayed to include the most recent period.

MENU>RUN|o
Run the model using the current simulation setup. Load the run last. If option O (the letter oh) is specified any existing run with the same name will be overwritten, otherwise the user will be prompted to ask if they want to overwrite the existing file.

MENU>RUN1|o
Same as RUN except the run is loaded as the first run instead of the last run. Use the option O to overwrite existing files without query.

MENU>RUN_OPTIMIZE|o
This command runs the optimizer on the model using the current simulation setup. to overwrite existing files without query. Use the option O

53

MENU>RUN_SENSITIVITY|o
This command runs sensitivity simulations on the model using the current simulation setup. option O to overwrite existing files without query. Use the

MENU>SENS2TAB|vdffile|tabfile|*![#
Converts a sensitivity simulation file to a tab delimited file. This command will fail silently if vdffile is not the result of a sensitivity simulation. A number of options can follow the name of the output file.

* ! # [

causes the simulation index (or time if # is specified) to run down instead of across. causes only the values at final time to be exported. causes the variables names to be modified by simulation number instead of time (only applies when ! is not specified). causes the variable names to be modified using a subscript instead of a prefix (only applies when ! is not specified).

MENU>SYNTHESIM|o Starts SyntheSim mode. Use O to overwrite the existing run without prompting. In SyntheSim mode all changes to model values will trigger simulations and Venapp sliders will simulate as they are moved, saving the results when they are released. If you display a sketch in SyntheSim mode the behavior graphs for each variable will be displayed, but the sliders will not be created. To leave SyntheSim mode use SPECIAL>STOPSIM.MENU>TAB2VDF|tabfile|outfile|form
Converts the Tab delimited data contained in tabfile to the .vdf format file outfile. If outfile is omitted or left blank then tabfile is given extension .vdf during the conversion. form is the name of a form file controlling the conversion process. It is optional. See Chapter 9 of the Reference Manual for more information on form files.

MENU>VDF2DAT|vdffile|datfile|savelist|+
Converts the Vensim dataset vddffile to a .dat format file datfile. If datfile is left off or empty the extension .dat is given to vdffile. savelist is a list of variables that should be extracted from the dataset (see Chapter 9 of the Reference manual). If savelist is left of or empty then the values for all variables are converted. Adding the final option + causes the data to be appended to the .dat file instead of overwriting this file.

MENU>VDF2TAB|vdffile|tabfile|savelist|+[*!|frequency|start|end
This is the same as MENU>VDF2DAT except it converts the file to a Tab delimited file. After supplying the savelist there are a number of options that can be used to control output. These should all be together and not separated by vertical bars |. * causes time to run down instead of across. ! causes the Time axis to be suppressed from the output. [ causes subscript names to appear in separate column or row.

frequency, if specified, causes the data to be saved at that frequency instead of every SAVEPER. You can also use start and end if you do not want to get values from the entire range contained in vdffile.

54

If you use the command MENU>VDF2TAB with no options a dialog will appear just as for the Vensim menu command Model>Export Dataset command.

MENU>VDF2WK1|vdffile|tabfile|savelist|+[*!number
Same as VDF2TAB but converts to a Lotus 123 format file.

MENU>VDF2XLS|vdffile|tabfile|savelist|+[*!number
Same as VDF2TAB but converts to an Excel version 4.0 format file.

MENU>WK12VDF|tabfile|outfile|form
Same as TAB2VDF except it takes in a Lotus 123 format file.

MENU>XLS2VDF|tabfile|outfile|form
Same as TAB2VDF except it takes in a Microsoft Excel format file.

PRINT
Print the sketch or tool window named in the command. The name or a tool window appears in the txt position of the control definition for the tool. The print command uses whatever print options have been set inside of Vensim. See also EXPORT. You can use PRINT>! to print the current screen. Because this prints as a bitmap quality is lower than it would be for graphs but it does capture the current settings in all controls.

SETTING
The setting commands are used to control the Vensim settings essentially a subset of those available through the Global Options dialog. If you are running the Venapp from within Vensim DSS the changes you make using SETTING commands will no longer apply once you close the Venapp (that is, the changes are temporary and apply only within the Venapp). If you use the SETTING commands via DDE the changes are persistent.

SETTING>EURONUMBER|n
Determines whether the Venapp uses European format number (a period separating thousands fields and a comma to denote the decimal) versus American format numbers (a comma separating thousands fields and a period to denote the decimal). This setting changes the behavior of both input and output controls, but does not change the expected format for changes files. Changes file contents must appear in standard scientific notation only (1.45E6 and so on).

SETTING>EXPORTSIZE|n
Determines how graphs are sized for exporting. Set n to 0 to use the screen size, 1 to query the user and 2 to size to the desired size specified by the tool. This setting only has an effect on the EXPORT command.

Setting>EXTTERNALFUNCTION|dll name
Resets the external function library to the named DLL. It is good practice to include this command preceding the LOADMODEL command. If you are working with .vmf files it is acceptable to first load the model and then set the external functions. If you are working with .mdl files and changing the directory you may want to include a small model to first set the directory and then load the complete model as in:

55

COMMAND,"",0,0,,,,,"SPECIAL>LOADMODEL|empty.mdl", COMMAND,"",0,0,,,,,"SETTING>EXTERNALFUNCTION|myfunction.dll", COMMAND,"",0,0,,,,,"SPECIAL>LOADMODEL|mymodel.mdl",

SETTING>HOVERCOM
Determines whether or not comments will be displayed when the user lets the mouse stay over a variable on the sketch. For Vensim this option is on by default. However, for Venapps, the Vensim Application Runtime and the Vensim DLL this option is off by default. If you want to show comments on sketches you should set this at the beginning of your application.

SETTING>PRINTOPTQUERY|n
Determines whether or not the print options dialog appears when tool output is printed. Set n to 1 to have the dialog appear and 0 to not have it appear. Printing a sketch will always bring up the dialog.

SETTING>SHOWINITIAL|n
Determines whether or not initial connections are shown on sketches. Set n to 0 to hide initial causes and 1 to show them. NOTE the SHOWINITIAL command is obsolete and kept only for backward compatibility. You should set up your models to either show or not show initial causes and not use this command.

SETTING>SHOWLOOKUP|n
Determines whether or not Lookups are shown on sketches. Set n to 0 to hide Lookups and 1 to show them. NOTE the SHOWLOOKUP command is obsolete and kept only for backward compatibility. You should set up your models to either show or not show Lookups and not use this command.

SETTING>SHOWMACRO|n
Determines whether or not Macro variables will appear in the variable selection dialog and on Trees and Causes Strip graphs. Set n to 0 to hide all Macro variables and 1 to expand macro variable definitions.

SETTING>SHOWWARNING|n
Determines whether warnings will be displayed during simulations. Set n to 0 to suppress warnings and 1 to show them. In general it works beds to hide warnings in Venapps.

SETTING>SIZEINCHES|n
Determines whether displayed sizes are in inches or centimeters. Set n to 0 to size in centimeters and 1 to size in inches.

SIMULATE
The simulate class allows you to control simulation input control parameters, and also read results from other runs to start another simulation. It is important to note that the way simulation control is implemented .cin files named in the changes field of the simulation control dialog are typically ignored.

56

SIMULATE>1TABCHG|varname
Invoke the graphical Lookup Editor for varname. If you are using subscripted tables you may need to enclose the command in quotes.

SIMULATE>ADDCIN|cinfile
Read the .cin file cinfile and add the changes made there to current model changes Any simulation made will then be based on those changes. ADDCIN allows you to cascade a series of changes based on user choices. See also SIMULATE>READCIN.

SIMULATE>ADDDATA|vdffile
Add the .vdf file vdffile to the list of data files to be used in the simulation. This is a useful way of building up a list of files to be used as data sources. The SIMULATE>DATE command on the other hand replaces any existing list of files.

SIMULATE>BASED|oldrun
Change the based on run control parameter to oldrun. If oldrun is 0 or missing Based On is reset to empty. BASED is normally used in conjunction with the SIMULATE>RESUME command. SIMULATE>BASED will reset any changes to constants that might have been made using SIMULATE>READCIN, SIMULATE>SETVAL or SIMULATE>READRUNCHG.

SIMULATE>CHGFILE|cinfile
Sets the name of the change file to be used. This name is used only if no interactive changes are allowed, and you do not specify ADDCIN, READRUNCHG or READCIN. The occurrence of MODVAR, GETCNSTCHG and so on in any screen will cause the change file to be ignored. In general it is best to use either READCIN or SETVAL commands to directly control simulation.

SIMULATE>DATA|filelist
Set the data file(s) to be used in the simulation. filelist should be a comma delimited list of files. If you have more than one file the entire command must be surrounded by double quotes " ". If filelist is empty no data files will be used. This command is necessary if you are using exogenous inputs or optimizing against historical data.

SIMULATE>GETCNSTCHG|varname
Gets the constant change dialog available from the Simulation Control dialog. If varname is missing or empty the list of all constants in the model will be presented. If varname is a valid constant name the constant changes dialog will be brought up for all elements of that constant (if the constant is not subscripted there is only 1 element). This allows the user to change any of the Constants in the model. Note that if you use GETCNSTCHG on a screen with other value controls (e.g. MODVAR) the values you should follow the GETCNSTCHG command with a SPECIAL>RESETINPUT command to update the screen values.

SIMULATE>GETTABCHG|varname
Gets the Lookup Modification dialog that is available from the Simulation Control dialog. If varname is missing or empty, this lists all the Lookups in the model and allows the user to select one to change. If varname is a valid Lookup name, it lists the various subscript elements of varname.

57

SIMULATE>MINMEM|n
If n is nonzero then the simulation will be made minimizing memory usage, otherwise it will be made normally. Note that minimizing memory usage during simulation will significantly degrade the performance of graph and other data analysis tools.

SIMULATE>OPTPARM|optfile
Sets the name of the optimization parameter file to optfile. Only used in optimization.

SIMULATE>PAYOFF|payfile
Set the name of the payoff file. If payfile is 0 or missing, the payoff file is set to empty (no payoff computed). Resetting the payoff to empty after a simulation is good practice since payoff definitions are model specific and can cause errors during simulation if used with another model.

SIMULATE>POSTPROCESS|postfile
Set the name of the post processing command or database output file or files. If using multiple files separate them with commas , and be sure to put double quotes " around the command. If postfile is empty, the post processing file is set to empty (no post processing performed). Resetting the post processing to empty after a simulation is good practice since post processing operations are model specific and can cause errors during simulation if used with another model.

SIMULATE>READCIN|cinfile
Read the .cin file named in cinfile. Any simulation made will then be based on those changes. The READCIN command will reset any changes that might have been made to model Constants or Lookups before reading cinfile. If cinfile is missing or empty, the original model values for all Constants and Lookups will be restored.

SIMULATE>READRUNCHG|oldfile
Use an existing .vdf file to load in Constant and Lookup changes. Note that both READCIN and READRUNCHG add the changes in the named files to the base model they do not cumulate. If oldfile is empty the contents are restored to the values in the base model.

SIMULATE>RESUME|n
Set the resume switch for simulation. If n is 0 (zero) or missing the switch is turned off. The resume switch causes the model to resume simulation at the end of the Based On run. The RESUME command is normally used with the BASED command.

SIMULATE>RUNNAME|filename|mode
Set the name of the simulation run. If you are using a ? to get a File Selection Dialog, you can also add a second option after the prompt information. Use a mode of E to specify that you want the user to select an existing file so that the Save button will be relabeled Open. Use a mode of O to specify that the user should not be asked if they want to overwrite an existing file. If filename does not begin with ? you cannot specify a mode.

SIMULATE>SAVELIST|list
Sets the name of the saved variable list to be used in the simulation. This save list is used during normal simulations only. To set the save list used during sensitivity simulations, use SIMULATE>SENSSAVELIST. See Chapter 10 of the Reference Manual for more information on save lists.

58

SIMULATE>SENSITIVITY|sensfile
Set the sensitivity file to be used during a sensitivity simulation. Setting this file only has an effect when the MENU>RUN_SENSITIVITY command is called. In this case sensfile contains the sensitivity control information.

SIMULATE>SENSSAVELIST|list
Set the name of the saved variable list for sensitivity simulations. See also SIMULATE>SAVELIST and Chapter 10 for more information on save lists.

SIMULATE>SETVAL|var=val or var((x1,y1)...(xn,yn)) or var :IS: literal


Set the value of a Constant, Lookup String Variable or, in gaming mode, a Game Input. var must be a valid Constant, Lookup, String Variable or Game Input. For Constants and Game variables val can be either a number (3.5) or a valid model variable name. For Lookups there can only be numbers. Whatever appears for String Variables is simply taken as a literal express (you do not need to enclose it in single quotes '). NOTE You can only change Constants, Lookups and String Variables during a simulation setup. If you have executed the MENU>GAME command nothing will happen. NOTE You can only change Game Variables during a game. If you have not executed the MENU>GAME command nothing will happen. If you are setting Constants, you can only set them to other constants, but Vensim will not check this so be careful. If you are setting Game variables, you can set them to any valid model variables. If you use subscripted variables in the SETVAL command you will need to surround the command in double quotes " ". To change a Lookup using the SETVAL you must supply a sequence of x,y pairs in parentheses as in SIMULATE>SETVAL|mylookup((0,0),(1,1),(2,2),(5,5)) If you are using the SETVAL command to set a string variable do not include the surrounding single quotes. For example: SIMULATE>SETVAL|productname:IS:Metronone If you use the SETVAL command and have input controls on the screen you should also use the SPECIAL>RESETINPUT command or reenter the current screen.

SIMULATE>SPREADALIAS|?alias=filename.xls
Sets an alias for a filename used in any of the GET XLSor GET 123... functions. When the filename specified by ?alias is encountered the filename filename.xls will be substituted. The alias term must begin with a ?, and you can use just a ? (or a blank) for the empty alias reference. If filename is empty any alias that did exist will be removed (so that the user will be prompted for a filename when the model is run).

SIMULATE>WRITECIN|cinfile
Writes the model changes made so far to the file named in cinfile. This can be useful if you have two parallel models and want to transfer changes from one to the other, or if you want to record a user's input decisions.

SKETCH
The SKETCH commands allow you to manipulate a sketch that has been put up using a SKETCH control. For all the SKETCH commands, you must specify the name of the sketch as it appears in the txt field of the SKETCH control.

59

SKETCH>CHOOSEVIEW|sketchname|prompt
Brings up a list of the views defined in the model and allows the user to choose the view that they want to see. Prompt will appear in at the top of the selection dialog. The view currently displayed in sketchname will be replaced with the chosen view.

SKETCH>NEXTVIEW|sketchname
Displays the next view in sketchname. If the currently displayed view is the last one this command has no effect.

SKETCH>PREVVIEW|sketchname
Displays the previous view in sketchname. If the currently displayed view is the first one this command has no effect.

SKETCH>ZOOM|sketchname|percent
Zooms the sketch in sketchname to the specified percent. Enter a number between 10 and 500 %. If you use the special number 5% the sketch will be put into fit-to-screen mode. Use a ? followed by a prompt to have the user queried for a percentage to zoom to.

SPECIAL
The SPECIAL commands allow you to manipulate the Vensim environment in ways similar to what you could do from the Control Panel. There are also a number of SPECIAL commands that have no analog in the Vensim development environment.

SPECIAL|ALIASSCREEN|aliasname|screenname
Creates an alias that can be used in the shift to screen of a control. This is very useful for specifying a return screen that depends on the history of how the screen was arrived at. Consider for example the three screens: :SCREEN SCENARIO COMMAND,"",0,0,0,0,,,SPECIAL>ALIASSCREEN|SETUP|SCENARIO BUTTON,"Help",50,50,0,0,,,,HELP :SCREEN GAME COMMAND,"",0,0,0,0,,,SPECIAL>ALIASSCREEN|SETUP|HELP BUTTON,"Help",50,50,0,0,,,,HELP :SCREEN HELP BUTTON,"Return to Setup",50,50,0,0,,,,SETUP In this case pressing the "Return to Setup" button will return you to the screen you came from. You can use ALIASSCREEN as many times as you like. Each use of ALIASSCREEN with the same aliasname will simply replace the old value. If you specify a value for screenname that does not exist an error will be issued when you attempt to shift to aliasscreen.

SPECIAL>ASKYESNO|question
Puts up a dialog box with the question and a Yes and No button. If the user answers Yes the commands this command returns TRUE, which means that the command that follow will be executed. For example BUTTON,"Finish",25,45,0,0,C,,SPECIAL>ASKYESNO|Do you want to end the game?&\

60

GAME>ENDGAME

SPECIAL>BUTTONFOCUS|n
When n = 1 this causes buttons to take the focus in response to Tab keys. Normally only input controls will take the focus and buttons will need to be clicked on. When n is missing or 0 buttons will not take the focus (the default). The SPECIAL>BUTTONFOCUS|1 command will cause the Venapp to behave more like a standard Windows dialog box would. NOTE The BUTTONFOCUS command has no effect on the Macintosh.

SPECIAL>CLEARRUNS|n
n specifies after which run to clear, if blank all runs will be cleared. For example SPECIAL>CLEARRUNS|3 clears the fourth, fifth . . . runs. If three or fewer runs are loaded, then no action is taken. This is useful in assuring that not too many runs pile up.

SPECIAL>EXIT1
SPECIAL>EXIT1 is the same as MENU>EXIT except if you have started a Venapp from the command line. When you start a Venapp from the command line MENU>EXIT closes Vensim, while SPECIAL>EXIT1 closes the Venapp, and opens the Vensim Workbench. The demo disk uses this to give access to the Vensim development environment.

SPECIAL>EXTERNAL|funcname
Executes the function funcname in a DLL you have loaded using the SPECIAL>LOADDLL command. The function will be called without options. It should return 1 if successful or 0 otherwise. The return value will be used to determine whether to execute the remaining commands or shift to another screen. NOTE Special EXTERNAL is not related to Vensim's External functions. It simply provided a mechanism to call in functionality from outside of Vensim. You can use the SETTING>EXTERNALFUNCTION to change the external function library in use.

SPECIAL>LOADAPPINT|appname@screen
Load the application interface file appname. The screen number to open on follows the @. This allows you to move between application interfaces. LOADAPPINT is usually preceded by a SPECIAL>LOADMODEL command.

SPECIAL>LOADDLL|dllfile
Loads the Dynamic Link Library dllfile. You can load Dynamic Link Libraries in order to have Venapp call your code with the SPECIAL>EXTERNAL function. There are not currently any mechanisms for passing arguments back and forth. When you load a DLL, any DLL you may have loaded previously in the Venapp will be unloaded.

SPECIAL>LOADMODEL|mdlname
Load the model mdlname. If the model is in a different directory, that directory will become current. This command can be followed by a SPECIAL>LOADAPPINT command to shift between Vensim applications. When doing this you do not need to specify a directory for the LOADAPPINT command as long as the application interface is in the same directory as the model. You can use relative directory strings in DOS format (e.g. ..\intro.vmf) and they will automatically be translated for the Macintosh.

61

If you are working with Vensim DSS, you can load both text format model (.mdl files) and binary format models (.vmf) files. The runtime configurations only allow the loading of binary format models. The only real reason to load text format models would be to use the output of another program that automatically creates Vensim models or, as in the case of the sample models, so as not to require extra copies of the models (.vmf and .mdl). NOTE that if you load text format models, the SIMULATE>READRUNCHG and SIMULATE>BASED commands will not work very well since the time stamps on the models will not match from session to session. As with other file names, you can use a ? to query for the name of a model to load. This feature is used by the Vensim Model reader code to allow users to select models.

SPECIAL>LOADRUN|runname
Load the run named runname. As with other file name you can use a ? to prompt for a name or an ! to load the current run name as set by SIMULATE>RUNNAME or SIMULATE>RUNNAME.

SPECIAL>LOADTOOLSET|toolname
Load the toolset named in option. Since the WORKBENCH commands refer to tool names it is important that you match the toolset to the application.

SPECIAL>MESSAGE|severe|title|string
Puts up a message for the user in a separate popped up window with an OK button. severe determines the icon that will be shown in the window. Use 1 for an informational icon, 2 for a warning icon and 3 for a stop icon. title appears in the title bar of the window. string is displayed inside the window. You can break a message into more than one line by using the escape sequence \n. For example: SPECIAL>MESSAGE|2|Pay Attention|Profits have fallen two \ quarters in a row.\nYou are in danger of going bankrupt! will result in:

SPECIAL>NOINTERACTION|n
This command is available only for Command Scripts. When n = 1 it causes any user interaction in the form of Stop, Inform or ask yes or no messages to be suppressed. When these messages would appear they are written to the error log and the default response assumed. If n = 0 interaction is turned back on. While NOINTERACTION is in effect, as each command is executed the command is also recorded in the error log (vensim.err).

SPECIAL>READCUSTOM|graphfile
Read the custom graph definition file graphfile. Note that when using the Vensim Application Runtime, it is necessary for graphfile to be a binary format (.vcf) file.

62

SPECIAL>REFRESH
Force a refresh of displayed values on the screen. This function is useful if you want to use buttons to change values as in: :SCREEN ONLY SHOWVAR,"FINAL_TIME",10,10,0,0,L BUTTON,"Small",10,20,0,0,L,,SIMULATE>SETVAL|FINAL_TIME=80&SPECIAL>RE FRESH BUTTON,"Big",10,30,0,0,L,,SIMULATE>SETVAL|FINAL_TIME=800&SPECIAL>REF RESH

SPECIAL>RESETINPUT
Reset the inputs on the current screen to reflect the current model settings. This is useful in gaming mode where SETVAL can be used to set gaming parameters to variables computed in the model. For example: :SCREEN GAME TEXTONLY,"Spending ($,000,000)",2,40,0,0,L|Times New Roman|12|B|0-00 TEXTONLY,"Recom- mended",17,43,7,8,R||10||128-0-0 TEXTONLY,"Operations",2,50,0,0,L||10||0-0-255 SHOWVAR,"RecommendedOperatingSpending",17,55,0,0,L||||128-0-0 MODVAR,"InputOperatingSpending",2,54,13,5,, BUTTON,"Set to Recommended",2,91,22,6,L|Times New Roman|10||0-0-0,,\ SIMULATE>SETVAL|InputOperatingSpending=RecommendedOperatingSpending\ &SPECIAL>RESETINPUT BUTTON,"Continue",45,93,0,0,C,Cc,GAME>GAMEON BUTTON,"End Game",80,93,0,0,C,,GAME>ENDGAME,MAIN Here a button is available to set the value to a recommendation computed in the model. You can use one button to set multiple values. The final RESETINPUT brings the screen up to date. If you do not do this, the previously entered values would be read from the screen and used.

SPECIAL>RUNCOMMAND|cmdfile
Runs the command (.cmd) or database output (.vdo) file named. Vensim uses the file name to determine which type of file it is. This would normally be used from within a Venapp, or from within a command file or via the DLL for a .vdo file. It is also possible to nest command files in this way which can be useful if you have a number of commands that are repeated as would be the case for making a number of variations on a simulation in batch mode.

SPECIAL>SECONDCLICK|graph
Tell Vensim the equivalent of a second click has occurred in the window named by graph. graph must refer to a tool output window as labeled in the txt field of a TOOL or WIPTOOL control (see the EXPORT command for an example). The SECONDCLICK command selects the highlighted variable in the tool output into the workbench. Consider the example: :SCREEN CAUSE TEXTONLY,"Causal tracing -",0,2,50,0,R WBVAR,"",50,2,0,0,L TOOL,"TR1",2,6,96,42,,,WORKBENCH>CAUSES TREE TEXTMENU,"T - Trace on highlight",5,50,0,0,L,Tt,SPECIAL>SECONDCLICK|TR1,

63

SETWB,"",0,0,0,0,,,,CAUSE

SPECIAL>SETFOCUS|number
Sets the focus the control with the number given. Number is the control number where 1 is the first control that appears, 2 the second and so on. This can be useful in validating use input. E.g., :SCREEN BOBTEST MODVAR,"Var 1",50,50,20,10, BUTTON,"OK",20,90,0,0,C,,SPECIAL>SETFOCUS|1&IFTHENELSE&TEST>TVar 1=0&\ BRANCH>OK&SPECIAL>STOP|Var 1 must be even integer! BRANCH,"OK",0,0,0,0,,,,OTHERSCR (where Tvar 1 = INITIAL(MODULO(Var 1,2)) ~ ~ | ).

SPECIAL>SETTITLE|title
Sets the window title to contain title. This is useful for customizing appearance. You can display the name of the loaded model, the title of the currently displayed view, and the current workbench variable. To do this begin the title with a * followed by M for model, V for view and W for workbench variable. You can include 1, 2 or three of these letters in any order. Follow the letters by a vertical bar | and then the text for the title with %s where the names should appear (this is standard C syntax). For example: SPECIAL>SETTITLE|*M|My App the model is %s Naming a view only works on a screen in which a SKETCH control is included. NOTE Don't ever repeat %s more than 3 times as this will cause a program error.

SPECIAL>SETWBITEM|varname
Set the workbench item to varname. If the name is subscripted and contains comments be sure that the command is put in quotes.

SPECIAL>STOP|message
Puts up a stop sign and displays message. Useful for informing the user of some condition that has been detected. The SPECIAL>MESSAGE function is more flexible.

SPECIAL>STOPSIM|option
Stops a simulation. Use option of SAVE to save the results so far, NOSAVE to discard results and QUERY to ask the user. The options have no effect in gaming mode the output is always saved. This command must appear first in the list of commands, and will be the only command executed during simulation. If this command is invoked and there is no simulation in progress, it has no effect, and the commands that follow it are executed. The STOPSIM command is the only command that has any effect while a simulation is in progress.

SPECIAL>SUBSCRIPT|range|elem1|elem2
Allows you to control the selection of Subscripts from within a Venapp. range should name a subscript range and should be followed by one or more element names for that range. You can also follow the range by a subrange or the range itself to select all elements in the subrange. If you want to add to the set of selected subscripts instead of replacing it use + instead of the subscript range name. Examples (Sub: (S1-S5) ~ ~ | ): Button,"The third element",20,10,30,0,C,,SPECIAL>SUBSCRIPT|SUB|S3

64

Button,"All elements",30,20,30,0,C,,SPECIAL>SUBSCRIPT|SUB|SUB Button,"one and four",40,30,30,0,C,,SPECIAL>SUBSCRIPT|SUB|s1|s4 Button,"add 5 to selected",40,50,30,0,C,,SPECIAL>SUBSCRIPT|+s5 You can also use a ? in place of the Subscript element to bring up a Popup version of the subscript control dialog. This dialog will not be a tabbed dialog, but only a dialog for the subscript you choose. Button,"query",40,60,30,0,C,,SPECIAL>SUBSCRIPT|sub|? Finally you can use a ? in place of the Subscript Range name. This will bring up a list of the available Subscript ranges. Selecting one of these will then bring up the Popup form of the Subscript Control for that subscript. This feature is used in the Vensim Model Reader.

SPECIAL>VARSELECT|prompt
Prompts for a variable to select into the workbench. prompt is displayed in the title bar of the selection box. A Popup form of the Variable Selection dialog is displayed allowing the user to choose one variable.

SPECIAL>WINHELP|helpfile|data
Invokes the Windows help engine. helpfile should contain the name of a help (.hlp) file which, for best success, should be contained in the same directory as the current model. You can, optionally specify an integer index value at which to open the help file as in SPECIAL>WINHELP|myhelp.hlp|1000. The Microsoft Windows software development documentation contains information on creating and using help files.

SYNTHESIM>AUTO|n (n is 0 or 1)
By default when the MENU>SYNTHESIM command is used the model will be simulated whenever a model Constant or Lookup is changed. This behavior can be suppressed by calling SYNTHESIM>AUTO|0 (zero) to run off automatic simulation. This is useful if you want to set a number of values at once without each change causing a new simulation. When you turn off automatic simulation you will need to explicitly invoke SYNTHESIM>GO.

SYNTHESIM>GO|n (n is 0 or 1)
When in SyntheSim mode causes a simulation to be performed. This command is only useful if you have turned off automatic simulation. If it is called with the optional argument of 0 the results will not be saved to disk and all visible graphs will not have the scales reset. See also the vensim_synthesim_vals.

TEST
TEST commands are used to test model constants and variables against numbers or other model variables. The TEST command returns 1 (TRUE) if the specified relationship is true, and 0 (FALSE) if not. The TEST command is intended primarily for use with IFTHENELSE and BRANCH commands. The command portion of TEST should take the form varname relation value where varname is a model Constant or variable, relation is one of <, <=, =, >=, > or <> and value is either a number or another model variable. For example TEST>FRACTION < 1 TEST>PERCENT TO ADVERTIZING>PERCENT TO KICKBACK

65

The second of these compares two model variables and is, because the > is used in the command syntax and the comparison, a little hard to read. Vensim looks for the first > and treats everything after that (and before the next &) as the command. If you specify a model variable that is not a constant, Vensim will execute the equation for that variable in the model. Vensim will not, however, test dependency. Thus if you want to compute values, the values computed should depend only on model constants. Consider the following common example: sector : S1,S2,S3,S4 ~~| ALLOCATION FRACTION[sector]=.25 ~~| TOTAL ALLOCATION FRACTION = SUM(ALLOCATION FRACTION[sector!])~~| Now in the Venapp you might want to test that the entered fractions do indeed add up to 1. :SCREEN ENTRY MODVAR,"ALLOCATION FRACTION[S1]",10,10,20,0,,[0|1] MODVAR,"ALLOCATION FRACTION[S2]",10,20,20,0,,[0|1] MODVAR,"ALLOCATION FRACTION[S3]",10,30,20,0,,[0|1] MODVAR,"ALLOCATION FRACTION[S4]",10,40,20,0,,[0|1] BUTTON,"Simulate Model",10,50,0,0,L,,IFTHENELSE&TEST>\ TOTAL ALLOCATION FRACTION=1&BRANCH>OK&\ SPECIAL>STOP|Fractions must add to 1. BRANCH,"OK",0,0,0,0,,,MENU>RUN,NEXTSCREEN If the fractions add to one, Vensim will make a simulation and shift to NEXTSCREEN. If the numbers do not add to one, the user will see a stop sign. If you do attempt to compute a value that depends on something other than Constants you will likely get nonsense back. If you are careful, you can cause Vensim to execute equations in a specific order (through a series of Test commands) and get correct model results (Only the initial portion of INTEG will be evaluated.)

TIMEAXIS
The TIMEAXIS command manipulate the time axis used in graphs and tables.

TIMEAXIS>RESET
Resets the time axis to cover all runs. Users can zoom in by holding down the shift key and dragging across a graph. The RESET command returns to the full range.

TIMEAXIS>SPECIALTIME|value
Sets Special Time to value. Special time is used in the Table and Bar Graph tools and in the SHOWVAR controls not specifying a specific time. value can be a number or a model constant or, in gaming mode, other model variable.

TIMEAXIS>STARTTIME|value
Sets the Start Time to value. Start Time is used in graphs to set the first displayed value.

TIMEAXIS>STOPTIME|value
Sets the Stop Time to value. Stop Time is used in graphs to set the last displayed value.

66

WORKBENCH
Invokes a workbench tool placing it in the stated position. Following the WORKBENCH class should be the name of a tool as it appears in the toolset on the workbench. It is important that the correct toolset be loaded for this command to work properly.

Command Use Summary


The list on the following shows a summary of which Venapp Commands are supported in different environments. A command that is supported in Venapp means that it can be used in a Venapp and will also work when using the Vensim Application Runtime. Command scripts are discussed in Chapter 7, Dynamic Data Exchange (DDE) is discussed in Chapter 9 and the Vensim DLL is discussed in Chapters 11 and 12.

Class/Command BRANCH CANCEL CUSTOM ERROR EXPORT FILE


COPY CREATE DECRYPT DELETE ENCRYPT EXISTS MDL2VMF RENAME VCD2VCF VGD2VGF VMF2MDL

Venapp

Command

DDE

DLL

MinDLL

GAME
BACKUP ENDGAME GAMEINTERVAL GAMEON READGIN RELOAD WRITEGIN

Class/Command IFTHENELSE LOG


CREATE MESSAGE TIMESTAMP

Venapp

Command

DDE

DLL

MinDLL

MENU

67

DAT2VDF EXIT GAME LOAD_RUN REDO_GRAPHS RUN RUN1 RUN_OPTIMIZE RUN_SENSITIVITY SENS2TAB SYNTHESIM TAB2VDF VDF2DAT VDF2TAB VDF2WK1 VDF2XLS WK12VDF XLS2VDF

Class/Command PRINT SETTING


EURONUMBER EXPORTSIZE EXTERNALFUNCTION HOVERCOM PRINTOPTQUERY SHOWINITIAL SHOWLOOKUP SHOWMACRO SHOWWARNING SIZEINCHES

Venapp

Command

DDE

DLL

MinDLL

SIMULATE
1TABCHG ADDCIN ADDDATA BASED CHGFILE DATA GETCNSTCHG GETTABCHG MINMEM OPTPARM PAYOFF READCIN READRUNCHG RESUME

68

RUNNAME SAVELIST SENSITIVITY SENSSAVELIST SETVAL WRITECIN

Class/Command SKETCH
CHOOSEVIEW PREVVIEW NEXTVIEW ZOOM

Venapp

Command

DDE

DLL

MinDLL

SPECIAL
ALIASSCREEN ASKYESNO BUTTONFOCUS CLEARRUNS EXIT1 EXTERNAL LOADAPPINT LOADDLL LOADMODEL LOADRUN LOADTOOLSET MESSAGE NOINTERACTION READCUSTOM READINI REFRESH RESETINPUT SECONDCLICK SETTITLE SETWBITEM STOP STOPSIM SUBSCRIPTS VARSELECT WINHELP

SYNTHESIM
AUTO GO

TEST TIMEAXIS
RESET SPECIALTIME STARTTIME

69

STOPTIME.

WORKBENCH

70

Venapp Examples
Vensim DSS ships with a number of sample Venapps in the Venapp subdirectory of the sample models directory.

Template Application
Vensim DSS ships with a template Venapp that is a very good starting point for developing your own Venapp. Only a small amount of this template is actually model specific. The files to support this Venapp are contained in the venapp\template subdirectory of the sample models directory (normally c:\Program Files\vensim\models\sample).

Model Setup
The example is based on Jay Forrester's World Dynamics model as published in the book World Dynamics (available from Productivity Press). The World model has been modified to remove the various switch times and alternate parameters. This was done in order to make it simpler to present this Venapp. Two gaming variables were also added to this model. capital investment rate normal= GAME (capital investment rate normal c) natural resource utilization normal= GAME (natural resource utilization normal c) Here the same names ending in c represent constants in the model. We chose to have people game on the investment rate rather than the actual amount of investment being made because it would be hard to most people to get a sensible order of magnitude value for investment in this model. For applications that are closer to people's every day experience, or settings where some amount of preparation is expected before playing a game using variables like actual investment would be more appropriate (that is we could use an equation like (capital investment = GAME( Population * capital investment multiplier * capital investment rate normal)).

Welcome Screen
:SCREEN WELCOME SCREENFONT,Times New Roman|12|B COMMAND,"",0,0,0,0,,,"SPECIAL>SETTITLE|Venapp Template Example" COMMAND,"",0,0,0,0,,,SPECIAL>LOADMODEL|worldapp.vmf COMMAND,"",0,0,0,0,,,SPECIAL>READCUSTOM|world.vgd COMMAND,"",0,0,0,0,,,SPECIAL>LOADTOOLSET|world.vts COMMAND,"",0,0,0,0,,,SPECIAL>CLEARRUNS COMMAND,"",0,0,0,0,,,SPECIAL>LOADRUN|base.vdf COMMAND,"",0,0,0,0,,,SETTING>SHOWWARNING|0 TEXTONLY,"World Model",50,5,0,0,C||36|B|255-0-0, TEXTONLY,"Vensim Application Template",0,20,100,0,C|Arial|22|B|0-0255, TEXTONLY,"Ventana Systems, Inc.",0,58,100,0,C||10||128-0-128|, TEXTONLY,"60 Jacob Gates Road",0,62,100,0,C||10||128-0-128|, TEXTONLY,"Harvard MA 01451 - USA",0,66,100,0,C||10||128-0-128|,

71

TEXTONLY,"Software subject to restriction of the license agreement",\ 0,70,100,0,C||10||128-0-128|, TEXTONLY,"Copyright 1986-1997 Ventana Systems, Inc. ALL RIGHTS RESERVED",\ 0,74,100,0,C||10||128-0-128|, TEXTONLY,"Press any key or button to continue",0,84,100,0,C||14|||, BUTTON,"Continue",50,90,45,5,C,,,MAIN ANYKEY,"",0,0,0,0,0,,,MAIN The first screen is the one that will be entered when the Venapp is first started and thus contains a number of commands to load the model, graph file, toolset and so on. The model is loaded as a .vmf file. If you are going to use the READRUNCHG command (as this application does), you should use .vmf files so that closing the Venapp and returning to it later will not prevent the use of old runs. The screen loads a .vgd file. In the development of models, it is often simplest to use the default graph set associated with a model. When developing Venapps, however, it is good practice to save these graph sets as separate files. This will facilitate packaging of your Venapp as a standalone application, and will also prevent problems that might arise if a model was set to use a graph set other than its default graph set. The loading of the toolset is done primarily to prevent problems that might occur if some other toolset had been in use. The toolset world.vts is simply a copy of default2.vts. The run base has been loaded alone. This is not really necessary for this application, but is often helpful if you want people to have a baseline run for comparison. Warnings are turned off to prevent Lookup overrun messages from being displayed. The text provides Copyright and other information. The ANYKEY control allows the user to close this screen by pressing any key.

Main Menu
:SCREEN MAIN TEXTONLY,"World Model",50,5,0,0,C|Times New Roman|30|B|200-55-0, TEXTONLY,"Main Menu",50,18,0,0,C|Arial|24|B|0-0-255, RECTANGLE,"",20,30,60,46,C||||0-0-255 BUTTON,"Review Model Structure",50,35,50,6,C,,,STRUCTURE BUTTON,"Simulate the Model",50,45,50,6,C,,,SETUPSCENARIO BUTTON,"Play a Game",50,55,50,6,C,,\ SIMULATE>RUNNAME|?Name for new game output,STARTGAME BUTTON,"Analyze Simulation Results",50,65,50,6,C,,SPECIAL>ALIASSCREEN|ARETURN|MAIN,ANALYSIS BUTTON,"? Help ?",50,80,40,6,C,,SPECIAL>WINHELP|VRHELP.HLP|1100 BUTTON,"Exit",50,90,40,6,C,Qq,SPECIAL>ASKYESNO|Do you really want to exit?&MENU>EXIT, This application is centered around a main menu from which different things can be done, and which can be returned to after the user does something. This is a common way to organize an application (although you can organize it differently). The different options are all presented using buttons. The Help button calls up the Windows help engine on the Vensim Model Reader help file. This invocation actually references a specific topic in that file. You can use the WINHELP command without a topic number to bring up the opening screen of the help file.

Presenting Structure
:SCREEN STRUCTURE SKETCH,"SK1",0,0,100,82,,5,1, COMMAND,"",18,77,20,6,L,,SPECIAL>SETTITLE|*MV|%s - View:%s

72

BUTTON,"Choose a View",8,84,20,6,L,,SKETCH>CHOOSEVIEW|SK1|Choose a view of model structure&SPECIAL>SETTITLE|*MV|%s - View:%s BUTTON,"Previous",7,92,10,6,L,,SKETCH>PREVVIEW|SK1&SPECIAL>SETTITLE| *MV|%s - View:%s, BUTTON,"Next",19,92,10,6,L,,SKETCH>NEXTVIEW|SK1&SPECIAL>SETTITLE|*MV |%s - View:%s, BUTTON,"Print",54,84,10,6,L,,PRINT>SK1 BUTTON,"Export",54,92,10,6,L,,EXPORT>SK1 BUTTON,"? Help ?",71,84,22,6,L,,SPECIAL>WINHELP|VRHELP.HLP|1200 BUTTON,"Exit to Main Menu",71,92,22,6,L,,,MAIN There are a number of ways to present structure. This screen is pretty much the same as the structure screen in the Vensim Model Reader. The Zoom percent is set at 5 to put the sketch in fit to screen mode. Because of this, no scroll bars are shown for the sketch. Notice that the SETTITLE command appears on entry to the screen and also whenever the selected view is changed. The Help button brings up a topic appropriate to this screen.

Scenario Setup
Setting up scenarios consists of letting people pick a name for the scenario, changing model Constants and Lookups, and actually making the simulation. The actual order in which things happens is flexible. You can, for example, wait until just before the simulation starts to choose a name for the run. The architecture we are using here first gets a run name and a basis for the simulation, then goes to a menu that allows the user to move to other screens and change Constants and Lookups or start the simulation. :SCREEN SETUPSCENARIO TEXTONLY,"Scenario Setup",50,5,0,0,C|Arial|24|B|0-0-255, BUTTON,"Scenario based on model constants",50,32,50,6,C,Ss,\ SIMULATE>READRUNCHG&\ SIMULATE>RUNNAME|?Name the new scenario,SETUPSIM BUTTON,"Modify and rerun an existing scenario",50,42,50,6,C,Mm,\ SIMULATE>RUNNAME|?Select the scenario to modify|E&\ SIMULATE>READRUNCHG|!,SETUPSIM BUTTON,"Scenario based on an existing scenario",50,52,50,6,C,Ss,\ SIMULATE>READRUNCHG|?Select scenario for basis&\ SIMULATE>RUNNAME|?Name the new scenario,SETUPSIM BUTTON,"Scenario based on changes (.cin) file",50,62,50,6,C,Ss,\ SIMULATE>READCIN|?Choose a changes file&\ SIMULATE>RUNNAME|?Name the new scenario,SETUPSIM BUTTON,"Exit to Main Menu",50,90,40,6,C,EeXx,,MAIN This screen just offers the four most obvious options for starting up a scenario. The inclusion of .cin files may be confusing to some users and you might want to leave it out. Since there are only a small number of buttons on this screen it may be possible to incorporate them into the main menu. There is a complexity tradeoff between the number of screens and the amount of stuff on a single screen. Which works better depends on who will be using it. :SCREEN SETUPSIM TEXTONLY,"Set Up the Model",50,5,0,0,C|Arial|24|B|0-0-255, TEXTONLY,"Simulate the Model",75,52,0,0,C|Arial|24|B|0-0-255, TEXTONLY,"Save Setup",25,52,0,0,C|Arial|24|B|0-0-255, BUTTON,"Change model assumptions",25,20,40,6,C,,,INPUT1 BUTTON,"Modify policy options",25,30,40,6,C,,,INPUT2 BUTTON,"Make changes to other constants",75,20,40,6,C,,SIMULATE>GETCNSTCHG

73

BUTTON,"Make changes to other lookup tables",75,30,40,6,C,,SIMULATE>GETTABCHG BUTTON,"Save setup as changes file (.cin)",25,65,40,10,C,,\ SIMULATE>WRITECIN|?Name the changes file, BUTTON,"SIMULATE",75,65,40,10,C,,,RUNNING !BUTTON,"GAME",75,65,40,10,C,,,STARTGAME BUTTON,"Exit to Main Menu",50,90,40,6,C,,,MAIN This screen has four options for changing Constants and Lookups. One of these is for model assumptions (INPUT1) and another for policy settings (INPUT2). This is a useful way to categorize changes, though it is not always appropriate to give users access to basic assumptions. This screen also allows the user to go in and change any Constants or Lookups in the Model using the GETCNSTCHG and GETTABCHG commands. These commands are useful when you developing an application and want to experiment with what will be included, or if you want to give people complete access to the model. In general, however, you will probably not want to include them in finished applications. The "SIMULATE" button shifts to the RUNNING screen which starts the simulation. It would also be possible to start a game based on the changes made. The "GAME" button is commented out in the above screen but could be used in place of or as well as the "SIMULATE" button. :SCREEN INPUT1 TEXTONLY,"Scenario Assumptions",50,5,0,0,C|Arial|24|B|0-0-255, TEXTONLY,"Birth Rate",15,15,0,0,L LISTVAR,"birth rate normal",60,15,20,0,,[0|0.1]\ Very low (0.005) = 0.005|Low (0.02) = 0.02|Medium (0.04) = 0.04|\ High (0.06) = 0.06|Very high (0.1) = 0.1 TEXTONLY,"Capital Agriculture Fraction Adjustment Time",15,25,0,0,L RADIO1VAR,"capital agriculture fraction adjustment time",60,25,8,0,,[8],Low RADIOVAR,"capital agriculture fraction adjustment time",70,25,8,0,,[15],Medium RADIOVAR,"capital agriculture fraction adjustment time",80,25,8,0,,[30],High TEXTONLY,"Natural Resource Extraction Table Function",15,35,0,0,L MODTABLE,"natural resource extraction mult tab",60,35,0,0,L, TEXTONLY,"Initial Natural Resources",15,45,0,0,L MODVAR,"natural resources initial",60,45,20,0,L,|[9e10|9e12] TEXTONLY,"Initial Pollution Level",15,55,0,0,L MODVAR,"pollution initial",60,55,20,0,L,|[2e7|2e9] BUTTON,"Record changes and return to Modeling Choices",20,70,50,5,L,Rr,,SETUPSIM BUTTON,"Return to Modeling Choices (cancel changes)",\ 20,80,50,5,L,EeXx,CANCEL,SETUPSIM This screen allows the user to set the assumptions for the model. This screen makes use of LISTVAR, RADIOVAR and MODVAR to set values. Notice the use of the CANCEL command to back out without keeping settings. :SCREEN INPUT2 TEXTONLY,"Scenario Policy Options",50,5,0,0,C|Arial|24|B|0-0-255, TEXTONLY,"Rate of Capital Investment",20,22,0,0,L TEXTONLY,"Pollution Per Capita",20,37,0,0,L TEXTONLY,"Natural Resource Utilization",20,52,0,0,L SLIDEVAR,"capital investment rate normal

74

c",50,20,15,10,H,[0|0.2|.01] SLIDEVAR,"pollution per capita normal c",50,35,15,10,H,[.05|2|.025] SLIDEVAR,"natural resource utilization normal",50,50,15,10,H,[.05|2|.025] BUTTON,"Record changes and return to Modeling Choices",20,70,50,5,L,Rr,,SETUPSIM BUTTON,"Return to Modeling Choices (cancel changes)",\ 20,80,50,5,L,EeXx,CANCEL,SETUPSIM This screen allows the user to set some policies. The screen uses SLIDEVAR controls to allow the user to change things. Again there is a CANCEL command to back out.

Simulating
:SCREEN RUNNING WIPTOOL,"GR1",5,5,90,80,,,CUSTOM>WIP1 COMMAND,"",0,0,0,0,,,MENU>RUN1|O COMMAND,"",0,0,0,0,,,SPECIAL>SETWBITEM|Population CLOSESCREEN,"",0,0,0,0,,,,OUTPUT1 With everything set up all that is required to simulate the model is the MENU>RUN1 command (which could be attached to the "SIMULATE" button in the SETUPSIM screen). Executing this command will cause any Work in Progress graphs to pop up. The short screen RUNNING (above) is an alternative and more controlled way of getting the same result. The custom graph WIP1 is opened as a WIPTOOL, then the simulation is started. After the simulation is completed the CLOSESCREEN command causes the screen to be closed and the Venapp to shift to the OUTPUT1 screen. The SETWBITEM command that precedes this makes sure that the output graph opens on a variable that is dynamic (that will display some interesting behavior).

Displaying Output
There is likely to be a lot of variation in the way that output is displayed. This Venapp has a very simple capacity to show different graphs and tables and allows the user to select among custom graphs, reports and tables. In developing most Venapps, you will probably want to combine SHOWVAR controls and custom graphs in a more sophisticated way. :SCREEN OUTPUT1 TOOL,"GR1",5,5,90,70,,,WORKBENCH>Graph BUTTON,"Show table",20,82,25,10,C,,,OUTPUT2 !BUTTON,"Modify and Rerun Last Scenario",75,82,0,6,L,,\ SIMULATE>READRUNCHG|!,SETUPSIM BUTTON,"Select a new variable",50,80,25,0,C,,\ SPECIAL>VARSELECT|New variable to use,OUTPUT1 BUTTON,"Change subscripts",50,90,25,0,C,,\ SPECIAL>SUBSCRIPT|?Choose a subscript to control selection on,OUTPUT1 BUTTON,"Perform detailed analysis",80,80,25,0,C,,\ SPECIAL>ALIASSCREEN|ARETURN|OUTPUT1,ANALYSIS BUTTON,"Return to Main Menu",80,90,25,0,C,,,MAIN This screen allows the user to look at a graph and choose a new variable to be graphed. The subscript control is also made available from this screen though it is not relevant to this model which has no subscripts. :SCREEN OUTPUT2 TOOL,"GR1",5,5,90,70,,,WORKBENCH>Table BUTTON,"Show graph",20,82,25,10,C,,,OUTPUT1

75

BUTTON,"Select a new variable",50,80,25,0,C,,SPECIAL>VARSELECT|New variable to use,OUTPUT2 BUTTON,"Change subscripts",50,90,25,0,C,8,SPECIAL>SUBSCRIPT|?Choose a subscript to control selection on,OUTPUT2 BUTTON,"Perform detailed analysis",80,80,25,0,C,,SPECIAL>ALIASSCREEN|ARETURN|OUTPUT2,ANALY SIS BUTTON,"Return to Main Menu",80,90,25,0,C,,,MAIN This screen is the same as OUTPUT1 except that it show a table instead of a graph.

Gaming
There is a little bit more to gaming than there is to regular simulation because gaming requires user intervention. Thus, instead of just running the simulation, the game is first started, and then the user can change things as the simulation progresses. :SCREEN STARTGAME COMMAND,"",0,0,0,0,,,GAME>GAMEINTERVAL|10 COMMAND,"",0,0,0,0,,,MENU>GAME|O CLOSESCREEN,"",0,0,0,0,,,,GAMECONTROL This sets up the gaming interval, starts the game, and goes to the game control screen. Once the game is started, input controls will only work on gaming variables. Using input controls on model Constants or Lookups will just give the message ERROR or gray the control. :SCREEN GAMECONTROL TEXTONLY,"Game Control",50,0,0,0,C|Arial|24|BU|200-55-0, RECTANGLE,"",13,10,15,7,C||||0-0-255 TEXTONLY,"Time = ",22,12,0,0,R SHOWVAR,"Time%4.0f",22,12,0,0,L WIPTOOL,"GR1",40,10,58,55,,,CUSTOM>WIP1 BUTTON,"Forward",20,25,0,0,C,Ff,GAME>GAMEON BUTTON,"Backup",20,35,0,0,C,Ff,GAME>BACKUP TEXTONLY,"Natural Resource Utilization Per Person",20,45,0,0,C MODVAR,"natural resource utilization normal",15,50,10,0,L,[0|2] TEXTONLY,"Fraction of Capital Invested",20,65,0,0,C SLIDEVAR,"capital investment rate normal",5,70,30,10,H,[0|0.1|.005] BUTTON,"Perform detailed analysis",20,90,0,0,C,,SPECIAL>ALIASSCREEN|ARETURN|GAMECONTROL,AN ALYSIS TEXTONLY,"End the Game and Return to Main Menu",70,73,0,0,C|Arial|14|B|0-0-255, BUTTON,"End Game",70,80,0,0,C,,GAME>ENDGAME,MAIN The game control screen has SLIDEVAR controls to change the gaming variables, displays a work-inprogress graph on the right, and shows the current time at the top. The user can go forward in time or back up in time, and also perform model analysis. Notice the use of the ALIASSCREEN command so that model analysis returns the user to the game control screen and not the main menu.

Analysis
The analysis screens are quite generic, and should work without modification on different models. :SCREEN ANALYSIS TEXTONLY,"Analysis Control",50,5,0,0,C|Arial|24|B|0-0-255, BUTTON,"Select a variable for analysis",50,13,60,5,C,4,\

76

SPECIAL>SETWBITEM|TOT COST&SPECIAL>VARSELECT|New variable to use BUTTON,"Load, unload, or reorder previous runs",50,20,60,5,C,1,MENU>LOAD_RUN, BUTTON,"Change subscript selection",50,27,60,5,C,8,\ SPECIAL>SUBSCRIPT|?Choose a subscript to control selection on, TEXTONLY,"Results",0,36,100,0,C|Times New Roman|24||0-0-255 BUTTON,"List differences between the first two loaded runs",50,43,60,5,C,8,,DIFF BUTTON,"Display a predefined graph or report",50,50,60,5,C,,,RESULT BUTTON,"Trace underlying causes using Trees",50,57,60,5,C,5,,CAUSE1 BUTTON,"Trace underlying causes using Graphs",50,64,60,5,C,6,,CAUSE2 BUTTON,"Trace the Uses of a variable",50,71,60,5,C,7,,USE BUTTON,"Return to Menu",50,90,40,5,C,,,ARETURN This is just a secondary menu screen. Notice the shift to screen ARETURN. This is an alias, not an actual screen name. This screen will return to the screen defined for that alias, which will depend on how the ANALYSIS screen was entered. :SCREEN DIFF TEXTONLY,"Constant and table differences between first two loaded \ scenarios",0,2,100,0,C32 TOOL,"D1",5,10,90,80,,,WORKBENCH>RUNS COMPARE BUTTON,"Print",30,92,20,6,C,Pp,PRINT>D1 BUTTON,"Analysis Control",70,92,20,6,C,,,ANALYSIS ANYKEY,"",0,0,0,0,0,,,ANALYSIS The run compare tool is a handy tool for summarizing differences. If you have a model with data inputs you might also want to change the options on runs compare tool to include data and possibly gaming variables. :SCREEN RESULT TOOL,"GR1",2,5,96,80,,,CUSTOM>?Graph to display BUTTON,"Select another graph or report",2,90,34,6,L,,CUSTOM>?Other graph|GR1 BUTTON,"Print",38,90,10,6,L,,PRINT>GR1 BUTTON,"Copy",50,90,10,6,L,,EXPORT>GR1 BUTTON,"? Help ?",62,90,12,6,L,,SPECIAL>WINHELP|VRHELP.HLP|1600 BUTTON,"Analysis Control",76,90,22,6,L,,,ANALYSIS This is a generic custom graph screen. You might hard wire a series of buttons across the bottom to bring up different custom graphs. :SCREEN CAUSE1 TEXTONLY,"Causal tracing -",0,2,50,0,R WBVAR,"",50,2,0,0,L TOOL,"TR1",2,6,96,42,,,WORKBENCH>CAUSES TREE BUTTON,"Graph based",2,50,40,0,L,Cc,,CAUSE2 BUTTON,"Definition...",43,50,0,0,L,Cc,WORKBENCH>DOCUMENT, BUTTON,"Uses - of current variable",2,57,40,0,L,Cc,,USE BUTTON,"Select a new variable to trace",2,64,40,0,L,Ss,\ SPECIAL>VARSELECT|New variable for tracing BUTTON,"? Help ?",2,71,40,0,L,,SPECIAL>WINHELP|VRHELP.HLP|1700 BUTTON,"Analysis Control",2,78,40,0,L,EeXx,,ANALYSIS TOOL,"GR1",60,50,40,50,,,WORKBENCH>STRIP GRAPH SETWB,"",0,0,0,0,,,,CAUSE1

77

Generic causal tracing. Uses the SETWB control to reenter itself on a variable selection. :SCREEN CAUSE2 TEXTONLY,"Causal tracing -",2,2,0,0,L WBVAR,"",20,2,0,0,L TOOL,"TR1",60,0,40,100,,,WORKBENCH>CAUSES STRIP BUTTON,"Tree based",2,50,40,0,L,Cc,,CAUSE1 BUTTON,"Uses - of current variable",2,57,40,0,L,Cc,,USE BUTTON,"Select a new variable to trace",2,64,40,0,L,Ss,\ SPECIAL>SETWBITEM|POPULATION&SPECIAL>VARSELECT|New variable for tracing BUTTON,"? Help ?",2,71,40,0,L,,SPECIAL>WINHELP|VRHELP.HLP|1800 BUTTON,"Analysis Control",2,78,40,0,L,EeXx,,ANALYSIS TOOL,"GR1",2,8,58,40,,,WORKBENCH>DOCUMENT SETWB,"",0,0,0,0,,,,CAUSE2 Similar to CAUSE1. :SCREEN USE TEXTONLY,"Uses of -",0,2,50,0,R WBVAR,"",50,2,0,0,L TOOL,"TR1",2,6,96,42,,,WORKBENCH>USES TREE BUTTON,"Causes - of Current variable",2,50,40,0,L,Cc,,CAUSE1 BUTTON,"Definition...",43,50,0,0,L,Cc,WORKBENCH>DOCUMENT, BUTTON,"Causes - Graph Based",2,57,40,0,L,Cc,,CAUSE2 BUTTON,"Select a new variable to trace",2,64,40,0,L,Ss,SPECIAL>SETWBITEM|POPULATION&SPECIAL>VARSEL ECT|New variable for tracing BUTTON,"? Help ?",2,71,40,0,L,,SPECIAL>WINHELP|VRHELP.HLP|1900 BUTTON,"Analysis Control",2,78,40,0,L,EeXx,,ANALYSIS TOOL,"GR1",60,50,40,50,,,WORKBENCH>STRIP GRAPH SETWB,"",0,0,0,0,,,,USE Again similar to CAUSE1 but showing uses instead of causes.

Other Examples
Here is a brief description of the other examples.

Demo Disk
The Vensim demo disk is written as a Venapp. It contains a number of different models and demonstrates some of the ways that they can be used. The Venapp intro.vcd contained in the models\sample directory will start the program, but the Venapps in the various subdirectories can also be used directly without reference to intro.vcd, although they will return to intro.vcd rather than exiting directly. For simplicity, the demo disk Venapps have been written to use binary forma (.vmf) models. There are several things that are done in the demo disk Venapps that are interesting and you may want to explore these and make use of some of the screens. Resuming from a Prior Run The uban.vcd Venapp (in the models\urban subdirectory) sets up a game starting at the end of a simulation using the SIMULATE>BASED command. This is a useful way to set up a simulation that will run over a historic period, and then allow for policy interventions after that period is run. If you want to do this you should use a binary format (.vmf) model.

78

Optimization The maint1.vcd Venapp (in the models\maint1 subdirectory) allows the user to set up and run an optimization. Running optimization inside of Venapps is not always successful because the optimization can take a long time. At the same time, if the Venapp is being used to make it easy to set up and run things overnight, this can be very useful. Sensitivity Simulations The finance.vcd Venapp (in the models\finance subdirectory) demonstrates how you can setup sensitivity simulations from within a Venapp. Like optimization, this can be very slow.

Vensim Model Reader


The source code for the Version 3 Vensim Model Reader is contained in the venapp\venread subdirctory. With Version 4 we have gone to a non-Venapp based model reader, but the old Venapp code still contains some useful capabilities.

Multiplayer Games
There is a very small Venapp mplayer.vcd in the venapp\mplayer subdirectory that implements a very simple networked multiplayer game using timers and marker files. The example is extremely simple but demonstrates some key ideas that can be used in this type of development.

Screen Updating
There is a small Venapp flicker.vcd in the venapp\flicker subdirectory that demonstrates how to force a screen to update during a simulation.

Dialog Based Changes


There is a small venapp change.vcd in the directory venapp/change that demonstrates how user interaction can change variable values. Note that you have to run a model in gaming mode for this to work.

Moving Beyond
Venapps allow you a rich variety of behavior in a relatively compact framework. The example Venapp we considered in this chapter probably used less than half the available commands. The key in developing a good Venapp, like any other computer application, is to get the functionality required with the minimal complexity. If you are looking to develop interfaces to models that go beyond the capabilities of the Venapp language, you will probably want to look at the Vensim DLL discussed in Chapters 11 and 12.

79

Command Scripts
Vensim is a highly interactive environment for developing and working with models. Nonetheless, there are situations where the ability to execute long lists of commands can be useful. This functionality can be achieved, to some extent, in Venapps, but using Venapp is a cumbersome way to do real batch processing. Vensim provides a simple command script capability to facilitate batch processing. This chapter: Describes how to create and use command scripts. List the functions available for use in command scripts.

Command Files
A command file is a file containing a list of commands. These files have extension .cmd. You can run these command scripts by opening the file with the File>Open Model command, loading the file in the Text Editor and executing File>Run Command or by naming the file when Vensim is called as in: c:\Program Files\vensim "c:\Program Files\vensim]models\dobook.cmd" The file itself is a simple text file with a single command on each line. The commands are a subset of the commands use in Venapps. The list of available commands is described in "Supported Commands" below and also in the table at the end of Chapter 5. NOTE: If you have a path that has spaces in it as the above path does then you will need to put double quotes around the argument to Vensim as shown above. If there are not spaces in the path names the double quotes are not necessary. A command file might contain: SPECIAL>NOINTERACTION SPECIAL>LOADMODEL|big.mdl SIMULATE>SETVAL|initial workforce=20 SIMULATE>RUNNAME|bob1 MENU>RUN|O MENU>VDF2DAT|bob1.vdf|bob1.dat|bob.lst MENU>EXIT This file will load big.mdl, simulate it, and put the results in the ASCII file bob1.dat. Vensim will then close. The first command means that the process will not stop for user interaction such as might occur if, for example, the model big.mdl had a .vif file that referenced a dataset you had deleted. Because you can start Vensim with a command script that will in turn close Vensim, you can treat Vensim as a batch processor. Call Vensim with a command file that does a few things and then closes itself. When the NOINTERACTION option is used, a history of each command executed is written to vensim.err.

Supported Commands
Batch files can contain only subset of the Venapp commands. The following is a list of supported commands:

80

FILE
COPY, CREATE, DECRYPT, DELETE, ENCRYPT, MDL2VMF, RENAME, VCD2VCF, VGD2VGF, VMF2MDL

MENU
DAT2VDF, EXIT, RUN,, RUN1, RUN_OPTIMIZE, RUN_SENSITVITY, SENS2TAB, TAB2VDF, VDF2DAT, VDF2TAB, VDF2WK1, VDF2XLS, WK12VDF, XLS2VDF

SETTING
EXTERNALFUNCTION,SHOWWARNING

SIMULATE
ADDCIN, ADDDATA, BASED, CHGFILE, DATA, MINMEN, OPTPARM, PAYOFF, READCIN, READRUNCHG, RESUME, RUNNAME, SAVELIST, SENSITIVITY, SENSSAVELIST, SETVAL, WRITECIN

SPECIAL
CLEARRUNS, LOADMODEL, LOADRUN, LOADTOOLSET, NOINTERACTION, READCSTOM, READINI.

TIMEAXIS
RESET, SPECIALTIME, STARTTIME, STOPTIME.

Preparing files for use with Vensim Application Runtime


If you are preparing files for use with Vensim Application Runtime you may want to write a simplify this process. The following example does this, placing all the files in a ship subdirectory. Note that you must first create this subdirectory outside of Vensim and make sure it is empty. For example suppose you have a simple venapp flicker.vcd you want to pepare. The following script does this. FILE>MDL2VMF|flicker.mdl !FILE>ENCRYPT|flicker.vmf FILE>RENAME|flicker.vmf|ship\flicker.mdl FILE>VGD2VGF|flicker.vgd !FILE>ENCRYPT|flicker.vgf FILE>RENAME|flicker.vgf|ship\flicker.vgd FIlE>VCD2VCF|flicker.vcd !FILE>ENCRYPT|flicker.vcf FILE>RENAME|flicker.vcf|ship\flicker.vcd FILE>copy|flicker.vts|ship\flicker.vts NOTE The script will fail if the ship directory does not exist or is not empty. What this script does is make binary files from all the source files and then put them in the ship directory with the names of the source files. Renaming in this way allows you to use the same Venapp so you do not have to load .vmf and .vgf files in the Venapp. If you do want to load those files anyway do not rename the model to .mdl with this script. If you have a redistribution license the FILE>ENCRYPT lines will prepare the files for use with the redistributable application runtime.

81

You can use the same technique to prepare files for use with the Vensim DLLs.

82

External Functions
In addition to the variety of built in functions, you can also make use of external functions in Vensim. External functions allow you to define arbitrary computations that can be made of Vensim model variables during a simulation. Vensim passes the external functions values, and the external function uses those values, possibly modifying them, and then returns a value. This chapter: Gives an overview of how external functions work. Describes how to define an external function. Describes how to call external functions. Discusses the use of External Functions in Compiled Simulations Discusses some implementation issues.

NOTE External functions are not available on the Macintosh.

External Function Libraries


When Vensim simulates a model, it makes computations on the model variables and calls to functions when it is appropriate to do so. Since all model variables are floating point variables, and since all functions return floating point variables, there is not much variety in how functions get called, except in the number of arguments. External functions are described using a Windows Dynamic Link Library or DLL file. When this DLL is loaded, Vensim requests from it a list of functions and their attributes by calling the user_definition function. Once this has happened, Vensim recognizes those functions just as it would recognize built in functions. During model simulation when a model contains an external function, Vensim makes a call to a routine in the DLL called vensim_external passing it information including an index for the function. The DLL is then responsible for doing the appropriate argument conversion and calling the external function. You can have more then one external function library, but you can only load one at a time. The external function library that will be used is shown in the Startup tab of the Global Options dialog accessible from the Tools>Options command. You can select a new library to change this. When you change the external function library you should close and reopen any models you are working with. Each library can have up to 32000 distinct external functions defined. NOTE By default Windows hides the names of .dll files so that when you try to select an external function library you may find that the names do not show up in the file selection dialog. To see .dll files open Windows Explorer and select the Options or Folder Options menu item on the View menu. There should be a Check Box (possibly on the View tab) to show or not show Hidden and System files. .dll files are considered system files so make a selection that does show those.

Defining External Functions


In order to define external functions, you will need access to a C/C++ compiler capable of generating Windows Dynamic Link Libraries (DLLs). The use of C/C++ is not mandatory, since there are other languages with which you can generate DLLs. If you wish to use another language please be sure that the variable types supported by that language are the same as those in C, or are appropriately recast.

83

Vensim DSS ships with a sample external function library venext.c. It is highly recommended that you copy this file and modify it to add in your own functions, or at least use it as an example. The file contains sufficient internal documentation to make this a straightforward task. The documentation contained in this section provides an overview of what the external function library does, but is not sufficiently detailed to be of use as a guide to programming external functions unless you have considerable Windows programming experience. For Vensim DSS16, The external function library must contain LibMain and WEP in accordance with standard windows library practice. LibMain is called only once at the time the DLL is loaded (at Vensim startup). WEP is called on exit. Neither of these routines need do anything, but they are available for special initialization and termination tasks if you wish to perform these. These functions are not required for DSS32. LibMain is not called by Vensim directly, but by Windows as part of the library loading procedure. When Vensim loads the external function library, it will first call the function version_info. This function must be exported by the DLL and should return the version number as an int. If this function does not exist, is not exported, or if it returns a value other than EXTERN_VCODE as defined in Vensim.h, the library will be unloaded and no external functions will be available. EXTERN_VCODE is currently 400 and 401 for double precision, but check Vensim.h to determine the correct value to use. NOTE It is important that the exported functions be named in an export definitions (.def) file included in your project definition. The file venext.def is should be all that you need.

version_info
int _export PASCAL version_info() { return(EXTERN_VCODE) ; } Where EXTERN_VCODE is defined in Vensim.h and will be updated with new releases of Vensim.

funcversion_info
This function must be exported and included in the .def file for your project. int _export PASCAL funcversion_info() { return(1) ; } This function is intended to allow you to pass information about the version of your external functions. It is not used in the current release of Vensim but is kept as a placeholder. If it does not exist it is assumed that it would return 1.

set_gv
void _export PASCAL set_gv(GLOB_VARS *vgv) { GV = vgv ; } This function provides the address of the GLOB_VARS structure that contains information about the simulation state and also other information such as the location of active Lookup table values. If the function does not exist or is not exported Vensim will not call it.

84

user_definition
Once Vensim has the library successfully loaded, Vensim calls the function user_definition. This function must be exported and has the following format (note that the format is different from what it was in earlier releases): int _export PASCAL user_definition( int setup_index, char **sym, ` char **arglist, int *num_args, int *num_vector, int *func_index, int *dim_act, int *modify, int *num_loops int *num_literal, int *num_lookup)
setup_index is the index for the call to user_definition. Vensim passes indices starting from 0 and incrementing by 1 each time. Vensim will continue to call user_definition until a 0 value is returned. sym is the name of the function as you want it to appear in Vensim. You should assign this a value using *sym =. arglist is a string that will be placed inside of the parenthesis () for the function when you select the function name in the Equation Editor. To be consistent with the rest of Vensim this should be a string in the form " {arg1_desc} , {arg_desc} " starting and ending in a space with spaces around commas and curly brackets around the argument descriptions. Also there should not be any spaces in the argument descriptions so that double clicking on an argument description allow easy replacement. You should assign arglist a value using *arglist =. num_args is the number of arguments the function takes. You should assign this a value using *num_args =. If you are using user_loop functions, as discussed in the next section, this value is the number of arguments in the Vensim function, and will be one less than the number of arguments Vensim uses when calling the function library. num_vector is the number of vector arguments the function takes. You should assign this a value using *num_vector =. Vector arguments, instead of being passed as floating point numbers are passed a pointer to a VECTOR_ARG structure (see Vector Arguments below). These are useful when dealing with arrays of elements. Vector arguments are passed after Literals and Lookups but before any regular arguments. func_index is the index of the function. This must be a number between 0 and 32000. You should use *func_index= to assign it a value. Vensim uses this value to tell the library which function is desired. dim_act is reserved for future use. value. You should not assign it a

modify is a flag to tell Vensim whether or not the function may modify its vector arguments. This flag should take on one of three values: 0 to indicate that it is a normal function that does not modify values; 1 to indicate that it will modify values; 2 to indicate that it will modify values and also serve as the solver for a simultaneous set of equations. The last of these is analogous to the FIND_ZERO function described in the Reference Manual. See

85

Modifying Values below for more discussion. value.

Use *modify= to assign a

num_loops tells Vensim how many loops the function expects to manage computation for. See the section on User Loops below for more details. Assign this a value using *user_loops =. If you mark a function as controling loops the left hand side variable will also be passed to the function as a VECTOR_ARG. Note that in order to mark a function as a Constant Definition function you should assign -1 (CONSTDEF_MARKER) to num_loops. To mark a function as a Data Definition function assign 2 (DATADEF_MARKER) to num_loops. See the section on Constant and Data definition functions. num_literal tells Vensim how many string liiterals will be passed to the function. This is normally 0. If literals are passed they are passed before either Lookups or Vector arguments and they are passed as char *. Assign this a value using *num_literal =. num_lookup tells Vensim how many Lookup functions will be passed to the function. Assign this a value using *num_lookup =. Lookups are passed as pointers to TAB_TYPE - see Lookup Arguments below. Lookups are passed before any vector arguments but after any literal arguments

Return value The return value should be 1 if assignments were made and 0 if nothing was done. Once Vensim receives a 0 return it will stop calling the function. The user_definition function defines the nature of the function. In order to actually call an external function during simulation, Vensim uses the vensim_external function.

vensim_external
int _export PASCAL vensim_external( VV *val, int nval, int funcid)
val is the vector of arguments passed to the external function. is a pointer to the union VV described below. It

nval is the number of elements in val. If user loops is set, it will exceed the number of arguments set by user_definition. funcid is the id of the function being called. Typically you will perform a switch on this to evaluate the function. VV typedef union { /* arguments are loaded on a vector and passed either */ COMPREAL val ; /* by value as floats or */ VECTOR_ARG *vec ; /* by address - normally the first element in an array */ TAB_TYPE *tab ; char *literal ; CONSTANT_MATRIX *constmat ; DATA_MATRIX *datamat ; } VV ; VV is a union of the different argument types. If the function being called has num_loops > 0 then the first element will be VECTOR_ARG and contain values for the left hand side variable. If the function has num_loops == -1 (a Constant Definition function) the first argument will be a

86

CONSTANT_MATRIX, and if num_loops == -2 is will be a DATA_MATRIX. (Remember that whenever num_loops is nonzero an additional argument will be passed first containing information about the left hand side variable). If the function being called has num_literal > 0, then the next num_literal elements will be char *. If the function being called has num_lookup > 0, then the next num_lookup functions will be TAB_TYPE *. If the function has num_vector > 0 then the next num_vector elements will be VECTOR_ARG *. The remaining elements, if any will, be COMPREAL (float or double for the double precision version of Vensim). It is often useful to pass integer values to function. To do this we recommend an explicit recast with rounding as in: matrix_size = (int)(val[2].val + .5) ; Return Value If the function call is successful it should return 1. Return 0 in case of an error this will be reported as an error in the simulation. The value computed by the function itself should be returned by assigning it to val[0].val. This is true even if val[0] was referencing a vector. Vensim makes no further use of val, except to reference val[0].val.

Compiling and Linking


Compiling and linking are done using the commands of your C compiler. The example ship with make and workspace files for Microsoft C/C++ versions 4 (venext4.mak) and 6 (venext6.dsw and venext6.dsp). The example batch files batch file mscvxt32.bat are designed to compile and link the file using 32 bit Microsoft C compilers. To compile and link you will need to include the files venext.c, venext.def. You will also to use vensim.lib when linking with Vensim. If your linker will not work the vensim.lib file that ships with Vensim you will need to create an exports library from vensim.def and vensim.c which contains shell versions of all the exported functions.

Calling External Function


Inside of Vensim, external function are referred to exactly the same way built in functions are. You simply call the function with the number of arguments you want. If the external functions you are using have user loops, vector arguments, or are marked as modifying values things get more complicated. Arguments are always passed in the order Literal, Lookup, Vector, Value. You can not pass arguments in any other order. For functions that are marked as self looping an additional Vector argument is added before any of the declared arguments. Because of this a self looping function with 4 arguments in Vensim will be called with 5 arguments and the first of these will be a VECTOR_ARG for the left hand side variables.

Literal Arguments
Literal arguments are passed as strings and must be first in the list of arguments. The strings passed should not be modified. The enclosing single brackets used in Vensim are not included.

Lookup Arguments
Lookup Arguments should appear before any Vector arguments or regular arguments but after any literal arguments. They are passed as a pointer to a TAB_TYPE structure. typedef struct tag_tab_type { REAL base ; /* the base val */

87

REAL xgap ; /* the time gap to the next x value */ REAL ygap ; /* the value gap the next y value */ REAL lstx ; /* the x value of the base */ REAL nextx ; /* the x value of the next entry after base */ BLK_OFFSET x ; /* pointer to the x values */ BLK_OFFSET y ; /* pointer to the y values */ V4BYTES curind ; /* the current index value (matches base) */ V4BYTES lstind ; /* the number of value for the lookup */ TABLE_RANGE range[1] ; /* used for reporting over under and in messages */ } TAB_TYPE ; To reference the values for the x and y elements use xvals = (float *)(GV->tabbase+tab->x) ; yvals = (float *)(GV->tabbase+tab->y) ; NOTE You should use REAL or float here not COMPREAL since the lookup table values are floats even for the double precision version of Vensim. The other elements of the TAB_TYPE structure are used internally by Vensim to speed computation and manage error messages. If you are using the Lookup in any built in Vensim function you should not change any other values as this will cause unpredictable behavior.

Vector Arguments
Normally a function takes several numbers as arguments and returns a number. Only a few built in Vensim functions, such as, ALLOC_P take vector arguments. While ALLOC_P is an exception among built in functions, vector arguments are used more commonly with external functions. When you request vector arguments instead of a number, you get a pointer to a number. Typically, the reason you would want a pointer is to evaluate a series of numbers. For example you might define VECTOR_AVERAGE as a function to take the average value of a vector. To do this you would define VECTOR_AVERAGE to have two arguments, and one vector argument. In Vensim you might have: city : ALBANY,NEW YORK,ROCHESTER ~~| average price = VECTOR_AVERAGE(price[Albany],ELMCOUN(city)) ~~| The external function would receive a vector of floats and the number of elements in the vector and return the average over that number of elements. This simple example would be equivalent to average price = SUM(price[city!])/ELMCOUNT(city) ~~| With external functions you are not limited to taking averages and some things that are very difficult to do in Vensim are very easy to do when using external functions. VECTOR_ARG Vector arguments are passed as a pointer to a VECTOR_ARG structure: typedef struct { COMPREAL *vals ; const COMPREAL *firstval ; const DIM_INFO *dim_info ; const char *varname ; } VECTOR_ARG ; vals is address of the value for the model variable. In the example above it would be the address of price[Albany]. Vensim arrays are stored as vectors with the last subscript varying most quickly so that arrays are also passed as a pointer to one of the elements (often the first) in the array.

88

firstval is the address of the first value for the variable being passed. You should never modify a value that precedes this. You can use an inequality test vals + offset < firstval to check that you are not about to do this. dim_info is a pointer to a dimension information structure. This can be used to determine the range of the vector as described below. varname is the name of the model variable (with no subscripts) for the argument. The example venext.c file has a function called validate_vector_arg that can be used to make sure operations you will be performing will not go outside the range of the variable being passed. If this function detects an error it generates a floating point exception. This will cause the simulation to terminate and Vensim to report the equation in which the error occurred. DIM_INFO No values in the DIM_INFO structure should ever be modified. Some are useful for determining how to process a vector argument and those are detailed below. typedef struct { V4BYTEU reserved ; V4BYTEU tot_vol ; /* the total size */ VAL_OFF dim[MAX_DIM] ; /* total size of a dimension */ VAL_OFF dim_vol[MAX_DIM] ; /* the total volume for one subscript */ ST_INDEX fam[MAX_DIM] ; /* families for elements */ V2BYTES tot_dim ; /* number of elements */ V2BYTES align ; } DIM_INFO ; tot_vol is the total volume of the variable being passed. For example, a 3 x 5 matrix would have a volume of 15. Only elements of vals that are >= firstval and < firstval+tot_vol are valid. dim is the number of elements in each dimension. dim_vol is the volume that an increment in the subscript value covers. For example in a 4*3x5 array the third subscript has a volume of 1, the second a volume of 5 and the first a volume of 15. tot_dim is the total number of dimensions used. This is a number between 0 (for a scalar) and MAX_DIM which is 8.

Constant Matrices
Instead of being passed a Vector Argument Constant Definition functions are passed a pointer to a CONSTANT_MATRIX structure as their first argument (all remaining arguments must be literals). typedef struct { unsigned long keyval ; char *varname ; REAL **vals ; long ncol ; long nrow ; } CONSTANT_MATRIX ;
keyval is must be equal to CONSTANT_MATRIX_KEY (0xF722438E). You can use this to check that you have received a valid CONSTANT_MATRIX.

89

varname is the name of the variable, fully subscripted with the first subscript to have its value filled. This is passed to make it easier to report errors, and can also be parsed if this is appropriate.

vals is the matrix of vals to be filled. When a Constant Definition function is first called each row of this matrix will be empty (that is vals[0] will be null, as will vals[1] and so on). You can call vensim_alloc_simmem and pass the CONSTANT MATRIX received as the second argument to allocate the rows.
ncol is the number of columns to be filled - this is passed from Vensim and is determined by the last varying subscript. for scalars this will be one. nrow is the number of rows to be filled - this is passed from Vensim and is determined by the first varying subscript for scalars and vectors this will be one.

Data Matrices
Instead of being passed a Vector Argument Data Definition functions are passed a pointer to a DATA_MATRIX structure as their first argument (all remaining arguments must be literals). typedef struct { unsigned long keyval ; char *varname ; REAL *timevals ; REAL **vals ; long nvar ; long ntime ; } DATA_MATRIX ;
keyval is must be equal to DATA_MATRIX_KEY (0x33F27413). You can use this to check that you have received a valid DATA_MATRIX. varname is the name of the variable, fully subscripted with the first subscript to have its value filled. This is passed to make it easier to report errors, and can also be parsed if this is appropriate. timevals is the vector of times to be filled. This will be null when the function is first called. You need to allocate this - most easily by calling vensim_alloc_simmem after specifying ntime.

vals is the matrix of vals to be filled. When a Constant Definition function is first called each row of this matrix will be empty (that is vals[0] will be null, as will vals[1] and so on). You can call vensim_alloc_simmem and pass the CONSTANT MATRIX received as the second argument to allocate the rows.
ncol is the number of columns to be filled - this is passed from Vensim and is determined by the last varying subscript. for scalars this will be one. nvar is the number of variables (rows) be filled - this is passed from Vensim and is determined by the first (and only) varying subscript in the equation using the Date Definition function. For scalars this will be one. ntime is the number of times that will be returned. The function must fill in a value for this, normally before calling vensim_alloc_simmem. Note that the entire vals matrix should be filled in. If a particular variable is not available at a particular time assign it a value of NA at that time and it will be purged when Vensim interprets the data.

Modifying Values
If you ask to have one or more arguments passed as Vectors you can choose to modify values. And you can also choose whether or not to tell Vensim that you are going to do this. In general, the modification of values is not likely to cause difficulty, though you do need to be cautious about

90

modifying Level values, especially if you want to use an integration technique other then Euler Integration. There is, however, one thing that can really mess up and that is computational sequence. If you write the equations: a = x x = 1+Time*0 y = f1(x) z = x Vensim reorders them for execution to the order: x = 1+Time*0 a = x y = f1(x) z = x You would expect a = 1 and z = 1. However, if f1 modifies the value of x (say setting it to 0), z will be 0, and a will be 1. The algorithm that Vensim uses to order equations for execution fails when external functions can change values at will. If f1 is marked as modifying values then Vensim will reorder these equations as follows: x = 1+Time*0 y = f1(x) a = x z = x Thus both a and z will be 0. Marking functions as modifying values is not, unfortunately always enough. Suppose that you have two functions, f1 and f2 marked as modifying values. Then the equations x = 1+Time*0 a = f2(x) y = f1(x) z = x will be executed in precisely this order. If f2 does not actually change x but just return its value and f1 sets the value to zero we will again get the erroneous result a = 1 and z = 0. The long and short of this discussion is that functions that modify values can give unpredictable results. Even from this example it should be clear that there is no "correct" ordering algorithm. If functions that modify values are used in a controlled manner with clear thought given to the computational implications they can be quite useful, but they are dangerous. Whenever possible, use the User Loops approach instead.

User Loops
If you mark a function as having a number of loops to manage it is a signal to Vensim to let the function manage the last num_loop subscripts loops that Vensim would normally manage. Consider the matrix inversion routine in the example external functions. In Vensim you write the equation input : i1,i2,i3,i4 ~~| output <-> input ~~| a_inverse[output,input] = MATRIX_INVERT(a[output,input]) ~~| Since the matrix inverse function is marked has managing 2 user loops, Vensim will pass a vector argument pointing to the left hand side (a inverse) and then an argument pointing to a. Instead of doing a nested for loop on output and input, Vensim will simply call the function once, and expect all of a_inverse to be filled in. Vensim assumes the behavior of the external function is proper.

91

Vensim initializes all variables to have the value NA so if an external function fails to update all elements some may be left with this value. To continue the discussion a little bit, if you were to write the Vensim equation region : east,west ~~| a_inverse[region,output,input] = MATRIX_INVERT(a[region,output,input]) ~~| Vensim would call the external function MATRIX_INVERT twice, once for EAST and once for WEST. It is important to note that Vensim arrays are stored as Vectors with the last arguments varying fastest (this is like C and unlike FORTRAN). If, for example, you were to use the equation a_inverse[output,input,region] = MATRIX_INVERT(a[output,input,region]) ~~| You would get nonsense results. Be extra careful when using multiply subscripted variable in user loops. NOTE if you have set user_loops then the function call must set the return value to be the value of the first element of the array. Otherwise this value will be overwritten by the return value when Vensim finishes the function call.

Constant and Data Definition Functions


Vensim treats external functions as active computations on the inputs. While it is possible to write functions that have memory of previous calls (see the INTERNAL_ROR example in venext.c) Vensim treats the function as a simple computation on current values. While this is usually appropriate, there are circumstances where you might want to tell Vensim to treat a function as defining a particular type of variable. Currently you can do this for Data variables and Constants. You mark such functions as special by giving them a number of user loops that is less than 0. Use -1 for a Constant Definition function (this is the definition of CONSTDEF_FUNC in vensim.h) and -2 (DATADEF_FUNC) for a Data Definition function. Constant definition functions are called whenever a model is checked, and just before the model is simulated. They are passed information about the array they are expected to populate. After Constant Definition function has been called you may still change the values of constants onscreen or using changes files. Data definition functions are called at the beginning of the simulation process. The allow you to populate a time valued array of data to be used during the simulation. Constant and Data Definition functions can only be passed literal arguments. They make it easier to get information from databases and other external sources without severe performance penalties. There are example of these types of functions in venext.c.

Notes on Memory Alllocation


The use of Constant and Data definition functions require that memory be allocated to store information. For Constants, this memory is a 2 dimensional array of value (even if the function is being invoked for a scalar). For Data the memory is an array with a number of rows determined by the subscript used when the function is called and a number of columns determined by the number of times available. In addition, Data requires that a Time vector be allocated and populated. The easiest way to allocate memory is to use the vensim_alloc_simmem function described below. For constants this can simply be called with the information passed from Vensim. For Data, you must first determine the number of time values to include, then call this function.

92

The memory that is allocated to store Data (including the time vector) will be referenced again and again and must not be reused in a different call to a Data Definition function. This restriction does not apply to Constant definition functions since the memory used to pass constant arguments will be accessed once directly after the call to the Constant Definition function and then not referred to again. If you use the vensim_alloc_simmem function to allocate memory you do not need to free the memory. Vensim will automatically do this when the simulation has been completed. If you use an alternative allocation technique you will need to free the memory in your simulation_shutdown routine (when it is called with finalflag==1).

Global Variables
If you have included the set_gv function then you can make use of the elements of the GLOB_VARS structure. This structure is used for both compiled simulations and external functions. You should not make any changes to any of the elements of this, but some of the values can be very useful for referencing. Those elements are discussed here. BBASE tabbase the base memory position for table values. Use (REAL *)(GV>tabbase+tab->x) to access the x axis and (REAL *)(GV->tabbase+tab->y) to access the y axis. COMPREAL time the current simulation time. COMPREAL time_step the current simulation Time Step. Remember that TIME_STEP can be a variable so this might change. COMPREAL time_plus this is the current simulation time plus Time Step/2. It is useful for doing comparison of the current time with other values without risking incorrect results because a floating point == returns 0. COMPREAL time_minus this is the current simulation time minus Time Step/2. Also useful for using >. Instead of targtime == GV->time use argtime > GV->time_minus && targtime < GV->time_plus). COMPREAL final_time is the FINAL_TIME for the simulation. COMPREAL saveper is the SAVEPER for the simulation. char simulation_state is the current state of simulation. It takes on the values: SS_IDLE(=0) to indicate nothing is happening. SS_ONSCREEN(=1) to indicate that the user is making changes on the screen. SS_LOCKED(=2) to indicate that there is no more user interaction. SS_INIT(=3) to indicate that initial values are being computed. SS_ACTIVE(=4) to indicate that active equations are being computed. SS_INTEG(=5) to indicate that integration is occurring.

If you need to do something at the time of initialization test to see if the state is SS_INIT. In the SS_INTEG state, which is only invoked for Runge Kutta integration technique, you may want to have the function behave differently - certainly any messages or other output should be suppressed. char gaming_state specifies the state of a gaming simulation. It is one of: GS_NONE(=0 ) to indicate that Vensim is not in a gaming state. GS_PREP(=1) to indicate that the game results must be prepared for storage for the first time. GS_CONTINUE(=2) to indicate that a game is continuing for another step.

93

GS_FINISHED(=3) to indicate that the model has been gamed to final time. GS_STARTING(=4) to indicate that the game is just being started or has just been backed up.

char integ_type specified the integration technique being used. It can be one of: IT_EULER(=0) for Euler integration. IT_DIFFERENCE(=2) for Difference Equations. IT_RK2F(=3) for fixed step size second order Runge-Kutta integration. IT_RK2(=4) for variable step size second order Runge-Kutta integration. IT_RK4F(=5) for fixed step size fourth order Runge-Kutta integration. IT_RK4(=1) for variable step size fourth order Runge-Kutta integration.

char simulation_type specifies the type of simulation being made. It can be one of: ST_NORMAL(=0) for a normal simulation. ST_PARTIAL(= 1) for a partial model simulation. ST_GAME(=2) for a gaming simulation. ST_REALITY_CHECK(=3) for a Reality Check simulation.

Memory Management
Vensim provides a simple memory allocation function that is appropriate for allocating memory that will remain valid while a simulation is in progress, and then automatically be freed. void* PASCAL vensim_alloc_simmem(DATA_MATRIX *dm,CONSTANT_MATRIX *cm,V4BYTEU bytes) ;
dm a pointer to a DATA_MATRIX structure. Before calling vensim_alloc_simmem you need to fill in the number of times in the DATA_MATRIX (the number of variables will have been filled in by Vensim). The memory that is allocated will be accessed throughout the simulation so it is not recommended that you use an alternate memory allocation mechanism for data matrices.

cm a pointer to a CONSTANT_MATRIX structure. Both the number of rows and columns required in a CONSTANT_MATRIX are specified by Vensim before it passes the structure to an external function. The use of the callback to vensim_alloc_simmem is designed to allow you to use an alternate memory allocation mechanism. The memory required for a constant will only be referenced once, and before any other external functions are called. Because of this you can use the same memory for different calls to constant definition functions without problems.
bytes is the number of bytes of memory to allocate. The return value is a pointer to those bytes.

Return Value: vensim_alloc_simmem returns a pointer to the amount of memory specified by bytes (and initialized to zero). If memory allocation fails Vensim will throw a fatal error and exit. Thus you do not need to check the return value. If bytes is 0 then the function returns NULL. Note that vensim_alloc_simmem would normally only be called with one nonnull argument. You can, however, pass two or all three and it will do the allocation for each nonnull argument it receives.

Error Handling
Vensim provides a simple function to send error messages to the user. void _export PASCAL vensim_error_message(int severity,char *str) ;

94

severity - the importance of the message. It should be one of WARNING (3), VERROR (5) or STOP (8). These constants are defined in vensim.h. str - a string containing the message to send. STOP messages result in a dialog box being displayed. VERROR and WARNING messages are displayed in the simulation error log.

Startup and Terminate Routines


In addition to the required functions described above you may include and export two optional functions that will be called before and after simulations occur. It is often useful to do some startup and termination activity. This might be the allocation and discard of storage, resetting global values or other things. To do this you should include in your external function library simulation_setup and simulation_shutdown. int _export PASCAL simulation_setup(int iniflag) This function is called before simulating the model. iniflag is 1 if the simulation is being prepared and vectors allocated, and 0 if the simulation is about to start. If any error conditions are detected, it should call vensim_error_message(VERROR,...) as described above in order to terminate the simulation. This function should return a value of 1 to indicate success and 0 to indicate failure. If simulate_setup returns 0 when iniflag is 1 then the simulation will be aborted. When iniflag is 0 the return value is ignored. int _export PASCAL simulation_shutdown(int finalflag) This function is called after simulation. If finalflag is 0 then computations have just finished. IF finalflag is 1 then data storage has been completed and simulation memory is about to be freed. In a normal simulation these functions are called in the sequence: simulation_setup(1) ; simulation_setup(0) ; simulation_shutdown(0) ; simulation_shutdown(1) ; For an optimization, sensitivity or SyntheSim run, the middle two function calls are repeated for each simulation that is made.

External Function Library Files


When you install the Compiled Simulation/External Functions option there will be a number of files created. These files include: mscvxt32.bat - batch files for compiling venext.c with Microsoft C compilers. venext4.mak, venext6.dsp, venext6.dsw make files for creating external function with Microsoft C/C++ version 4 and Microsoft C/C++ version 6. These files are preferred to using batch files. venext.c - sample source code for defining external functions. This file contains additional internal documentation. vensim.h - definitions and function prototypes for use with external functions. This file is also used for compiled simulation.

95

vensim.lib, vensimdp.lib library files to link with in order to make your dll. The vensimdp.lib file is for use with the double precision version of Vensim. vensim.c - a file containing stubs for Vensim's exported functions. Use this to create your own vensim.lib file if your linker does not work with the vensim.lib file shipped with Vensim. venext.dll - the compiled sample external functions ready to be run with Vensim. venext.def - the definition file used by the linker when creating venext.dll. extern.mdl - a small model calling the external functions in order to demonstrate their use.

External Functions in Compiled Simulations


External functions should work fine in compiled simulations. Vensim will create a function stub in the C code and automatically redirect the call to the external function library just as it would for an interpreted simulation. Basically you don't need to worry about that. Earlier versions of Vensim required that you add in additional .obj files to link the compiled simulation with. This is not recommended practice. However, it is still possible to do this by defining LINKEXTERN in vensim.h.

External Functions and Venapps


Once you have created and loaded the external functions they will be available with any simulation you make including simulations from a Venapp. If you are using External Functions for an application you are distributing using the Vensim Redistribution kit or the Vensim Application Runtime you should include the external function library in the same directory as the model and use the Venapp command SETTING>EXTERNALFUNCTION|dllname.dll. The Vensim Application Runtime is also named Vensim.exe (or Vensimdp.exe) so the same DLL library will work without modification.

External Functions and the Vensim DLL


The full Vensim DLL and its redistributable analog also support external functions (the minimal DLL does not). However, to use external functions with these it is necessary to link your external function DLL with a different .lib file. The DLL libraries have names corresponding to the respective Vensim DLL. These are: vendll32.dll/vendll32.lib - The 32 bit full DLL and also the DLL available with the Vensim Application Runtime. These require Windows 95/98/2000 or NT. vendlx32.dll/vendlx32.lib - The redistributable DLL that is part of the redistribution license. vdpdll32.dll/vdpdll32.lib, vdpdlx32.dll/vdpdlx32.lib are the double precision versions of the preceding libraries.

NOTE The treatment of DLL names is different from that of Version 3 of Vensim. You should not rename any of the .lib file or .dll files but use them with the names they are shipped with. It is strongly recommended that you name your external function library file to indicate which Vensim configuration it is intended to work with.

96

Dynamic Data Exchange


Dynamic Data Exchange is not Available on the Macintosh.

Using Vensim as a Server


You can use Vensim as a DDE server from other applications if you want to get values of different variables or make Vensim take some action such as simulating a model. As with other DDE communications, you must first establish a link, and then send messages across that link. The details on how you do this will depend on the software that you are working with. Vensim does not support the pasting of DDE or OLE links.

Establishing a Link
To establish a link with Vensim you should use the server name "Vensim" and any topic name. Vensim ignores the topic name. If you want to load a specific model you can send a command to Vensim to do this.

Executing Command
You can pass the same set of commands using DDE as are available in command scripts as described in Chapter 6. To pass a command, use the same format as you would for command scripts, such as [SPECIAL>LOADMODEL|c:\vensim\models\world.mdl] The use of square brackets around the commands passed through DDE is not required by Vensim but is considered standard. It is good practice to include them as there are applications such as Excel which will hang and wait for you to close Vensim if you send a command without the square brackets.

Getting Values
You can get values for model variables using the same conventions that are used for custom reports and graphs as described in Chapter 14 of the Reference manual. That format is varname&runname#timebase@time%format?value=label

Hot Links
Vensim supports both the WM_DDE_REQUEST and WM_DDE_ADVISE messages. The latter, which creates a hot link, is not always that easy to set up. If a hot link is established, Vensim will update it at each SAVEPER during a simulation, and also when the list of runs is changed or changes are made to the time axis.

Excel Example
The Excel file ddeserv.xls contained in the DDE subdirectory demonstrates how DDE can be used to control and get values from Vensim. To use this example you must first start Vensim. The functions used to manage DDE are: Dim DDE_channel As Integer Sub StartupDDE() DDE_channel = Application.DDEInitiate("VENSIM", "System") End Sub

97

Starts Vensim - the topic name is arbitrary. Sub LoadVensimModel() varstr$ = "[SPECIAL>LOADMODEL|" + Cells(2, 7).Value + "]" Application.DDEExecute DDE_channel, varstr$ End Sub Loads the model name typed into the cell 2,7 (G2) using an execute command. Sub SetConstant() varstr$ = "[Simulate>SETVAL|" + Cells(5, 4).Text +"="+ Cells(5, 5).Text + "]" Application.DDEExecute DDE_channel, varstr$ End Sub Reads a constant name and value from the spreadsheet and uses SETVAL to set the value for it in Vensim. Sub Simulate() Application.DDEExecute DDE_channel, "[MENU>RUN1|O]" End Sub Simulates the model. Sub GetValue() Dim returnList As Variant varstr$ = Cells(8, 4).Text + "@" + Cells(8, 5).Text returnList = Application.DDERequest(DDE_channel, varstr$) Cells(8, 6).Value = returnList(LBound(returnList)) End Sub Gets a value for the variable named at the time specified in the spreadsheet. Sub StopDDE() Application.DDETerminate DDE_channel End Sub Stops the DDE communication. If you try the spreadsheet you can press the buttons in order. You can change things and press intermediate buttons any number of times, but you should press the open and close communications only once. Depending on what you are doing you might want to open and close communications within each command as this is not that slow and will save you the trouble of remembering whether or not you have done so.

Using Vensim as a DDE Client


In addition to having Vensim act as a DDE server, it is possible to use special Vensim function calls from within external functions to make Vensim act as a client and allow the processing of information by other applications. The following lists the functions available for use from within Vensim. The included example vddeext.c, vddeext.mdl, venext.h and vddeext.xls (all in the dde subdirectory) show how to use Vensim to communicate with an Excel spreadsheet.

int PASCAL vdde_execute(int dde_channel,char *ddecommand) ;


dde_channel - as returned from vdde_initiate. ddecommand - the command you want to execute. return value - 0 on failure 1 on success

98

The vdde_execute command sends a command to the server. The format for these commands is normally the same as the form of a command or macro string for the server enclosed in square brackets. You can send several commands by putting in a \n\r sequence between the commands. Arguments to commands containing commas, parens or quotes should be enclosed in double quotes. Refer to the documentation for your server for more information.

int PASCAL vdde_initiate(char *servname,char *topic) ;


servname -a string containing the name of the server application as in "Excel" topic - a string naming a topic for the server. Often a filename as in "VDDEEXT.XLS" return value - returns a non negative channel id on success or -1 on failure. The returned channel id should be used in all subsequent calls to the vdde... functions. The vdde_initiate function is used to begin a DDE conversation. This is normally called from the function simulation_setup. servname is usually the name of an application and topic the name of a file, but the actually meaning of the parameters depends upon the DDE server you are using.

int PASCAL vdde_poke(int dde_channel,char *item,char *value) ;


dde_channel - as returned from vdde_initiate. item - the name of the item you want to set a value for. value - the value to set for the item. return value - 0 on failure and 1 on success The vdde_poke function sends the DDE server a WM_DDE_POKE message normally setting the value for item to value.

int PASCAL vdde_request(int dde_channel,char *item,char **buf,unsigned max_wait) ;


dde_channel - as returned from vdde_initiate. item - the name of the item you want a value for. buf - a location to put the results. This should be the address of an unallocated char *. max_wait - the maximum time, in milliseconds, to wait for a response from the server before returning an error code. return value - 0 on failure and 1 on success The vdde_request function is used to retrieve data from a DDE server. Because DDE is an asynchronous operation this function will wait for up to max_wait time before returning in order to allow the server time to respond. If the server responds earlier the function will return earlier. On success *buf contains the string received. All data is sent and received as text strings. NOTE *buf points to globally allocated memory managed internally by Vensim. Under no circumstances should you attempt to free this memory or use it elsewhere. Its contents remain valid until a new call to vdde_request or vdde_vrequest or vdde_terminate.

int PASCAL vdde_vrequest(int dde_channel,char **item,char **buf,int nitem,unsigned max_wait) ;


dde_channel - as returned from vdde_initiate. item - the list of names of the items you want a value for.

99

buf - a vector of locations to put the results. This should be declared in the form char *buf[MAXREQ] and passed as buf. nitem - the number of items contained in the lists. max_wait - the maximum time, in milliseconds, to wait for a response from the server before returning an error code. return value - 0 on failure and 1 on success The vdde_vrequest function is used to retrieve data from a DDE server. If you need to retrieve several items from the server this function will be faster to use than multiple calls to vdde_request. On success buf[0] contains the string for the first item, buf[1] for the second and so on. On failure one or more of buf[i] will be null indicating a failure to retrieve that item. NOTE each element of buf points to globally allocated memory managed internally by Vensim. Under no circumstances should you attempt to free this memory or use it elsewhere. Its contents remain valid until a new call to vdde_request, vdde_vrequest or vdde_terminate.

int PASCAL vdde_terminate(int dde_channel) ;


dde_channel - as returned from vdde_initiate. return value - 0 on failure and 1 on success The vdde_terminate function closes a DDE conversation and frees all memory and resources associated with the conversation. dde_channel can no longer be used after a call to vdde_terminate.

void PASCAL vensim_transmit_dde(void) ;


This function is used to force Vensim to transmit all hot data links that have been requested of Vensim acting as a server. Normally this data is transmitted only when Vensim is about to store the current period's simulation. If you are using this mechanism to pass data to another application and also querying that application for values, you should call the vensim_transmit_dde function before requesting values.

100

10

Compiled Simulations

Compiled simulations are not available on the Macintosh.

Vensim Interface
If you have asked Vensim to query you to see whether or not to compile the model for simulation (with the Options>Settings command), you will be asked if you want to compile the model for faster simulation. See Chapter 17 of the Reference Manual for more information on the Options>Settings command.

Answer yes if you want to compile the model, which takes time, and then have it simulate quickly. Answer no if you want to interpret the model, which starts right away but simulates somewhat more slowly. If you answer yes, but do not change the model, the compiled model will be used the next time you do a simulation. Compiled simulations can speed things up quite a bit for large and stable models. If you answer yes, Vensim will invoke the batch file mdl.bat residing in the directory for compiled simulations. This results in the appearance of a Console DOS window in which the compilation takes place. The default mdl.bat will pause if an error is detected. You should see the message:

Under Windows 95/98 you will need to close the DOS window manually. It should close automatically under Windows NT. If errors were encountered this window will remain open and list one or more error messages (see the section on Compile Errors below for discussion of what to do). If necessary, close the DOS window and click on OK in the above prompt. If everything worked the simulation should continue in the same way it would using an interpreted simulation. Note that regular simulation, sensitivity simulation and optimization have separate settings for determining whether to use compiled or interpreted simulation.

Details of the Compilation Process


Vensim performs compiled simulations by creating a Dynamic Link Library (sim.dll that contains the computer code necessary to execute the model equations. Vensim maintains control of the simulation, calling this DLL to compute model values. The DLL, in turn, calls Vensim to evaluate the different functions used.

101

When you ask to have a compiled simulation performed, Vensim orders the model's equations and then creates a C language file mdl.c for these equations. The file contains eight functions: mdl_desc returns a description of the model. comp_rate computes the rates of changes for the levels. comp_delay computes the inputs to delays. init_time initializes to begin a simulation. init_tstep initializes TIME_STEP before beginning a simulation. comp_init computes the initial values of all Levels. Auxiliaries needed to initialize the Levels are also computed. comp_reinit computes the initial values of all equations using the REINITIAL function. comp_aux computes the values of all Auxiliaries, given the values of all the Levels.

Vensim calls mdl_desc to verify the source of the model, init_time to find the starting Time, init_tstep to find the initial value of TIME_STEP, comp_init to initialize levels and then performs the simulation by calling comp_aux and comp_rate and performing integration steps. comp_reinit is only called during resume. The separate init_tstep is used because TIME_STEP can be input as an exogenous driver, and this requires a value for time. Since TIME_STEP is usually a constant, init_tstep is most commonly an empty function. Depending on what you have in the model some of the other functions may also be empty. Because models can be quite large, Vensim places a number of #pragma statements in mdl.c to allow the C compiler you are using to successfully compile the model. The #pragma statements used may cause warnings to be issued by the compiler since Vensim issues the union of the #pragma statements required, and those that cause warnings can be safely ignored. Having written the file mdl.c, Vensim invokes the batch file mdl.bat located in the compiled simulation directory (mdl.bat is discussed further below). This batch file is executed in a DOS style console window. On Windows NT this window will appear and disappear by itself. With Windows 95/98 you will need to close this window manually. If there are any errors encountered while compiling the error messages will go to this window and it will pause waiting for a keystroke to close. See Compile Errors below for what to do next.

Compile Errors
The most common compile error message is a "Bad Command or Filename" in response to the CL command. Usually this means that you have not set up paths to the C compiler correctly. See the discussion of mdl.bat below for more details. Sometimes, however, you will get other error messages and the easiest way to track these down is with this set of steps: 1. Save your model in binary form in the same directory you have installed the compiled simulation files ((normally this is c:\program files\vensim\comp). You do not need to copy any supporting datasets or other files. Attempt to compile and simulate this model.

2.

If step 2 succeeds there is something very funny going on, and the following steps may not be of much help. If it fails, as is to be expected, continue working through these steps. 3. Using the visual interface to C/C++ open the makefile sim.mak contained in the compiled simulation directories as a project. Depending on which version of C you have you may be asked to convert this file to another form, do so saving it as another name. Attempt to build the sim.dll project. You should then be able to more clearly understand what

4.

102

errors have occurred. If there are errors in mdl.c that prevent compilation it is not worthwhile to correct them. mdl.c is generated automatically by Vensim and either the code it is putting out is bad, or something has happened to vensim.h to render the statements wrong. If you did not change vensim.h a call to technical support is called for at this point.

mdl.bat
Vensim ships with a default mdl.bat file that should work with standard installations of Microsoft C/C++ version 6.0. There are also remarked lines in mdl.bat that should work with earlier compilers. If you need something different simply add and remove comment markers (REM statements).

Path
The file mdl.bat controls the compilation process. The most common problem with this file is that the simulation paths have not been properly set. At the very top of this file we recommend that you explicitly set the compilation paths with commands such as: path = "c:\Program Files\Microsoft Visual Studio\VC98\bin;"c:\Program Files\Microsoft Visual Studio\common\MsDev98\bin" set LIB=c:\Program Files\Microsoft Visual Studio\vc98\lib set INCLUDE=c:\Program Files\Microsoft Visual Studio\vc98\include The first two lines must actually appear on a single line. Microsoft Visual C/C++ version 5 and later require two bin directories to be included in the Path statement. Earlier versions required only 1. The default mdl.bat that ships with Vensim has the above path, lib, and include statements, as well as commented out versions of these for earlier compilers. If you installed your compiler into a different directory or drive you will need to make adjustments to the above statements. If you make changes to mdl.bat an original version of this file is kept in mdlorig.bat. NOTE If you are using Windows NT don't put quotes in the path name. The mdl.bat file that ships with Vensim tests for Windows NT and should work on both Windows NT/2000/XP and Windows 95/98/Millennium.

Compilation
The remainder of the mdl.bat file compiles and links the model equations to create sim.dll. CL /c /DWIN32 mdl.c This line compiles mdl.c. If there is an error, or if mdl.obj was not created then the batch file will issue an error message. LINK /DLL /OUT:sim.dll /def:%1sim.def mdl.obj %1simext.obj %1vensim.lib This line links the object file with the Vensim library and the default libraries the Link program will always access. If there is an error it is reported. These commands will work for Micsosoft C compilers. If you are using a different compiler you will need to adjust your command lines appropriately.

Compiled Simulation for the Vensim Application Runtime


The Vensim Application Runtime will look for sim..dll and use it if it exists and matches the model currently in use. Application runtime is not capable of compiling a model so it will interpret the model if sim.dll does not exist or is not from the same model.

103

Compiled Simulations and the Vensim DLL


Compiling models will also work with the full Vensim DLL (the minimal DLL does not support this). However, the Vensim DLL needs the file simdll32.dll (or simdll16.dll for the 16 bit version) not sim.dll to simulate a compiled model. The default mdl.bat file that ships with Vensim contains lines to create simdll32.dll. These lines are remarked out but if you remove the REM at the beginning of the line simdll32.dll will be created. The only different between sim32.dll and sim.dll is the simdll32.dll is linke with vendll32.dll while sim.dll is linked with vensim.lib. Similarly, the redistribution Vensim DLL requires simdlx.dll.

Compiled Simulation with Double Precision Vensim


If you are using the double precision version of Vensim you will need to use slightly different options to create the sim.dll file. You need to define the constant DBLPREC is the comiple line and link with vensimdp.lib instead of Vensim.lib. You also need to output the DLL simdp.dll instead of sim.dll. To make this easier Vensim calls the batch file mdldp.bat instead of mdl.bat for the double precision version of Vensim. This file is nearly identical to mdl.bat but uses the appropriate compile options and link statements.

Compiled Simulation Files


The compiled simulation and external function source files are installed into the same directory. The .lib files are used by both as is vensim.h. The following files relate to compiled simulations: simext.c - the source code connecting Vensim to the model C equations in mdl.c. simext.c contains limited internal documentation. simext.obj, simextdp.obj - object files compiled from simext.c using a Microsoft C/C++ version 4.0 compiler. The simextdp.obj file is for double precision linking. sim.def - the definition file defining sim.dll to be a Dynamic Link Library and showing which functions are exported. vensim.h - an include file required by simext.c and mdl.c defining the different types and structures used in these files. vensim.lib, vensimdp.lib, vendll32.lib, vendlx32.lib, vendll16.lib, vendlx16.lib, vdpdll32.lib, vdpdlx32.lib. Library file containing the exported Vensim functions used by sim.dll. The different files are available so that compiled simulations can be used with different configurations. sim.mak is a make file to aid in tracking problems with compiled simulations. It can also be used to recompile simext.c but is not convenient to use for creating sim.dll since mdl.c is generated automatically by Vensim. mdl.bat, mdldp.bat - batch files used to compile mdl.c and create the DLL in support of compiled simulation.

Other files
In addition to the files you install, using compiled simulations may create some or all of the following files. These files will be created in the directory the model you are compiling is contained in. mdl.c - the C equations representing the model. mdl.obj - a compiled version of mdl.c.

104

sim.dll, simdll32.dll, simdlx32.dll,simdp.dll, sdpdll32.dll, sdpdlx32.dll - the compiled simulation program. This is all that is necessary to actually run the compiled simulation. The different names map to the different versions of Vensim and the Vensim DLL. sim.lrf - a link reference file created in order to link sim.dll.

Compiled Simulations and External Functions


When you compile a model with external functions Vensim will automatically embed in the mdl.c file callbacks to Vensim that access the external function. You should not need to make any changes to Vensim's compiled simulation files. Previous versions of Vensim required that external function bodies be linked for compiled simulations. This can still be done by defining LINKEXTERN in vensim.h but is not recommended.

105

11

Vensim DLL Overview

The Venapp development environment provides a flexible way of developing interfaces to simplify access to models. In some cases you may want to have more complete control over your interface and this is possible using the Vensim DLL. The Vensim DLL is a separate program that can be called from other applications such as Visual Basic, Delphi, Excel and multimedia authoring tools. It allows you to make use of the models you have developed in Vensim and, if appropriate, Vensim's tools for analyzing and displaying information. At the same time it allows you to use whatever development and presentation tools you want. IMPORTANT NOTE Do not ever rename any .dll files or .lib files or they will not work. This is a change from the way things worked in version 3.

Functionality
With the Vensim DLL you can display sketches and tool output, setup and perform simulations and manipulate data. Just as for a Venapp, there is no way to build or modify models, but the Vensim DLL does supply some functionality for retrieving information about a model. There are several functions available for interacting with the Vensim DLL but the majority of control will be exercised by passing the Venapp commands described in Chapter 4 to the vensim_command and vensim_tool_command functions. The Vensim DLL can only use binary format models (.vmf files) and binary format graph definitions (.vcf files). See "Preparing Models" below. To use the Vensim DLL, you must create an application in an environment that can call a DLL. This is quite easy to do and there are a number of examples that come with Vensim to demonstrate how this can be done.

Full DLL
The full DLL will allow you to display sketch and graph information. You can pass most of the commands documented in Chapter 5. The table at the end of Chapter 5 shows which commands are supported in the Full DLL. Many commands, such as the FILE commands, which will work but are better executed directly from your program. If you try to execute a command that is not supported Vensim will do nothing and return 0.

Minimal DLL
The minimal DLL is designed to be as small as possible and does not have any visual capabilities at all. The minimal DLL can be used to simulate a model and retrieve data from a model, but does not have any analysis capabilities. The minimal DLL does support gaming but it does not support sensitivity simulations or optimization. Because the minimal DLL has no visual capabilities, it support fewer commands than the full DLL. The supported commands are detailed in the table at the end of Chapter 5. Essentially, user interaction commands such as SPECIAL>ASKYESNO will not work, nor will the tool and graph commands (CUSTOM, WORKBENCH) be available.

vensim.ini
The Vensim DLL does not maintain any initialization information from session to session. You can use SETTING> commands to change setting or send the full DLL a SETTING>READINI command if you would like to change settings not available with the SETTING> commands. The Minimal DLL does not support any setting changes.

106

Redistribution
The full Vensim DLL that comes with Vensim DSS may not be redistributed. The full DLL is included with the Vensim Application Runtime software that can be purchased in 5-packs and 10packs. The Venapp Developers License also allows for redistribution of the full DLL. The Minimal Vensim DLL may be redistributed without charge as long as the copyright notice: Portions Copyright 1987-2002 Ventana Systems, Inc. appears on the licensing information for the application, or on the opening screen, or in a splash screen for the application. Chapter 13 contains more details on redistribution options.

Function Synopsis
For details on all the functions see the alphabetical listing in Chapter 12.

Commands and Output


vensim_command, vensim_tool_command, vensim_show_sketch The Vensim DLL is used by passing commands to control loading of models and simulation. The majority of the work is done using the vensim_command function and its counterpart vensim_tool_command when there is visual output. The vensim_show_sketch function allows you to present model sketches to the user. Use the vensim_tool_command with the PRINT and EXPORT commands to print and place things into the clipboard.

Simulation Control
vensim_start_simulation, vensim_continue_simulation, vensim_finish_simulation Simulation can be performed by passing the MENU>RUN command to Vensim. An alternative is to use the vensim_start_simulation, vensim_continue_simulation and vensim_finish_simulation commands in order to perform a simulation bit by bit. This allows you to provide the user feedback on simulation progress. If you do not use these commands, Vensim will perform the entire simulation before returning control to your program and this can be time consuming. NOTE It is not possible to perform optimization or sensitivity simulations using these commands.

Data Access
vensim_get_data, vensim_get_dpval, vensim_get_dpvecvals, vensim_get_sens_at_time, vensim_get_val, vensim_get_varoff, vensim_get_vecvals The vensim_get_data function is used to retrieve data from simulation output and converted data files. The vensim_get_val (vensim_get_dpval for double precision) is useful for retrieving information during the progress of a simulation or while gaming is going on. You can call vensim_get_vecvals (vensim_get_dpvecvals for double precision) to get a number of values at once with offsets as determined by vensim_get_varoff. The vensim_get_sens_at_time function retrieves the results of sensitivity simulations.

Structure Access
vensim_get_varattrib, vensim_get_varnames The vensim_get_varnames function can be used get the names of variables in the model. The vensim_get_varattrib function can then be used to retrieve attributes including causes, uses, comments, subscript and equations.

107

Miscellaneous
vensim_be_quiet, vensim_check_status, vensim_get_substring, vensim_get_info, vensim_set_parent_window The vensim_be_quiet function allows you to shut off the visual work in progress elements that Vensim displays during simulation and some other activities. The vensim_check_status function allows you to determine the internal state Vensim is in (simulating, gaming or idle). The vensim_get_info function lets you get information about the current model, loaded runs, available tools and so on. The vensim_set_parent_window allows you to specify a parent window for dialog boxes and other prompts the Vensim DLL brings up. The vensim_get_substring function is a utility function designed to make it easier to work with strings in Visual Basic.

Installation Notes
When you install Vensim DSS, there is an option to install the DLL support files. By default these files are installed in the DLL subdirectory of Vensim. The DLLs themselves are installed in the system32 subdirectory of the Windows directory. This mimics the behavior of the Vensim Application Runtime kit and allows you to call the DLLs without specifying a full path.

DLLs Installed
The installation program will install both the full and minimal DLLs corresponding to the Vensim you are installing. That is, if you are installing Vensim DSS32 for Windows then vendll32.dll and vendlm32.dll will be installed. IMPORTANT NOTE Do not rename these DLLs. You can copy them or put them in different directories, but they must keep the same name. If you move them from the place they are installed they will not be removed if you choose to uninstall Vensim.

Model Files
Before using model files with the DLL program, they must be saved as .vmf files. Graph files must be saved as .vgf files (from Graph Control in Vensim). The DLL version of Vensim cannot open .mdl or .vgd files, nor can it read the default graphs for a model. When you install the DLLs two model files are installed for use with the examples. The DLLs install two models files: WORLDAPP.VMF - The Word Dynamics model of Jay Forrester. WORLDAPP.VGF - graph definitions for this model. POPSUB.VMF - is a subscripted model that is used by some of the examples. The model and graph definition are referenced by the examples and shouldn't be removed.

Library Files
When you install the DLL files a number of libraries will be installed. These libraries correspond to the DLLs with the same names. They are required for linking with C/C++. If you are using a linker that can not process the library files you may need to build your own library files. You can do this using vensim.h, vensim.c and vensim.def that are installed when you install the external function sources. You will need to modify these to correspond to the DLL file you want to use. The library files installed are vendll32.lib, vendlm32.lib, vendlx32.lib, vdpdll32.lib, vdpdlx32.lib. If you install the 16 bit Vensim the 16 bit variants of these are installed. In addition to the library files the include file vendll.h will be installed in the DLL directory. This file contains function prototypes for use with any C or C++ programs.

108

Sample Uses
We have provide samples for using the DLLs with Excel, Java, Visual Basic, Delphi and C++. Note that you need to use a 32 bit development environment to use the 32 bit DLLs and a 16 bit development environment to use the 16 it DLLs. The function prototypes in these samples can be pasted into you applications. DELPHI20 (32 bit) - directory with Delphi 2.0 (32 bit) example. The function prototypes in this example can be pasted into you applications. EXCEL7 (32 bit)- contains an example written in Excel version 7.0 using VB for Applications.. EXCEL97(32 bit) - contains an example written in the Office 97 version of Excel using VB for Applications. MSVC40 (32 bit)- directory with an example of a MFC application calling the Vensim DLL. The project vdllr32.mak can be opened as a make file in Microsoft Visual C++ version 4.0 or later. MSVC60 (32 bit) directory with a MFC for Microsoft application for Visuall C/C++ 6.0 that demonstrates how to use SyntheSim with the Vensim DLL. VBASIC40 (32 bit) - directory with 2 Visual Basic Version 4.0 examples. VENDLL.MAK contains a simple example using the full DLL. VENDLM.MAK is an example using only the functionality of the minimal DLL. The function prototypes may be copied from the (general) section to your own code. JAVA (32 bit)- directory contains an example that uses a Java Application to call the Vensim DLL. This directory also includes an additional DLL - venjava.dll that acts a glue between Java and the Vensim DLL. The example uses the full DLL, but will also work with the minimal DLL (this will require relinking venjava.dll). In Java it is not possible to make use of the sketch or tool display capabilities of the Vensim DLL without using platform specific extensions.

Visual Basic Example


The following examples is in the VBASIC40 subdirectory. Later versions of Visual Basic do not come with built in graphing tools so the graphing part will not work with these. This application is set up so that each button has is a conceptual step. In general it may be better to do more within a function. This example uses the Minimal DLL, but will also work with the full DLL (just replace vendlm32.dll with vendll32.dll in the general section of the code.

109

General (Prototype & Global) Code


Include in this section the prototypes as they are shown in Chapter 12. You can copy and paste the prototypes in the examples. Private Declare Function quietflag As Long) As Private Declare Function As Long Private Declare Function Vcommand$) As Long ......... Note that if you do not use one of the functions it does not matter. Thus the easiest thing is just to copy all the prototypes for use in your code. Dim tval(500) As Single Dim tval2(500) As Single Dim rval(500) As Single Dim rval2(500) As Single Dim tpoints1 As Integer Dim tpoints2 As Integer Some globals are used to store results. vensim_be_quiet Lib "vendll32.dll" (ByVal Long vensim_check_status Lib "vendll32.dll" () vensim_command Lib "vendlm32.dll" (ByVal

Form (Startup) Code


Private Sub Form_Load() result = vensim_be_quiet(2) result = vensim_command( "SPECIAL>LOADMODEL|c:\Program Files\vensim\dll\worldapp.vmf") The vensim_be_quiet call will make the full Vensim DLL act like the minimal DLL. As the form is loaded, the Vensim DLL is told to load a model. For this application no graph sets are required.

110

NOTE Because of the way the Visual Basic development environment manages working directories you need to include the full path for the model in this statement. If you build an executable file you can rely on the program starting in the directory it is in, and leave off the path for the LOADMODEL command.

Simulating the Model


result = vensim_command("SIMULATE>RUNNAME|bobblah") If result = 0 Then Exit Sub num$ = Text1.Text comstr$ = "SIMULATE>SETVAL|POPULATION INITIAL = " + num$ result = vensim_command(comstr$) If result = 0 Then Exit Sub result = vensim_command("MENU>RUN") If result = 0 Then Exit Sub To simulate the model it is useful to supply a run name. The application then reads in the initial value of population and passes that on to Vensim. The MENU>RUN command is passed to perform a simulation. Without any visual activity from Vensim, the user can experience a long delay while simulation occurs. While it would be possible to put up a clock timer or similar object on the Visual Basic side, a better indicator of progress is helpful. The "Simulate under my control" button does this. See "VB Controlled Simulation" below.

Retrieving Data
tpoints1 = vensim_get_data("base.vdf", "population", "time", rval(1), tval(1), 500) tpoints2 = vensim_get_data("bobblah.vdf", "population", "time", rval2(1), tval2(1), 500) The vensim_get_data function will populate arrays with values for time and population. Note that Vensim is very general in its handling of time axis and will not always return the same number of points or the same time values for different runs. Even for a single run, Data variables will be different from other variables.

Plotting Results
If tpoints1 < tpoints2 Then tpoints = tpoints1 Else tpoints = tpoints2 Graph1.DrawMode = 0 Graph1.NumPoints = tpoints Graph1.NumSets = 2 Graph1.ThisSet = 1 For i = 1 To tpoints Graph1.ThisPoint = i Graph1.GraphData = rval(i) Next i Graph1.ThisSet = 2 For i = 1 To tpoints Graph1.ThisPoint = i Graph1.GraphData = rval2(i) Next i Graph1.DrawMode = 2

111

A simple Visual Basic graph capability is used to display results. There are probably more efficient ways to do this, but it is important to stop the graph from drawing itself every time a new point is added and that is why DrawMode is changed twice.

VB Controlled Simulation
Dim timeval As Single result = vensim_command("SIMULATE>RUNNAME|bobblah") If result = 0 Then Exit Sub num$ = Text1.Text comstr$ = "SIMULATE>SETVAL|POPULATION INITIAL = " + num$ result = vensim_command(comstr$) If result = 0 Then Exit Sub ' now do the work result = vensim_start_simulation(1, 0, 1) If result = 0 Then Exit Sub Do result = vensim_get_val("Time", timeval) If result = 1 Then stime$ = timeval Label2.Caption = "Time = " + stime$ Label2.Refresh End If result = vensim_continue_simulation(20) If result <> 1 Then Exit Do Loop Label2.Caption = "Storing Results" Label2.Refresh result = vensim_finish_simulation() Label2.Caption = " " End Sub Controlling simulation is a little more complicated then just launching a simulation, but it provides an opportunity for the user to see the progress of the simulation. Here the progress is displayed with a simple text showing the value for time. The value with which vensim_continue_simulation is called (20) determines the number of TIME STEPS that will be run. A bigger number takes longer, but there is some overhead in calling the functions so using 1 is probably not a good idea.

SyntheSim
It is possible and very fast to use SyntheSim in the full Vensim DLL (SyntheSim is not available in the minimal DLL). To do this issue a command to start SyntheSim. You will probably also usually want to turn off automatic simulation whenever a changes is made. For example, consider the following simple sensitivity simulation using SyntheSim: Dim varvals(200) As Single Dim timevals(200) As Single result = vensim_command("MENU>SYNTHESIM|O") If result = 0 Then Exit Sub result = vensim_command("SYNTHESIM>AUTO|0") result = vensim_get_data("", "Population", "", varvals(1), timevals(1), 200) For initpop = 1 To 9 num$ = initpop

112

SETVAL$ = "SIMULATE>SETVAL|population initial=" + num$ + "E9" result = vensim_command(SETVAL$) vensim_command ("SYNTHESIM>GO|0") result = vensim_get_data("", "Population", "", varvals(1), timevals(1), 200) Next initpop vensim_command ("SPECIAL>STOPSIM") The first call to vensim_get_data is used to signal Vensim that it should be ready to return values for the variable "Population." By turning AUTO off we can set multiple parameters without having Vensim initiate a simulation. We then call SYNTHESIM>GO|0 telling Vensim to simulation, but not write the results. This is very fast. The call to vensim_get_data then fetches the values from memory. Finally we close the process with SPECIAL>STOPSIM to close down SyntheSim. This frees up resources and is good practice.

Starting a Game
Dim timeval As Single result = vensim_command("SIMULATE>RUNNAME|bobblah") If result = 0 Then Exit Sub num$ = Text1.Text comstr$ = "SIMULATE>SETVAL|POPULATION INITIAL = " + num$ result = vensim_command(comstr$) If result = 0 Then Exit Sub result = vensim_command("GAME>GAMEINTERVAL|5") If result = 0 Then Exit Sub result = vensim_command("MENU>GAME") If result = 0 Then Exit Sub result = vensim_get_val("Time", timeval) If result = 1 Then stime$ = timeval Label3.Caption = "Time = " + stime$ End If result = vensim_get_val("Population", timeval) If result = 1 Then stime$ = timeval Label4.Caption = "Population = " + stime$ End If In order to run a game it is necessary to first start the game and then continue it. This is true whether you are using the vensim_start_simulation function or just the GAME>GAMEON command. This code starts the game and then retrieves some indicators of the games status for display.

Continuing or Backing up a Game


Dim timeval As Single result = vensim_command("GAME>GAMEON") 'result = vensim_command("GAME>BACKUP") to back up If result = 0 Then Exit Sub result = vensim_get_val("Time", timeval) If result = 1 Then stime$ = timeval

113

Label3.Caption = "Time = " + stime$ End If result = vensim_get_val("Population", timeval) If result = 1 Then stime$ = timeval Label4.Caption = "Population = " + stime$ End If To continue or backup a game just bass the GAME>GAMEON or GAME>BACKUP commands. Once that has happened the results are displayed.

Ending a Game
result = vensim_command("GAME>ENDGAME") It is simple to end a game. It would also be possible to update the display to indicate that the game is over.

Speeding up a Game
For large models it can be slow to run a game because of the time it takes to store data on each play of the game. This can be speeded up quite a bit by having Visual Basic control the progress of the game. The button labeled "Continue a game without intermediate storage of results" does this. Dim timeval As Single result = vensim_command("GAME>GAMEINTERVAL|250") If result = 0 Then Exit Sub ' now do the work result = vensim_start_simulation(1, 2, 1) If result = 0 Then Exit Sub Do result = vensim_get_val("Time", timeval) If result = 1 Then stime$ = timeval Label2.Caption = "Time = " + stime$ Label2.Refresh End If result = vensim_continue_simulation(20) If result <> 1 Then Exit Do stime$ = 0.05 * (1 - (timeval - 1900#) / 200#) comstr$ = "SIMULATE>SETVAL|capital investment rate normal=" + stime$ result = vensim_command(comstr$) If result <> 1 Then Exit Do Loop Label2.Caption = "Storing Results" Label2.Refresh result = vensim_finish_simulation() Label2.Caption = " " In this case we are computing the value to set a gaming variable to. In general you will want to let the user set values. In this framework if you want to back up in a game, it would be necessary to call vensim_finish_simulation() and then execute the GAME>BACKUP command.

114

Excel Example
Excel uses Visual Basic for Applications and essentially works the same way as Visual Basic. You need to include the Visual Basic prototypes just as was done above. You can also fairly easily interact with the contents of different cells in different sheets. These examples are in the vendll.xls file in the Excel97 subdirectory. It requires the full DLL. Note that Excel does not have the same concept as a form so we use a LOADMODEL command for each of the functions.

Getting Model Variables


Sub Dim Dim Dim Grab_Varnames() buf As String * 512 buf2 As String * 128 length As Integer

We allocate two buffers for holding the results of Vensim functions that fill in string buffers. result = vensim_command(" SPECIAL>LOADMODEL|c:\Program Files\vensim\dll\worldapp.vmf") filter$ = Worksheets("Sheet1").Cells(8, 5).Value vtype = Worksheets("Sheet1").Cells(9, 5).Value The filter and variable type have been taken from the spreadsheet itself and will then be passed to the Vensim DLL. result = vensim_get_varnames(filter$, vtype, buf, 500) The results of the query are now in buf as a series of null terminated strings ending in a double null. We put the required size of the buffer in cell A10. Note that no more than 500 characters will be copied into the buffer, so if this value is larger than 500 it means not all the results were included. Worksheets("Sheet1").Cells(10, 1).Value = result The next task is to copy these results into the worksheet. x = 5 y = 0 Do length = vensim_get_substring(buf, y, buf2, 128) If (length = 0) Then Exit Do Worksheets("Sheet1").Cells(10, x).Value = buf2 y = y + length x = x + 1 Loop The vensim_get_substring function is used to get the values of the Null terminated strings. When this returns 0 it is a signal that all the strings have been processed. Finally, we need to erase the content of later cells to clean up anything that might be left there. Do length = Len(Worksheets("Sheet1").Cells(10, x).Value) If (length = 0) Then Exit Do Worksheets("Sheet1").Cells(10, x).Value = "" x = x + 1 Loop End Sub

115

Row 10 now contains the size of the buffer required to handle the results of the function call and a variable name in each cell staring in column E.

Vensim Info
Sub Get_Vensim_Info() Dim buf As String * 512 result = vensim_command( "SPECIAL>LOADMODEL|c:\Program Files\vensim\dll\worldapp.vmf") vensim_command ("SIMULATE>CHGFILE|changes.cin") vensim_command ("SIMULATE>DATA|data") The first three vensim_command calls load a model and make some changes to the way the model will simulate - mostly to check to see that the changes stick. For i = 1 To 21 length = vensim_get_info(i, buf, 500) Worksheets("Sheet1").Cells(21, 5 + i).Value = buf Next i We then loop through the different types of information and put the results into successive columns. Note that a couple of these info calls actually return more than one string, but we do not check this. Only the first string will be displayed. We can do this because the Null terminator is the standard string terminator so the contents of buf will be treated as just the first string. End Sub

Other Info
This example also contains functions to get information about variables and to get results from sensitivity runs. The format of these function calls is very similar to what we have already shown.

Displaying and Printing Sketches and Tool Output


Displaying sketches and tool output requires the full DLL. See the vendll example in VBASIC40 or VBASIC60. Sketches To display a Sketch use the vensim_show_sketch command as in: Dim winint As Long winint = Form1.Picture1.hWnd result = vensim_show_sketch(1, 0, 100, winint) The recasting of the hWnd as a Long (an Integer in 16 bit) is necessary because of apparent restrictions on argument types in Visual Basic. If you want the prompts describing variable names to show on a sketch you will need to send Vensim the command SETTING>HOVERCOMMENT|1. By default the DLL does not display any of this comment information. Tools Dim winint As Long winint = Form1.Picture1.hWnd result = vensim_tool_command("WORKBENCH>Causes Tree", winint, 0) The hWnd recasting is the same as for sketches. winint = Form1.Picture1.hWnd To display a WIP tool use:

116

result = vensim_tool_command("CUSTOM>WIP", winint, 1) Printing and Exporting Dim winint As Long winint = Form1.Picture1.hWnd result = vensim_tool_command("PRINT>", winint, 0) ' or result = vensim_tool_command("EXPORT>", winint, 0) To the only trick for printing is to get the right window.

117

12

DLL Function Details

This section details the functions supported by the Vensim DLL. The server version of the DLL supports multiple contexts. These function calls are almost the same as the regular function calls with the addition of the context argument. For completeness we include prototypes for both the context calls and the non context calls for C and Java. The VensimContextAdd and VensimContextDrop functions are specific to the server version. It is worth noting that if a regular function call is made with the Server DLL the context 0 will be used. If a server function call is made with the regular DLL the regular function will be called.

Language Notes
Function prototypes are given in this chapter for C, Jave, Delphi (Pascal) and Visual Basic. C, Java and Pascal all use a 32 bit integer so the prototypes are on integers. For 32 bit Visual Basic we explicitly use Long instead of Integer. The function prototypes for C assume that EXPORTED_PROC has been defined as: #define EXPORTED_PROC __stdcall If you are using C++ you will also need to precede the function prototypes with extern "C" this is done for you in the file vendll.h that installs in the dll directory. The Java calls are actually all through an intermediate class definition and glue dll called venjava.dll. The function definitions all appear in vensim.java. To use the Java calls use the class vensim so that the calls appear as vensim.be_quiet(0) and so on. For Delphi you need to define the SinglePtr, DoublePtr and LongintPtr types as: type SinglePtr = ^Single ; DoublePtr = ^Double ; LongintPtr = ^Longint ;

vensim_be_quiet C/C++ Java VB Pascal int EXPORTED_PROC vensim_be_quiet(int quietflag) ; int EXPORTED_PROC VensimCBeQuiet(int context,int quietflag) ; public static native int be_quiet( int quietflag ); public static native int CBeQuiet(int context, int quietflag ); Private Declare Function vensim_be_quiet Lib "vendll32.dll" (ByVal quietflag As Long) As Long function vensim_be_quiet(quietflag: Integer) : Integer ; stdcall ; external 'vendll32.dll' ;

This allows you to turn off the work in progress dialog that Vensim displays during simulation and other activities, and also prevent the appearance of yes or no dialogs.

118

Arguments

quietflag

Use 0 for normal interaction, 1 to prevent the appearance of any work in progress windows, and 2 to also prevent the appearance of any interrogative dialogs.

Returns The function returns the value of quietflag. Notes This function has no impact on the minimal DLL (which never produces visible interaction). If you want to have work-in-progress windows appear but suppress interaction, use vensim_command("SPECIAL>NOINTERACTION"). Note that the full DLL will always display the Vensim Splash Screen while it is starting. If you have a redistribution license the dll (vendlx32.dll or vendlx16.dll) can be forced to suppress the Splash Screen by making vensim_be_quiet the very first function call.

vensim_check_status C/C++ Java VB Pascal int EXPORTED_PROC vensim_check_status() ; int EXPORTED_PROC VensimCCheckStatus(int context) ; public static native int check_status(); public static native int CCheckStatus(int context); Private Declare Function vensim_check_status Lib "vendll32.dll" () As Long function vensim_check_status : Integer ; stdcall ; external 'vendll32.dll' ;

vensim_check_status is used to check the current status of the Vensim DLL. The two main purposes are to check Vensim is still in gaming mode, and to be sure Vensim is in a consistent internal state. Arguments

None
Returns 0 - to indicate that Vensim is idle and awaiting activity. This is the normal value. 1 - to indicate that Vensim is in an active simulation. This value will normally be returned after vensim_start_simulation has been called but before vensim_finish_simulation has been called. 2 - to indicate that Vensim is in a simulation, but not an active simulation. This value most likely indicates a frozen or hung condition in Vensim. 3 - to indicate that Vensim is blocking action. This value should indicates an error condition in Vensim and will prevent commands from functioning. 4 - to indicate that Vensim is not able to free working memory allocations. This is an error condition. 5 - to indicate that Vensim is currently working with an active gaming session. 6 - to indicate that Vensim has not freed all of its working memory. Normally a call to vensim_command will correct this. 16 - SyntheSim is active and SETVAL will not trigger simulations. This value will be added to the above values (eg 17 is SyntheSim is active and simulating). Note that values other than 16, 17 and 22 indicate a problem.

119

32 - SyntheSim is active and SETVAL will trigger simulations. This value will be added to the above values (eg 33 is SyntheSim is active and simulating). Note that values other than 32, 33 and 38 indicate a problem. Notes The only return values you should see are 0, 1, 5, 32 and 33. Other values indicate that Vensim is in an error state - please let us know if this happens. See Also vensim_start_simulation, vensim_continue_simulation, vensim_finish_simulation

vensim_command C/C++ int EXPORTED_PROC vensim_command(char *command) ; int EXPORTED_PROC VensimCCommand(int context,const char *command) ; public static native int command( String command ); public static native int CCommand(int context,String command ); Private Declare Function vensim_command Lib "vendll32.dll" (ByVal Vcommand$) As Long function vensim_command(command_string: PChar): Integer ; stdcall ; external 'vendll32.dll' ;

Java VB Pascal

The vensim_command function is the main function that is used to interact with Vensim. The commands supported are a subset of the commands supported when running Venapps. Arguments

command
Returns

Is a null terminated string that indicates the command to execute. See chapter 5 for details on supported commands.

A return value of 1 indicates successful completion of the command. A return value of 0 indicates the command or test failed. The interpretation of failure depends on the command being sent. Notes The vensim_command function should only be used with commands that do not require any interaction with the screen. Use vensim_tool_command for creating, copying and printing any visual elements. See Also vensim_tool_command

vensim_continue_simulation C/C++ int EXPORTED_PROC vensim_continue_simulation(int num_iter) ; int EXPORTED_PROC VensimCContinueSimulation(int context,int num_iter) ; public static native int continue_simulation( int numIntervals ); public static native int CContinueSimulation(int context, int numIntervals );

Java

120

VB Pascal

Private Declare Function vensim_continue_simulation Lib "vendll32.dll" (ByVal number_time_step As Long) As Long function vensim_continue_simulation(num_iter: Integer) : Integer ; stdcall ; external 'vendll32.dll' ;

Use vensim_continue_simulation as many times as necessary between vensim_start_simulation and vensim_finish_simulation to complete the simulation for all times. Arguments

num_inter

The number of TIME_STEP iterations that should be executed during the continuation. This can be chosen so that the execution time of the command is small enough to permit frequent feedback to the user.

Returns 1 - to indicate that there is still more to do. 0 - to indicate that there is nothing more to do. In this case vensim_finish_simulation should be called. -1 - to indicate that a floating point error occurred during the simulation. In this case vensim_finish_simulation should be called. Notes This function does nothing if vensim_start_simulation has not been called. In this situation it will return 0. See Also vensim_start_simulation, vensim_finish_simulation

vensim_finish_simulation C/C++ Java VB Pascal int EXPORTED_PROC vensim_finish_simulation(void) ; int EXPORTED_PROC VensimCFinishSimulation(int context) ; public static native int finish_simulation(); public static native int CFinishSimulation(int context); Private Declare Function vensim_finish_simulation Lib "vendll32.dll" () As Long function vensim_finish_simulation : Integer ; stdcall ; external 'vendll32.dll' ;

Completes a simulation started with vensim_start_simulation. Arguments

none
Returns 1 to indicate success and 0 to indicate failure. A return value of 0 should occur only if a simulation has not been started using vensim_start_simulation. Notes Use only with vensim_start_simulation, vensim_continue_simulation

121

See Also vensim_start_simulation, vensim_continue_simulation

vensim_get_data C/C++ int EXPORTED_PROC vensim_get_data(char *filename,char *varname,char *tname,float *vval,float *tval,int maxn) ; int EXPORTED_PROC VensimCGetData(int context,const char *filename,const char *varname,const char *tname,float *vval,float *tval,int maxn) ; public static native int get_data( String fileName, String varName, String timeAxisName, float vectorOfValues[], float timeVectorValues[], int maxNumberValues ); public static native int CGetData(int context, String fileName, String varName, String timeAxisName, float vectorOfValues[], float timeVectorValues[], int maxNumberValues ); Private Declare Function vensim_get_data Lib "vendll32.dll" (ByVal filename$, ByVal varname$, ByVal timename$, varvals As Single, timevals As Single, ByVal maxpoints As Integer) As Long function vensim_get_data(filename: PChar; varname:PChar; timename:PChar; varvals: SinglePtr;timevals:SinglePtr;maxpoints:Integer ): Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

Retrieves data from simulation runs or imported datasets. Arguments

filename varname tname

vval tval

maxn

the name of the file containing the data. This names a .vdf file. the name of the variable to retrieve data on. This must be a fully subscripted variable name. the name of the time axis against which to pull the data. This is normally "Time", but could name a different time axis if one has been defined in simulation or data conversion from which the dataset originated. the vector of values for the variable. This is a single precision vector of numbers. the vector of values for the designated time axis. It is important to remember that these numbers will not necessarily be evenly spaced. the maximum number of values that can be filled in. Use this to prevent any overruns on the vval and tval vectors. If this value is 0 the function will return the required buffer size for any variable. In this case the values specified for varname and tname do not matter.

122

Returns The number of values retrieved or, if maxn is 0, the required buffer size to fetch values from the dataset. A return value of 0 indicates that the variable was not found in the dataset. If the return value is the same as maxn and maxn is positive there may be insufficient room to return all values. Notes If the variable name is a Lookup in the model the x,y values will be returned. If a model variable is Auxiliary With Lookup you can use #variable name# to retrieve the Lookup values. When called with a NULL or empty filename the current Lookup settings for any pending simulation are returned. If vensim_get_data is called with a NULL or empty filename it can be used to retrieve SyntheSim results without having to save these to disk. Note that the first time this is called for a given variable it will return the saved value until another simulation is performed. This is because Vensim is basically building a save list based on these calls. It is therefore good practice to call the data retrieval functions directly upon starting SyntheSim even though the results may not yet be needed. vensim_command("MENU>SYNTHESIM") ; vensim_command("SYNTHESIM>AUTO|0") ; call a function to retrieve data values in .vdf file returned vensim_command("SYNTHESIM>GO|0") ; call same function to retrieve data current values returned This function can be used after a play in a game has occurred to retrieve all values up till the current time. See Also vensim_get_val

vensim_get_dpval C/C++ int EXPORTED_PROC vensim_get_dpval(char *name,double*val) ; int EXPORTED_PROC VensimCGetDPVal(int context,const char *name,double *val) ; public static native int get_dpval( String varName, double val[] ); public static native int CGetDPVval(int context, String varName, double val[] ); Private Declare Function vensim_get_dpval Lib "vendll32.dll" (ByVal varname$, varval As Double) As Long function vensim_get_dpval(varname:PChar; varval: DoublePtr): Integer ; stdcall ; external 'vendll132.dll' ;

Java

VB Pascal

Use this function to get the value of a variable during a simulation (with vensim_start_simulation...), as a game is progressing, or during simulation setup. This function is only useful if you are using the double precision Vensim DLL. Arguments

name varval
Returns

the fully subscripted name of the variable. a pointer to a double precision floating point number that will be filled in with the value.

1 to indicate the number has been successfully retrieved. 0 to indicate the variable was not found.

123

Notes During a simulation or a game, vensim_get_val will return a valid number for all variables in a model. Before a simulation or game has started, vensim_get_val will return valid numbers for constants and missing or :NA: (-1.2980742146337069E33) for other model variables. You can use the test command (e.g. vensim_command("TEST>c=5")) to force 1 stage intermediate computation just as in a Venapp. See Also vensim_get_val, vensim_get_data

vensim_get_dpvecvals C/C++ int EXPORTED_PROC vensim_get_dpvecvals(const unsigned long *vecoff,double *dpvals,int veclen) ; int EXPORTED_PROC VensimCGetDPVecVals(int context,const unsigned long *offsets,double *dpvals,int veclen) ; public static native int get_dpvecvals(int offsets[],double dpvals[],int veclen) ; public static native int CGetDPVecVals(int context,int offsets[],double dpvals[],int veclen) ; Private Declare Function vensim_get_dpvecvals Lib "vendll32.dll" (vecoff As Long, varvals As Double, ByVal veclen As Long) As Long function vensim_get_dpvecvals(vecoff:LongintPtr; varvals: DoublePtr;veclen:Integer): Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB Pascal

This is the same as vensim_get_vecvals except it takes a double vector to store values. Use of this call is only meaningful when you are using the double precision DLL, though it is supported in the single precision DLLs for compatibility. Arguments vecoff dpvals veclen Returns The number of elements in the vector or 0 on error. A vector containing offsets as returned by vensim_get_varoff. The location into which the values for variables should be written. The number of elements in the vector.

vensim_get_info C/C++ int EXPORTED_PROC vensim_get_info(int infowanted,char *buf,int maxbuflen) ; int EXPORTED_PROC VensimCGetInfo(int context,int infowanted,char *buf,int maxbuflen) ; public static native String[] get_info(int infowanted) ; public static native String[] CGetInfo(int context,int infowanted) ; Private Declare Function vensim_get_info Lib "vendll32.dll" (ByVal infowanted As Long, ByVal buf$, ByVal maxbuflen As Long) As Long function vensim_get_info(infowanted:Integer;buf:PChar; maxbuflen:Integer):

Java VB Pascal

124

Integer ; stdcall ; external 'vendll132.dll' ;


Use this function to get information about Vensim, what model is loaded and related things. Arguments

infowanted

Specifies the type of information desired.

1 for the type of DLL (Minimal, Silent, Full or Redist) 2 for the version of Vensim 3 for the Vensim user name and company (two strings) 4 for the current active directory 5 for the current model name 6 for the name of the loaded toolset 7 for the names of the tools in the current toolset 8 for the name of the currently loaded custom graph set 9 for the names of the custom graphs in the currently loaded graph set 10 for the names of the currently loaded runs 11 for name of the run that will be used when a simulation is made (SIMULATE>RUNNAME) 12 for the list (comma separated) of cin files that will be used (SIMULATE>CHGFILE) 13 for the list (comma separated) of data files (SIMULATE>DATA) 14 for the run the simulation will be based on (SIMULATE>BASED) 15 for the name of the optimization control files (SIMULATE>OPTPARM) 16 for the name of the payoff definition file (SIMULATE>PAYOFF) 17 for the resume status (0 or 1) (SIMULATE>RESUME) 18 for the name of the savelist ( SIMULATE>SAVELIST) 19 for the name of the sensitivity savelist (SIMULATE>SENSSAVELIST) 20 for the name of the sensitivity control file (SIMULATE>SENSITIVITY) 21 for the name of the workbench variable including all subscripts 22 for a list of the views in the model (first is view 1, second view 2 and so on)

buf maxbuflen

A buffer into which the subsstring will be placed. The maximum amount of space that will be used in buf. If this is zero the function will simple return the size of the buffer needed to store the information.

Returns The length of the buffer needed to store the information requested. Up to maxbuflen of this information will be copied into buf. If maxbuflen is bigger than 2 buf will always be terminated with a double null though information may need to be truncated to do this. Notes Most of these calls return a single string. Exceptions are 3,7,9 and 10 which return multiple null terminated string. The infowanted argument has defined values (eg INFO_WANTED) in vendll.h that you can use instead of numbers if you are working with C/C++.

125

vensim_get_sens_at_time C/C++ int EXPORTED_PROC vensim_get_sens_at_time(const char *filename,const char *varname,const char *timename,const float *attime,float *vals,int maxn) ; int EXPORTED_PROC VensimCGetSensAtTime(int context,const char *filename,const char *varname,const char *tname,const float *intime,float *vals,int maxn) ; public static native int get_sens_at_time(String filename,String varname,String tname,float intime[],float vals[],int maxn) ; public static native int CGetSensAtTime(int context,String filename,String varname,String tname,float intime[],float vals[],int maxn) ; Private Declare Function vensim_get_sens_at_time Lib "vendll32.dll" (ByVal filename$, ByVal varname$, ByVal timename$, attime As Single, vals As Single, ByVal maxpoint As Long) As Long function vensim_get_sens_at_time(filename: PChar; varname:PChar; timename:PChar; attime:Single; vals:SinglePtr; maxn:Integer ): Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

Gets results from a sensitivity run at a specific type and across sensitivity runs. Arguments

filename varname timename attime vals maxn


Returns

Dataset (.vdf) file containing the sensitivity results. Name of the variables to get results for (fully subscripted) Time base name (usually "Time") The time at which results should be retrieved vector of values at the specified time The maximum number of value to put into vals.

The number of values placed in vals - 0 on failure. If the function is called with maxn equal to 0 it returns the number of values available (that is the number of sensitivity simulations performed). Notes This function will return 0 if the run does not exist, if the run is not a sensitivity run, or if the variable does not exist or was not saved. See Also vensim_get_data

vensim_get_substring C/C++ int EXPORTED_PROC vensim_get_substring(char *fullstring,int offset,char *buf,int maxbuflen) ; int EXPORTED_PROC VensimCGetSubstring(int context,char *fullstring,int offset,char *buf,int maxbuflen) ; Private Declare Function vensim_get_substring Lib "vendll32.dll" (ByVal fullstring$, ByVal frompos As Long, ByVal buf$, ByVal maxbuflen As

VB

126

Pascal Java

Long) As Long function vensim_get_substring(fullstring: PChar; frompos:Integer; buf:PChar; maxbuflen:Integer ): Integer ; stdcall ; external 'vendll32.dll' ; Not useful

The vensim_get_substring function is utility function that is designed to make it easier to work with vensim_get_vernames, vensim_get_info and vensim_get_varattribs. It is most useful when working in Basic where string manipulation is not that straightfoward. Arguments

fullstring offset buf maxbuflen


Returns

The string that a substring is needed from. The offset at which the substring starts. A buffer into which the substring will be placed. The maximum amount of space that will be used in buf.

0 if the substring is empty, otherwise the number of characters in the substring including the null termination character.
Notes The return val is the same as the number of non-null characters in the substring plus 1. Thus, adding the return value to the old offset will give the location of the next substring. If the return value exceeds maxbuflen the string will be truncated at maxbuflen (there will be maxbuflen-1 nonzero characters in the string). See Also vensim_get_vernames, vensim_get_info, vensim_get_varattribs

vensim_get_val C/C++ int EXPORTED_PROC vensim_get_val(char *name,float *val) ; int EXPORTED_PROC VensimCGetVal(int context,const char *name,float *val) ; public static native int get_val( String varName, float val[] ); public static native int CGetVal(int context, String varName, float val[] ); Private Declare Function vensim_get_val Lib "vendll32.dll" (ByVal varname$, varval As Single) As Integer function vensim_get_val(varname:PChar; varvals: SinglePtr): Integer ; far ; external 'vendll32.dll' ;

Java VB Pascal

Use this function to get the value of a variable during a simulation (with vensim_start_simulation...), as a game is progressing, or during simulation setup. Arguments

name val
Returns

the fully subscripted name of the variable. a pointer to a single precision floating point number that will be filled in with the value.

1 to indicate the number has been successfully retrieved. 0 to indicate the variable was not found.

127

Notes During a simulation or a game, vensim_get_val will return a valid number for all variables in a model. Before a simulation or game has started, vensim_get_val will return valid numbers for constants and missing or :NA: (-1.2980742146337069E33) for other model variables. You can use the test command (e.g. vensim_command("TEST>c=5")) to force 1 stage intermediate computation just as in a Venapp. See Also vensim_get_data

vensim_get_varattrib C/C++ int EXPORTED_PROC vensim_get_varattrib(const char *varname,int attrib,char *buf,int maxbuflen) ; int EXPORTED_PROC VensimCGetVarAttrib(int context,const char *varname,int attrib,char *buf,int maxbuflen) ; public static native String[] get_varattrib(String varname,int attrib) ; public static native String[] CGetVarAttrib(int context,String varname,int attrib) ; Private Declare Function vensim_get_varattrib Lib "vendll32.dll" (ByVal varname$, ByVal attrib As Long, ByVal buf$, ByVal maxbuflen As Long) As Long function vensim_get_varattrib(varname: PChar; attrib :Integer; buf:PChar; maxbuflen:Integer ): Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

Use this function to get the attributes of model variables. Arguments

varname attrib

buf

maxbuflen
Returns

The name of the variable that you want information about. The attribute you want to retrieve. 1 for Units, 2 for the comment, 3 for the equation, 4 for causes, 5 for uses, 6 for initial causes only, 7 for active causes only, 8 for the subscripts the variable has, 9 for all combinations those subscripts create,10 for the combination of subscripts that would be used by a graph tool, 11 for the minimum value set in the equation editor, 12 for the maximum and 13 for the range, 14 for the variable type (see vensim_get_varnames for types). A memory location to put the results of the query. Results are stored as a sequence of null terminated strings one following another. A double null is used to mark the termination of the sequence. buf is NULL or maxbuflen is 0 the function just returns the amount of space needed. The maximum amount of material to put in the buffer.

The amount of space needed to store the result. -1 if there is an error or the variable is not found.

128

Notes The units, comments and subscript family atrtibutes (1,2 and 8) only return a single string. The others may return more than one string. If the variable has no subscript the subscript queries all return an empty string. If maxbuflen is not big enough the results will be truncated. Comments will be truncated arbitrarily, for other attributes truncation will be done on complete strings so, for example, fewer causes will be listed. If vensim_get_varattrib is called with a subscript range or element there will be no causes, uses will list all variables containing that subscript (main range), the subscripts for the variable will give the name of the main subscript range, 9 will return the elements of the subscript range or the subscript constant and 10 will return the list of elements in the main range currently selected. See Also vensim_get_dat

vensim_get_varnames C/C++ int EXPORTED_PROC vensim_get_varnames(const char *filter,int vartype,char *buf,int maxbuflen) ; int EXPORTED_PROC VensimCGetVarNames(int context,const char *filter,int vartype,char *buf,int maxbuflen) ; public static native String[] get_varnames(String filter, int vartype) ; public static native String[] CGetVarNames(int context,String filter, int vartype) ; Private Declare Function vensim_get_varnames Lib "vendll32.dll" (ByVal filter$, ByVal varitype As Long, ByVal buf$, ByVal maxbuflen As Long) As Long function vensim_get_varnames(filter: PChar; vartype:Integer; buf:PChar; maxbuflen:Integer ): Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

Use this function to get the names of variables in the model. Arguments

filter vartype

buf

maxbuflen
Returns

A wildcard filter that operates the same way as Vensim variable selection filter The type of variable you would like to see. 0 for all, 1 for Levels, 2 for Auxiliary, 3 for Data, 4 for Initial, 5 for Constant, 6 for Lookup, 7 for Group, 8 for Subscript Ranges, 9 for Constraint., 10 for Test Input, 11 for Time Base, 12 for Gaming and 13 for Subscript Constants. A memory location to put the results of the query. Results are stored as a sequence of null terminated strings one following another. A double null is used to mark the termination of the sequence. buf is NULL or maxbuflen is 0 the function just returns the amount of space needed. The maximum amount of material to put in the buffer.

The amount of space needed to store the result. -1 if there is an error.

129

Notes If the return value exceeds maxbuflen and buf is not null then the results have been truncated. Truncation is always done on complete variable names so that the names returned are all valid. See Also vensim_get_varattrib, vensim_get_info

vensim_get_varoff C/C++ unsigned long EXPORTED_PROC vensim_get_varoff(const char *varname) ; unsigned long EXPORTED_PROC VensimCGetVarOff(int context,const char *varname) ; public static native int get_varoff(String varname) ; public static native int CGetVaroff(int context,String varname) ; Private Declare Function vensim_get_varoff Lib "vendll32.dll" (ByVal varname$) As Long function vensim_get_varoff (varname: PChar ): Longint ; stdcall ; external 'vendll32.dll' ;

Java VB Pascal

This function is intended for use with vensim_get_vecvals. By filling up a vector of offsets you can speed the retrieval of multiple values. Arguments varname Returns The offset of the variable name or 0 if the variable name is not found or is not of the right type. Notes It is a Vensim convention that time is always offset 1. If you look at mdl.c you will notice that the offsets are 1 smaller than that returned by the function. This is because internally Vensim uses 0 based, not 1 based offsets. Do not adjust the offset returned since vensim_get_vecvals expects 1 based offsets. See Also vensim_get_vecvals, vensim_get_dpvecvals This is a full subscripted variable name that you want the offset for.

vensim_get_vecvals C/C++ int EXPORTED_PROC vensim_get_vecvals(const unsigned long *vecoff,float *vals,int nvals) ; int EXPORTED_PROC VensimCGetVecVals(int context,const unsigned long *vecoff,float *vals,int nvals) ; public static native int get_vecvals(int vecoff[],float val[],int nvals) ; public static native int CGetVecVals(int context,int vecoff[],float val[],int nvals) ; Private Declare Function vensim_get_vecvals Lib "vendll32.dll" (vecoff As

Java

VB

130

Pascal

Long, varvals As Single, ByVal nelm As Long) As Long function vensim_get_vecvals(vecoff:LongintPtr; varvals: SinglePtr;veclen:Integer): Integer ; stdcall ; external 'vendll32.dll' ;

Gets a vector of values at the current simulation time. For use during a game, or when controlling simulation using vensim_start_simulation and vensim_continue_simulation. Getting a vector of values can speed up data retrieval. Arguments vecoff vals nvals Returns The number of elements in the vector or 0 on error. Notes If any offset is invalid and NA will be returned at that location. A vector containing offsets as returned by vensim_get_varoff. The location into which the values for variables should be written. The number of elements in the vector.

vensim_set_parent_window C/C++ int EXPORTED_PROC vensim_set_parent_window(HWND window,long r1,long r2) ; int EXPORTED_PROC VensimCSetParentWindow(int context,HWND window,long r1,long r2) ; public static native int set_parent_window(int window,int r1,int r2) ;//generally references to windows just won't work public static native int CSetParentWindow(int context,int window,int r1,int r2) ;//generally references to windows just won't work Private Declare Function vensim_set_parent_window Lib "vendll32.dll" (ByVal vwidnow As Long, ByVal r1 As Long, ByVal r2 As Long) As Long function vensim_set_parent_window(pwindow : HWND;r1:Longint;r2:Longint) : Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

This is used to set a window that will be the owner of any dialogs or message boxes that Vensim presents. This can help to prevent the uncoupling of message boxes and the application. Arguments

window rl r2
Returns 1

Window that will act as parent For encrypted DLL only. Use the first key supplied with your redistribution package. For the regular DLL use 0. Fore encrypted DLL only. Use the second key supplied with your redistribution package. For the regular DLL use 0.

131

Notes Set the parent window to 0 (or NULL) to get the default behavior. If you are using the encrypted DLL you must call this function before trying to open any model or graph set. If you do not the open will fail and Vensim may crash. If you pass the wrong keys no models will open and Vensim may crash.

vensim_show_sketch C/C++ int EXPORTED_PROC vensim_show_sketch(int sketchnum,int wantscroll,int zoompercent,HWND pwindow) ; int EXPORTED_PROC VensimCShowSketch(int context,int sketchnum,int wantscroll,int zoompercent,HWND pwindow) ; public static native int show_sketch( int sketchNum, int wantScroll, int zoomPercent, int windowHandle );//generally references to windows just won't work public static native int CShowSketch(int context, int sketchNum, int wantScroll, int zoomPercent, int windowHandle );//generally references to windows just won't work Private Declare Function vensim_show_sketch Lib "vendll32.dll" (ByVal viewnum As Long, ByVal wantscroll As Long, ByVal zoompercent As Long, ByVal Vwindow As Integer) As Long function vensim_show_sketch(sketchnum: Integer;wantscroll: Integer; zoompercent: Integer;pwindow : HWND) : Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

Use this command to display a model diagram. Arguments

sketchnum wantscroll

zoompercent pwindow

the number of the view to be shown (1 is the first view, 2 the second and so on). use 0 to indicate that no scrollbars should appear and 1 to indicate that scrollbars should appear. If there are no scroll bars and the entire view is not visible there will be no way to see it all. specify the zoom percent (between 20 and 500) that you want the sketch to appear at. A value of 0 is the same as 100%. the handle to the window that the sketch should appear in. The sketch will be created in a child to this window. Note that in Visual Basic this value is passed as an integer.

Returns 1 to indicate successful complete, 0 otherwise. Notes If there is another view or other tool output in the window, Vensim will automatically remove this and clear the associated resources. This function does nothing in the minimal DLL. In general this functionality will not be useful with Java.

132

See Also vensim_tool_command

vensim_start_simulation C/C++ int EXPORTED_PROC vensim_start_simulation(int loadfirst,int game,int overwrite) ; int EXPORTED_PROC VensimCStartSimulation(int context,int loadfirst,int game,int overwrite) ; public static native int start_simulation(int loadFirst, int game, int overwrite ); public static native int CStartSimulation(int context, int loadFirst, int game, int overwrite ); Private Declare Function vensim_start_simulation Lib "vendll32.dll" (ByVal loadfirst As Long, ByVal game As Long, ByVal overwrite As Integer) As Long function vensim_start_simulation(loadfirst: Integer;game: Integer; overwrite: Integer) : Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

Start a simulation that will be performed a bit at a time. Arguments

loadfirst game

overwrite

Use 1 to indicate that the run resulting from the simulation should be loaded first in the list of runs (as in MENU>RUN1). Use 0 to indicate that this is a regular (not gaming) simulation. Use 1 to start a new game and use 2 to continue with an existing game. Note that using a game value of 1 during a game will restart the gaming session not continue it. Use 1 to suppress any query about overwriting an existing file when the simulation starts. (same as the |O option on the MENU>RUN command).

Returns 1 if the simulation is successfully started and 0 otherwise. If this is called with a game value of 2 and there is not an active game the command will return 0. Notes This, along with vensim_continue_simulation and vensim_finish_simulation allow you to provide the user feedback on the progress of a simulation. In C notation the process looks like: if(vensim_start_simulation(0,0,1)) { float time ; do { if(vensim_get_val("Time",&time)) /* get current value for time */ put_up_progress_indicators(time) ; /* another function that shows progress */ } while(vensim_continue_simulation(5) == 1) ; vensim_finish_simulation() ; }

133

Once you have called vensim_start_simulation only the SIMULATE>SETVAL command will work. You can use this to set the value of a gaming variable within the gaming simulation. It is faster to do this than run the game a one interval at a time because the data only need to be stored at the end of the simulation. See the example in the previous chapter. See Also vensim_continue_simulation,vensim_finish_simulation,vensim_get_val

vensim_synthesim_vals C/C++ int EXPORTED_PROC vensim_synthesim_vals(unsigned long offset, float **tval, float **varval) ; int EXPORTED_PROC VensimCSynthesimVals(int threadcontext,VAL_OFF offset,float **x,float **y) ; Not applicable Not applicable Not applicable

Java VB Pascal

This is a specialized function that uses memory managed by Vensim to give access to values while SyntheSim is active. Because it depends on native data formats it is available only in C. For other programming languages use vensim_get_data with a null or empty filename. Arguments

offset tval varval


Returns

the offset of the variable to get data for as returned by vensim_get_varoff. a pointer for which the address of the time values is returned. a pointer for which the address of the variable values is returned.

The number of points that are stored or 0 if offset is out of range or Vensim is not in SyntheSim mode. The addresses of the time and variable vectors are also returned in the passed arguments. These addresses will remain valid until SyntheSim is stopped, or the number of saved data points changes. Notes This function gives extremely fast access to model results. As Vensim simulates it fills in values at the designated addresses. This means that when working with a model for which SAVEPER, INTIAL TIME and FINAL TIME are not changing you can access simulation results as the simulation progresses. If any one of SAVEPER, INITIAL TIME or FINAL TIME is changing do not retain the returned addresses. If a floating point error occurs during simulation older values will be left in the later parts of the returned arrays. The first time you call this function the results will be those stored in the current run file. Subsequent calls will return the results of the last simulation whether it was saved or not. It is best practice to call this for all the offsets for which data is desired upon entering SyntheSim mode. See Also vensim_get_data

134

vensim_tool_command C/C++ int EXPORTED_PROC vensim_tool_command(char *command,HWND pwindow,int aswiptool) ; int EXPORTED_PROC VensimCToolCommand(int context,const char *command,HWND pwindow,int aswiptool) ; public static native int tool_command( String command, int windowHandle, int aswiptool );//generally references to windows just won't work public static native int CToolCommand(int context, String command, int windowHandle, int aswiptool );//generally references to windows just won't work Private Declare Function vensim_tool_command Lib "vendll32.dll" (ByVal Vcommand$, ByVal Vwindow As Long, ByVal iswip As Integer) As Long function vensim_tool_command(command_string: PChar;outwin : HWND; wipflag: Integer): Integer ; stdcall ; external 'vendll32.dll' ;

Java

VB

Pascal

Perform a command that will cause output to be created, or the printing or exporting of the contents of a currently displayed item. Arguments

command pwindow

aswiptool

the command to pass through Vensim. The available commands are documented in Chapter 5. the handle to the window that the tool output should appear in, or the material to be printed does appear in. Output will be created in a child to this window. Note that in Visual Basic this value is passed as an integer. 1 to indicate that the tool being created is a work in progress graph that should be kept open to display simulation results. Use 0 otherwise.

Returns 1 to indicate success, 0 to indicate failure. Notes This function is used for WORKBENCH, CUSTOM, ERROR, EXPORT and PRINT command classes. For all other command classes vensim_command has the same effect. For ERROR and PRINT you do not need to specify a command, but you must include the > as in: vensim_tool_command("PRINT>",mywindow,0). If you want to remove output previously created, call vensim_tool_command with a null or empty command. If you are manually loading and unloading vendll32.dll, be sure to do this before unloading the DLL. This function is the same as vensim_command in the minimal DLL. Generally this function will not be useful with Java. See Also vensim_command

135

VensimContextAdd C/C++ Java int EXPORTED_PROC VensimContextAdd(int wantcleanup) ; public static native int ContextAdd(int wantcleanup) ;

Creates a new context for the server version of the Vensim DLL. Each context is a separate environment that can have its own model and will run in its own state. When a model is open in a context created in this manner Vensim will create a subdirectory to perform all operations. Arguments

wantcleanup

a flag to indicate that when the context is closed all files associated with the context will be deleted. If this is 0 the files will not be deleted, otherwise they will.

Returns A positive context number to indicate success, 0 to indicate failure. The returned value can be passed as the context argument in calls to the DLL functions. Notes Each time a model is open a subdirectory will be created in the directory the model is in and all files from simulations will be created in that subdirectory. You can still refer to other files (optimization control and so on) without any additional directory information, Vensim will take care of the location relative to the place where the runs will be stored. If the wantcleanup flag is nonzero then each time a new model is open the files associated with the old model will be deleted, and the directory that was created will be removed. Contexts are independent and thread safe. That means you can have different threads calling different contexts at the same time. See Also VensimContextDrop

VensimContextDrop C/C++ Java int EXPORTED_PROC VensimContextDrop(int contex) ; public static native int ContextDrop(int context) ;

Drops a context that was created with VensimContextAdd.. Arguments

context
Returns

the context to delete. This must be a valid context as returned by VensimContextAdd.

1 on success and 0 on failure. This function will fail if the context is not valid or if the DLL fails to get a mutex lock that will allow the release of resources. Notes If the context was created with the wantcleanup flag nonzero the working files used by the context should be automatically deleted. See Also VensimContextAdd

136

13

Distributing your Work

You can use Vensim DSS to develop some pretty interesting models and applications. Having done this, you might want to send these models or applications to other people. There are several ways to do this and it is useful to briefly review them. For those options that are not free, please contact us for pricing information.

Vensim Model Reader


The simplest way to allow someone to use your model is to send them the Vensim Model Reader along with a copy of your model. To do this, you do not need to develop any interface for your model, but simply save your model as a binary format (.vmf) model. You can build in a very simple but effective interface using the Input Output Objects in the sketch. Chapter 11 of the Tutorial shows how to do this. Note that the Vensim Model Reader is not capable of reading any custom application or graph files. If you have defined a special graph set, it is necessary to make that the default graph set (using the "Into Model" button in the Graph tab of the Control Panel). The Vensim Model Reader is available free from our web site www.vensim.com. The Vensim model reader is also included in the Vensim Installation CD. The file venred32.exe in the Windows directory is the Windows 95 model reader installer. You are welcome to send this installer to other people to read your models. There is alwo PowerMac versions of the reader and this will work with models from other platforms. Note that the Vensim Model Reader does not support external function calls, optimization or sensitivity testing. It is also not possible to used the "Based On simulation option with it.

Vensim Runtime
Vensim Runtime is a read only Version of Vensim DSS. It supports the full interface, including optimization and external functions, of Vensim DSS, but does not have any ability to edit models or files. Vensim Runtime does not include the Text Editor, so it is harder to use with models that do not have sketch information. Vensim Runtime ships with the full set of Vensim Documentation (except the DSS Reference Supplement). To prepare a model for use with Vensim Runtime, it is necessary to save the model as a binary format (.vmf) model. It is not necessary to save the graph sets in binary format. Vensim Runtime can read .vgd files, and can also be used to create and modify custom graphs. Vensim Runtime can be purchased from the Vensim Product Center contact us for details.

Vensim Application Runtime


If you have developed a Venapp that you would like to send to other people who do not have Vensim DSS, they will need the Vensim Application Runtime engine to run the Venapp. The Application Runtime Engine works only with Venapps, it does not allow models to be opened directly. After the Application Runtime installed on a computer it is possible to use it to run the Venapps you have created. Vensim Application Runtime also installs the full Vensim DLL. To prepare a model for use by the Application Runtime engine, it is necessary to save the model as a .vmf file, the Venapp definition as a .vcf file and any graph definitions as .vgf files. You may need to rename these files in order to have the Venapp (which probably calls for loading .vgd files) work correctly. You can include any number of Venapp definitions and they can be linked using the SPECIAL>LOADCD command (as in the Vensim Demo disk). If you have a number of files, using a

137

Command Script can simplify the process of converting the files to binary format (see Chapter 7 for an example of a script that does this). The Vensim Application Runtime software is intended for redistribution by you to your users. Because the software is not of value without an application to run we do not sell it directly. When you purchase and Application Runtime package we will also provide you with software to support packaging your application for easier installation. Vensim Application Runtime can be purchased from the Vensim Product Center contact us for details.

Vensim Minimal DLL


If you have developed an application using the Vensim Minimal DLL, you can distribute that application along with the Minimal DLL free. The minimal DLL may be distributed free of charge subject to the following restrictions: A Copyright notice of the form "Portions Copyright 1987-1999 Ventana Systems, Inc." must be displayed on the opening or splash screen, or on a license agreement that ships with the product. The product you are distributing cannot be intended to allow the user to develop their own simulation models. Just as to use the DLL, you need to have binary format model and graph files.

Vensim DLL Runtime


If you have developed a model and interface using the full Vensim DLL you can send that to anyone who has Vensim DSS, Vensim Runtime or Vensim Application Runtime. When the Vensim Application Runtime is installed it also installs the Vensim DLL (but not the minimal DLL). The DLL will be installed in the system32 directory of Windows and will work just like the DLL that installs with Vensim DSS.

Vensim Application Distribution License


If you are planning on distributing large quantities of your application, you may want to consider an Application Distribution License. This gives you unlimited distribution rights and much more control over the form in which the material is packaged. The Application Distribution License allows you to use both the Venapp Runtime Engine and the DLL engine as is appropriate to your needs. The application distribution engines are the same as the regular engines except that they only work on encrypted binary files. Each distribution license is given a unique key so that other people's applications will not work with your engine. Because the files are encrypted, it also means that other Vensim users will not be able to open them. This gives you some security over your files, although it must be emphasized that the encryption is not very strong and cannot be expected to protect sensitive information. In order to prepare files for use under the distribution license, it is necessary to store them in binary format and encrypt them. Instructions for doing this along with the necessary software come with the kit. Command scripts are very useful for performing this encryption process. Your product must ship under a license agreement that protects your interests as well as ours. Vensim Application Distribution licenses can be purchased from the Vensim Product Center contact us for details.

138

Venapp Install Builder


The Venapp Install Builder is a utility program for creating installers for Venapps that will work with Vensim Application Runtime. the Venapp Install Builder is included with the Vensim Application Distribution license and may also be licensed separately for use with Vensim Application Runtime. Please contact us for pricing.

139

14

Connecting to Databases with ODBC

Starting with version 5.1 Vensim DSS has the ability to connect to databases using ODBC. This makes it much easier to bring data in from enterprise data sources and write simulation results out so that others can make use of them. The ODBC functionality is not available on the Macintosh and is not supported by the Minimal DLL. It will work only with Vensim DSS and the full Vensim DLL.

Overview
The conceptual framework in which database connectivity works is fairly simple. During the simulation setup you can specify a database as the source of values for model Constants, Lookups and Data variables. Then, at the end of a simulation, you can run a script that writes the simulation output to a database. Thus you can use databases as repositories of important model inputs and results and thereby integrate the modeling work into other information systems. The mechanics of this integration are a little bit more difficult, mostly because the data storage framework in a database, typically relational, is different from that used in Vensim. For example, a time series in Vensim is maintained as a variable name followed by a counted set of time and value pairs. In a relational database it would be common to have a table with information about the variable and a separate table with a time and a value element along with an index related to the first table. In developing the ODBC functionality for Vensim we have worked to make it easy to accommodate the above example, which is likely to be fairly typical. Still there may often be circumstances where the structure of the database needs to be modified somewhat to accommodate the connection to a dynamic model. The ability to modify database structure in order to make smooth connections is a database design skill, not necessarily something that most dynamic modelers have. Thus, the integration of a Vensim model using ODBC may require the cooperation of a number of people. The examples we will use will be for a simple Microsoft Access database. The same constructs would also work with an Oracle or SQL Server database. On the Vensim side no changes would be required except for the definition of the connection string. On the database side each database has slightly different techniques for managing tables. We have not made any attempt to set up indices and integrity constraints on the database side as the focus here is on the Vensim side.

Reading from a Database


Reading from a database is done at the beginning of a simulation run by loading a Vensim Database Input (.vdi) file. The database input file acts very much like a constant changes (.cin) file except that it reads information from a database, and also allows you to specify Data variables, not just Constants and Lookups. The database input file is also a little more strongly structured than a changes file. In fact, it most strongly resembles the graph definition file as described in Chapter 15 of the Reference Manual. To load a database input file just specify it in the list of changes input files on the Changes tab of the simulation control dialog. Based on the file extension (.vdi) Vensim will process this as a database input file. When Vensim reads information from a database it creates temporary structures to hold that information before incorporating it into the simulation. This is necessary because time based information for Data variables and x,y pairs for Lookups are likely to be spread over a number of records and be encountered in arbitrary orders. Normally, it is best to just let Vensim manage this but there may be situations where you want to explicitly force Vensim to incorporate information and start

140

the temporary storage process anew. For example, this might happen if you had a full set of data in a primary table and a single data series in a secondary table that you wanted to use instead of the data in the primary table. To do this use the INTERNALIZE command.

Writing to a Database
Writing to a database is done at the end of the simulation. By specifying one or more Vensim database output (.vdo) files in the Pre/Post tab of the Simulation Control dialog you can cause simulation results to be written to a database.

Database Input/Output File Structure


The input (.vdi) and output (.vdo) files have the same structure. Each file is a plain text file made up a series of keywords, which begin with a colon :, followed by values. Some of these are informational and are used to prepare queries and add selection clauses, and some are action keywords which are used to take an action. The informational keywords relating to an action must precede the action. Most informational keywords set values that are cleared after each action is performed, though a few of them are persistent. Many keywords will be followed by the name of a field in the database being accessed. The field will be used to read information from or write information to the database. It is best to use field names that do not have any embedded spaces or special characters. If you do have special characters or embedded spaces you can try putting double quotes " around the field name though this may not work with all ODBC sources. Sometimes, rather than querying the database for the value of a field you may want to specify a literal value. In this case prefix the value with a sharp sign # (this is also called a pound sign and a hash sign). What follows will be treated as if it were the result of a query from the database but the database will not be referenced for that value. See the examples section below.

Action Keywords
Action keywords cause an action to be taken connecting to a database, querying a database, writing to a database or internalizing what has been read from a database. Querying a database and writing to a database require that informational keywords have been set so that Vensim knows which fields to extract information from. :CONNECT database identifier Identifies the database to connect to. The connect string is a database identifier along with other information. The easiest way to get a connect string is to use the menu item Insert>ODBC Connection while working in the text editor. You can also use a placeholder (such as DATA1) for the database identifier. In this case the first time it is encountered the user will be queried to select a data source. After that the selected data source will be associated with DATA1 until Vensim is closed. The connect string is usually quite long and therefore often uses a continuation character which is a backslash \ right at the end of the line. The :CONNECT keyword should be the first to appear. There can only be one active connection at a time. If a connection is already open it will be closed and the new connection open. If the :CONNECT keyword was missing or the connection could not be completed the remaining statements will not be able to execute. Whatever connection is open will automatically be closed after the file is processed. :EXECUTE statement Causes the specified SQL statement to be executed against the ODBC source specified in the most recent :CONNECT line. A long statement may be continued on the next line by using a backslash \ at the end of a line.

141

The statement is passed through directly as is without being parsed by Vensim except that if there are any :FIELD lines preceding the :EXECUTE line they will be added to the end of the statement separated by AND. If the statement has the word WHERE in it there will be a leading AND, otherwise Vensim will insert WHERE before the first :FIELD pair. See the example on storing scenario results below. :INSERT tablename Output Only: Specifies that the values will be put to the database using an INSERT statement (as opposed to an UPDATE statement). The insert statement will take the form INSERT INTO tablename(field1,field2,field3) VALUES(value1,valu2,value3) Where the field value combinations come from the :FIELD, :VAR, :SUB and possibly :TIME lines. :INTERNALIZE Input Only. Causes all data accessed so far to be internalized in the model. This is useful if you are reading from multiple data sources that might have conflicting sets of value for Lookups and Data variables. Without this statement each x,y (Time,value) pair associated with a variable is added to a list of pairs. The :INTERNALIZE statement will close all those lists and start building them again. All data is automatically internalized after the completion of a .vdi file. :SELECT tablename clause Specifies the name of the table from which to extract information. The optional clause would typically be a WHERE qualifier that would restrict the dataset fetched of be used to determine the records updated. You can also let Vensim build the WHERE clause by specifying :FIELD lines. For output :SELECT can only be used with :VARLOOKUP and :VARLIST. Everything else must use a :UPDATE or :INSTERT command. It is best to choose table names that do not contain any special characters or embedded spaces. If a table name does have special characters you should put double quotes " around it though this may not work for all ODBC sources. :UPDATE tablename clause Output Only: Specifies the name of the table to write to and that the writing will be done using an UPDATE (as opposed to INSERT) statement. Update will change only the VALUE field, with everything else being part of the WHERE clause. The WHERE clause will be constructed from the :VAR, :SUB and :FIELD values and also, for time series and x,y pairs, the X or TIME value. Normally UPDATE would be used only to record constants or final values because it is much easier to delete and insert new time series values.

Informational Keywords
The informational keywords set up the background necessary to take actions. Most apply only to the action that follows, though some, such as :CONSTANTS are persistent. :CONSTANTS For input: Specifies that data coming in will refer to constants. This means that a value (or y) will be expected but no time (or x). Only a single value will be retrieved. If multiple records exist for the same constant the last record fetched will provide the value. For output this specifies that a single value will be written. This value could be for a constant or for a dynamic variable at a specific time. The :CONSTANTS setting remains active until a :LOOKUP or :DATA is encountered.

142

:DATA For input this specifies that the data coming in will refer to time series data. Data requires a series of Time and Value pairs associated with each variable (one or more). There is no requirement for any ordering of these pairs. Each variable for which data is retrieved must be a Data variable. For output species that data will be written as time and value pairs. You can also use this to write out the value of Lookups. The :DATA setting remains active until a :LOOKUP or :CONSTANTS is encountered. :DATASET datasetname Output only. Specifies the dataset that the data will be extracted from. If not specified, Vensim will used the first loaded dataset (*1) just as for graphs. You can use wildcards such as *2 just as for graphs and you can also use an exclamation point ! to indicate that the current run name should be used as the source dataset. Note that the dataset name is always a literal so you do not need the # sign in front of it, though the # sign can be used to maintain consistency. :FIELD name=value Specifies a fieldname and a value to set that fieldname to or require that fieldname to be equal to. For input this will be appended to the WHERE clause on the select statement using AND. For output this will be used in the definition of the table to insert or update values in. For INSERT the combinations will appear in the insert statement. For UPDATE the name=value combinations will be repeated in the WHERE clause separated by AND. You can use an exclamation point ! for the value of the field to indicate the name of the current run. This will appear without the .vdf extension. This can be a useful way to archive simulation results and fetch changes by scenario name as is shown in the examples. :LOOKUPS Input only: Specifies that data coming in will refer to Lookups. Lookups need a series of x and y values associated with each variable (each variable requires a minimum of two values). There is no requirement for any ordering of these pairs as there is no guarantee what the realized order of selection will be in any case. If you want to store a Lookup for output use the :DATA keyword. The :LOOKUP setting remains active until a :DATA or :CONSTANTS is encountered. :SUB fieldname Specified the field in which a subscript will be found. You can have up to 8 :SUB lines. When the data is read Vensim will construct a complete variable name by combining the :VARNAME result with the :SUB results as in: Varname[sub,sub,sub] Where the order is the same as the order in which the :SUB lines appear. If any :SUB is empty it will be ignored and if all the :SUB fields are empty the complete variable name will just be the value in the :VARNAME field. :TIME fieldname Specifies the field in which the time for which a value applies is stored. This field must be a number or a string containing a number. :TIME and :X are the same. :TIME is typically used for Data and :X for Lookups.

143

This field is ignored for constants except that for output you can use this to specify a literal value for the time at which dynamic variables should be retrieved from a dataset for storage. If no time is specified then the value of dynamic variables at the final time of the simulation will be used. :VARID fieldname Specifies the fieldname in which the variable ID will be found. See :VARLOOKUP for more details. :VARLOOKUP Specifies that the information that follows will be used to associate variable IDs with fully subscripted variable names. It is common in a relational database to associate a relatively short unique identifier (often just a number) with a table entry so that other tables can refer to that identifier rather than a longer name. For example you might have a table VARIABLES with fields Name, Sub1, Sub2, Sub3, Sub4, Type and Comment. Having a series of data points refer to that the table DATA would then need fields Name, Sub1, Sub2, Sub3, Sub4, Time and Value. If, however, a unique ID were to be added to the table VARIABLE then the table DATA could just have ID,Time,Value which saves a lot of space both for data and for indexing. When this is done, however, the table VARIABLE needs to be referred to in order to interpret the values from the table DATA. :VARLOOKUP allows this to happen. It needs to include a:VARNAME reference, 0 or more :SUB references and a :VARID reference. Vensim will then know which variable name to associate the ID with and can read in the data. For input, the :VARLOOKUP statement can come before or after any :CONSTANTS, :DATA or :LOOKUPS entries. It is recommended, however, that it appears last as this should give the best performance. There can be more than one :VARLOOKUP, and the variables referred to in :VARLOOKUP can be of all types. See the examples below. For output the :VARLOOKUP statement must come before the :UPDATE or :INSERT actions. The :VARLOOKUP sequence must end in a :SELECT statement. . :VARLIST Output only. Indicates that the information that follows indicates the list of variables to be output to the database. What follows can be either a list of variable names each on its own line, or the information necessary to perform a select and fetch the variable list from the database. Vensim recognizes a list by the lack of a colon : in the lines that follow and the termination of the variable list by the presence of a colon : in the next line. :VARNAME fieldname Specifies the field in which the variable name will be found. The variable name can be fully subscripted, in which case no :SUB lines should appear, or the subscripts might be stored in separate fields. :VALUE fieldname Specifies the field in which the value is stored. This field must be a number or a string containing a number. :VALUE and :Y are the same though :Y is typically only used with Lookups. :X fieldname Specifies the field in which the X value for a Lookup pair is stored. Actually a synonym for :TIME. :Y fieldname Specifies the field in which the Y value for a Lookup pair is stored. Actually a synonym for :VALUE.

144

Database Input Examples


In the following examples we will use :CONNECT DATA1. This will bring up a dialog box (more precisely a sequence of dialog boxes) to identify the data source the first time it is used in a Vensim session. After that the data source will be reused without the query. You can also specify a complete data source in the :CONNECT line. The easiest way to do this is to use the menu item Insert>ODBC connection from the Text editor.

Full Source Read


The following assumes that there are three tables DATA_VALS, LOOKUP_VALS and CONSTANT_VALS containing all the desired input data. :CONNECT DATA1 :DATA :VARNAME varname :SUB sub1 :TIME Time :VALUE value :SELECT DATA_VALS :LOOKUPS :VARNAME varname :SUB sub1 :X x :Y y :SELECT LOOKUP_VALS :CONSTANTS :VARNAME varname :SUB sub1 :VALUE value :SELECT CONSTANT_VALS For the remaining examples we will only do 1 of DATA, LOOKUPS or CONSTANTS but the same principles apply to each.

Using Variable IDs


Using variable IDs is likely to be generally useful, especially for time series data. It allows you to have one table to store information about a variable and second table to store the actual values with an arbitrary unique identifier identifying which variables values in the second table belong to. The following example is identical to the previous one except that variable IDs are used to mark all the tables containing values. :CONNECT DATA1 :DATA :VARID id :TIME Time :VALUE value :SELECT DATA_VALS :LOOKUPS :VARID id :X x :Y y :SELECT LOOKUP_VALS

145

:CONSTANTS :VARID id :VALUE value :SELECT CONSTANT_VALS :VARLOOKUP :VARID id :VARNAME varname :SUB sub1 :SELECT VARIABLES In this example the data is read in for the different Data, Constants and Lookups but the :VARLOOKUP section is needed to map those values to variables in the model. For input files it does not matter whether the :VARLOOKUP section goes before or after the other sections. However, for output files the VARLOOKUP section must go first.

Specific Variable Read


This example reads data values for a single variable. The WHERE clause uniquely identifies which variable to read information for. :CONNECT DATA1 :DATA :VARNAME #data2[sub1] :TIME Time :VALUE value :SELECT DATA_VALS WHERE VARNAME = data2 AND SUB1 = sub1

Different Time Fields


This approach would be useful if the data were not stored relationally but instead lumped together into fairly large records as might be the case in a data warehouse. :CONNECT DATA1 :DATA :VARNAME varname :TIME #1980 :VALUE value_at_1980 :SELECT DATA_VALS :VARNAME varname :TIME #1990 :VALUE value_at_1990 :SELECT DATA_VALS :VARNAME varname :TIME #2000 :VALUE value_at_2000 :SELECT DATA_VALS

Data Stored by Time


If the values are stored in records contain values for many variables at a time, you woulld use something like: :CONNECT DATA1 :DATA :VARNAME #var1 :TIME Time

146

:VALUE var1 :SELECT DATA_VALS :VARNAME #var2 :TIME Time :VALUE var2 :SELECT DATA_VALS

Values by Scenario
It is possible to use a database to store any number of scenarios. :CONNECT DATA1 :CONSTANTS :VARNAME varname :VALUE value :SELECT CONSTANT_VALS WHERE SCENARIO = baseline Alternatively, you can use the Runname to map to the scenario name as in: :CONNECT DATA1 :CONSTANTS :VARNAME varname :VALUE value :FILED SCENARIO=! :SELECT CONSTANT_VALS In this case the values would be selected from the scenario matching the run name.

Database Output Examples


The following are some simple examples of output to a database. For the most part the issues on the output side are the same as those on the input side. The database needs to be structured in a way that allows sensible communication with Vensim. It is possible to store Constants and Lookups used in creating a simulation as well as the results.

Output using Delete and Insert


A fairly common way to store output is likely to be by scenario. The following will store both values over time and values at a time (or constants) to tables which have a scenario identifier. The DELETE command is used to overwrite the existing scenario results with the same scenario name. In all cases we use the simulation run name as the scenario name. :CONNECT DATA1 :VARLOOKUP :VARID=ID :VARNAME=Varname :SUB=sub1 :SELECT VARIABLES :DATA :FIELD scenario=! :EXECUTE DELETE FROM DATA_OUTPUT :VARLIST variable one variable two :TIME X :VALUE Y

147

:VARID VARID :FIELD SCENARIO=! :INSERT DATA_OUTPUT :CONSTANT :FIELD scenario=! :EXECUTE DELETE FROM CONSTANT_OUTPUT :VARLIST constant one constant two :TIME X :VALUE Y :VARID VARID :FIELD SCENARIO=! :INSERT CONSTANT_OUTPUT Note that the DELETE command is constrained by the :FIELD value so that if the run name is current it would become DELETE FROM DATA_OUTPUT WHERE SCENARIO=current This SQL statement clears out the old results with the same scenario name. The Data and Constants are output to two different tables. If a Constant were output in the :DATA section its value would be output once at the first simulation time. Conversely, if a dynamic variable were to be output in the :CONSTANT section its value would be the final value unless you included a :TIME #other statement to specify which time to fetch values from.

Output Using Update


Normally UPDATE would be used to output a single value for each variable being output. In the example below variable names are used directly instead of with a surrogate ID. The value of the variables at time 20 will be stored in the database. Constant can clearly be stored in this manner as well but LOOKUPS will not be available. :CONNECT DATA1 :CONSTANTS :FIELD scenario=! :VARLIST constant2 varible2 :TIME #20 :FIELD scenario=! :VARNAME VARNAME :SUB SUB1 :VALUE VARVAL :UPDATE OUTPUT_CONSTANTS

Database Notes
The structure of the database will determine both the complexity of the statements needed to pass information back and forth with Vensim and the efficiency with which these statements can be executed. If you are passing small amounts of data then it is best to use the most convenient database structure and write very explicit queries and output statements.

148

If you are passing a larger amount of data you may want to emulate the simple example that comes with Vensim. You can then use Triggers or other mechanisms supported by the database you are using to do any necessary internal transformations prior to Vensims database reads and successive to its database writes.

Simple Database Example


The model odbctest.mdl along with the Microsoft Access Database odbctest.mdb provides a simple example of the ODBC connectivity. The database has a table describing variables along with a unique index for each variable subscript combination. There are no internal constraints on referential integrity in this database, but those should be included for a more complete application. Given the nature of the type of information Vensim will write to a database failure because of constraint violations is unlikely except when you are using an INSERT statement without a corresponding DELETE statement.

149

Index
:
:CONNECT 141 :CONSTANTS 142, 144 :DATA 142, 143, 144 :DATASET 143, 144 :EXECUTE 141 :FIELD 143, 144 :INSERT 142 :INTERNALIZE 141 :LOOKUPS 143, 144 :SELECT 141 :SUB 143 :TIME 142, 143, 144 :UPDATE 142 :VALUE 142, 143, 144 :VARID 142 :VARLIST 142 :VARLOOKUP 142 :VARNAME 142 :X 143, 144 :Y 143, 144

A
Accelerator/Range 30 Action Controls. 27 Action Keywords 141 Analysis 76, 77, 78 Analysis Screens 15 ANYKEY - com scr 33 Arguments119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135

B
Binary Venapp Files 16 BITMAP - txt pos 33 BRANCH 47, 48 BRANCH - txt com scr 34 Building Venapps 11 BUTTON - txt pos jst acc com scr ..................................................................................................................................34

C
CALLBACK txt com scr 34 Calling External Function 87 CANCEL 45, 48 CLOSESCREEN - com scr35 COLORCIRLE txt pos 35 COLORRECT txt pos 36 COMMAND 32 COMMAND - com 36 Command Definition Dialog23 Command Files 80 Command Scripts 9, 80 Command Use Summary 67

150

Commands and Output 107 Comments 33 Compilation 103 Compile Errors 102 Compiled Simulation Files104 Compiled Simulation for the Vensim Application Runtime..........................................................................................103 Compiled Simulation with Double Precision Vensim ...................................................................................................104 Compiled Simulations 9, 101 Compiled Simulations and External Functions .............................................................................................................105 Compiled Simulations and the Vensim DLL.................................................................................................................104 Compiling and Linking 87 Conditional Branching 15 Conditional Controls 15 CONDITIONAL txt 36 Connecting to Databases with ODBC ...........................................................................................................................140 Constant and Data Definition Functions..........................................................................................................................92 Constant Matrices 89 Continuing or Backing up a Game ................................................................................................................................113 Control Name or Type 28 Control Anatomy 28 Control Definition Dialog22, 23 Control Text 29 CUSTOM 45, 48 Cutting and Pasting 21

D
Data Access 107 Data Matrices 90 Data Stored by Time 146 Database Input Examples 145 Database Input/Output File Structure ............................................................................................................................141 Database Notes 148 Database Output Examples147 DATEVAR - txt pos acc 37 Defining External Functions83 Deleting 22 Demo Disk 78 Detailed Control Description33 Details of the Compilation Process ...............................................................................................................................101 Dialog Based Changes 79 Different Time Fields 146 Display Screens 14 Displaying and Printing Sketches and Tool Output.......................................................................................................116 Displaying Output 75 Distributing your Work 9, 137 DLL Function Details 118 DLLs Installed 108 Double Precision 8 Dynamic Data Exchange9, 97

E
EDATEVAR 37 Ending a Game 114 ERROR 49 Error Handling 94 ERROR in venapp 45 Establishing a Link 97 Examining Screens 12 Excel Example 97, 115 Executing Command 97 EXPORT 49, 50

151

External Function Libraries83 External Function Library Files.......................................................................................................................................95 External Functions 9, 83 External Functions and the Vensim DLL ........................................................................................................................96 External Functions and Venapps .....................................................................................................................................96 External Functions in Compiled Simulations ..................................................................................................................96

F
FILE 50, 81 File Names 46 FILECOPY|oldname|newname .......................................................................................................................................50 FILECREATE|filename 50 FILEDECRYPT|filename 50 FILEDELETE|filename 50 FILEENCRYPT|filename 50 FILEEXISTS|filename 50 FILEMDL2VMF|filename 50 FILERENAME|oldname|newname .................................................................................................................................51 FILEVCD2VCF|filename 51 FILEVGD2VGF|filename 51 FILEVMF2MDL|filename 51 Font 29, 30 Form 110 Full DLL 106 Full Source Read 145 Functionality 106 funcversion_info 84

G
GAME 51 Game Control 14 GAME in venapp 45, 67 Game Interface 13 GAMEBACKUP|totime 51 GAMEENDGAME 51 GAMEGAMEINTERVAL|value ....................................................................................................................................51 GAMEGAMEON 51 GAMEREADGIN|filename51 GAMEREADVDF|filename|time....................................................................................................................................52 GAMERELOAD 52 GAMEWRITEGIN|filename|savelist ..............................................................................................................................52 Gaming 76 General 110 General Guidelines 11 General Issues 46 General Operation 20 Getting Model Variables 115 Getting Values 97 Global Variables 93 GRAPHVAR txt pos jst acc37

H
Hot Links 97

I
IFTHENELSE 52 Informational Keywords 142 Input Controls 27 Input Screens 14

152

Installation Notes 108 int PASCAL vdde_execute 98 int PASCAL vdde_initiate 99 int PASCAL vdde_poke 99 int PASCAL vdde_request 99 int PASCAL vdde_terminate100 int PASCAL vdde_vrequest99 Introduction 8

J
Justification 29

L
Language Notes 118 Learning with Venapps 10 Letting the User Select a Graph.......................................................................................................................................49 Library Files 108 LINE - pos jst 37 LISTVAR - txt pos acc 37 Literal Arguments 87 Loading 18 Loading and Saving 22 LOG 52 LOGCREATE|filename 52 Logical Flow in Venapps 12 LOGMESSAGE|filename|message .................................................................................................................................52 LOGTIMESTAMP|filename53 Long Lines and Quotes 32 Lookup Arguments 87

M
Main Menu 14, 72 mdl.bat 103 Memory Management 94 Menu 53 MENU

in command scritps 81
Menu and Button Screens 14 MENUDAT2VDF|datafile|vdffile ...................................................................................................................................53 MENUEXIT 53 MENUGAME 53 MENULOAD_RUN 53 MENUREDO_GRAPHS 53 MENURUN_OPTIMIZE|o 53 MENURUN_SENSITIVITY|o........................................................................................................................................54 MENURUN|o 53 MENURUN1|o 53 MENUSENS2TAB|vdffile|tabfile|*!# .............................................................................................................................54 MENUSYNTHESIM

SyntheSim

54

MENUTAB2VDF|tabfile|outfile|form.............................................................................................................................54 MENUVDF2DAT|vdffile|datfile|savelist|+ .....................................................................................................................54 MENUVDF2TAB|vdffile|tabfile|savelist|+*!|frequency|start|end ...................................................................................54 MENUVDF2WK1|vdffile|tabfile|savelist|+*!number .....................................................................................................55 MENUVDF2XLS|vdffile|tabfile|savelist|+*!number ......................................................................................................55 MENUWK12VDF|tabfile|outfile|form ............................................................................................................................55 MENUXLS2VDF|tabfile|outfile|form .............................................................................................................................55 Minimal DLL 106 Miscellaneous 108 Model Files 108

153

Model Setup 71 Modifying Values 91 MODRUNNAME - txt pos jst.........................................................................................................................................38 MODTABLE - txt pos acc 38 MODVAR - txt pos acc 38 Moving Beyond 79 Multiplayer Games 79

N
Notes119, 120, 121, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135 Notes on Memory Alllocation .........................................................................................................................................92

O
odbctest.mdl 149 Opening 14 Other Examples 78 Other files 104 Other Info 116 Output Controls 27 Output Screens 15 Output using Delete and Insert ......................................................................................................................................147 Output Using Update 148

P
Painting PASSWORD txt Path PIXELPOS Plotting Results Preparing Presenting Structure Print PRINT in venapp PROMPT pos jst Purpose of a Venapp 19 39 103 18 111

Files for use with Vensim Application Runtime....................................................................................... 81


72 55 45, 68 39 10

R
RADIOVAR/RADIO1VAR - txt pos acc com................................................................................................................39 Reading 19 Reading from a Database 140 RECTANGLE - pos jst 39 Redistribution 107 Refreshing 19 Retrieving Data 111 Returns119, 120, 121, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135 RUNNAME - txt pos jst 39 Running Screens 15

S
Sample Uses 109 Scenario Setup 73 Screen Controls 21 Screen Definition 21 Screen Definition Dialog 24 Screen Updating 79 Screen-by-Screen Description .........................................................................................................................................13 SCREENFONT 17

154

Screens 16, 17 See Also120, 121, 122, 123, 124, 126, 127, 128, 129, 130, 133, 134, 135 Set Up a Simulation 14 set_gv 84 SETTING 55, 81 SETTINGEURONUMBER|n55 SETTINGEXPORTSIZE|n 55 SettingEXTTERNALFUNCTION|dll name....................................................................................................................55 SETTINGHOVERCOM 56 SETTINGPRINTOPTQUERY|n.....................................................................................................................................56 SETTINGSHOWINITIAL|n56 SETTINGSHOWLOOKUP|n56 SETTINGSHOWMACRO|n56 SETTINGSHOWWARNING|n.......................................................................................................................................56 SETTINGSIZEINCHES|n 56 Setup 18 SETWB - com scr 40 Shift to Screen 32 SHOWCOMPANY pos jst 40 SHOWDATEVAR txt pos jst acc ...................................................................................................................................40 SHOWEDATEVAR txt pos jst acc .................................................................................................................................40 SHOWUSER pos jst 40 SHOWVAR - txt pos jst 40 Simple Database Example149 Simulate 56

command scripts

81

SIMULATE in venapp 45, 68 SIMULATE1TABCHG|varname ....................................................................................................................................57 SIMULATEADDCIN|cinfile57 SIMULATEADDDATA|vdffile......................................................................................................................................57 SIMULATEBASED|oldrun57 SIMULATECHGFILE|cinfile .........................................................................................................................................57 SIMULATEDATA|filelist 57 SIMULATEGETCNSTCHG|varname ............................................................................................................................57 SIMULATEGETTABCHG|varname ..............................................................................................................................57 SIMULATEMINMEM|n 58 SIMULATEOPTPARM|optfile.......................................................................................................................................58 SIMULATEPAYOFF|payfile58 SIMULATEPOSTPROCESS58 SIMULATEREADCIN|cinfile ........................................................................................................................................58 SIMULATEREADRUNCHG|oldfile ..............................................................................................................................58 SIMULATERESUME|n 58 SIMULATERUNNAME|filename|mode ........................................................................................................................58 SIMULATESAVELIST|list58 SIMULATESENSITIVITY|sensfile................................................................................................................................59 SIMULATESENSSAVELIST|list...................................................................................................................................59 SIMULATESETVAL|var=val or var ..............................................................................................................................59 SIMULATEWRITECIN|cinfile ......................................................................................................................................59 Simulating 75 Simulating the Model 111 Simulation compiled vs. interpreted..............................................................................................................................101 Simulation Control 107 Simulation Interface 12 Sketch 59 SKETCH - txt pos jst acc com ........................................................................................................................................41 SKETCHCHOOSEVIEW|sketchname|prompt ...............................................................................................................60 SKETCHNEXTVIEW|sketchname.................................................................................................................................60 SKETCHPREVVIEW|sketchname .................................................................................................................................60 SKETCHZOOM|sketchname|percent..............................................................................................................................60 SLIDEVAR - txt pos jst acc42 SLIDEVARTIE txt 42 SPECIAL 60, 81

155

SPECIAL|ALIASSCREEN|aliasname|screenname .........................................................................................................60 SPECIALASKYESNO|question .....................................................................................................................................60 SPECIALBUTTONFOCUS|n .........................................................................................................................................61 SPECIALCLEARRUNS|n 61 SPECIALEXIT1 61 SPECIALEXTERNAL|funcname ...................................................................................................................................61 SPECIALLOADAPPINT|appname@screen ...................................................................................................................61 SPECIALLOADDLL|dllfile61 SPECIALLOADMODEL|mdlname ................................................................................................................................61 SPECIALLOADRUN|runname.......................................................................................................................................62 SPECIALLOADTOOLSET|toolname ............................................................................................................................62 SPECIALMESSAGE|severe|title|string ..........................................................................................................................62 SPECIALNOINTERACTION|n .....................................................................................................................................62 SPECIALREADCUSTOM|graphfile ..............................................................................................................................62 SPECIALREFRESH 63 SPECIALRESETINPUT 63 SPECIALRUNCOMMAND63 SPECIALSECONDCLICK|graph ...................................................................................................................................63 SPECIALSETFOCUS|number........................................................................................................................................64 SPECIALSETTITLE|title 64 SPECIALSETWBITEM|varname ...................................................................................................................................64 SPECIALSTOP|message 64 SPECIALSTOPSIM|option64 SPECIALSUBSCRIPT|range|elem1|elem2 .....................................................................................................................64 SPECIALVARSELECT|prompt .....................................................................................................................................65 SPECIALWINHELP|helpfile|data...................................................................................................................................65 Specific Variable Read 146 Speeding up a Game 114 SPREADALIAS|?alias=filename.xls ..............................................................................................................................59 Starting a Game 113 Starting the Venapp Editor 20 Startup and Terminate Routines ......................................................................................................................................95 Structure 14 Structure Access 107 Supported Commands 80 SWITCHVAR - txt pos acc com .....................................................................................................................................43 SyntheSim 112 SYNTHESIMAUTO 65 SYNTHESIMGO 65

T
Take-Down 19 Template Application 71 TEST 65, 66 Test Screen 25 Testing the Venapp 25 TEXTMENU - txt pos jst acc com scr ............................................................................................................................43 TEXTONLY - txt pos jst 43 TIMEAXIS 66, 81 TIMEAXISRESET 66 TIMEAXISSPECIALTIME|value...................................................................................................................................66 TIMEAXISSTARTTIME|value ......................................................................................................................................66 TIMEAXISSTOPTIME|value .........................................................................................................................................66 TIMER txt pos jst acc com scr ........................................................................................................................................43 TOOL - txt pos com 44 Tool controls 27 Two General Methods for Presenting Models.................................................................................................................10 Two Main Types of Interface10

U
User Loops 91, 92

156

user_definition 85 Using the Text Editor 12 Using Variable IDs 145 Using Vensim as a DDE Client .......................................................................................................................................98 Using Vensim as a Server 97

V
Values by Scenario 147 VB Controlled Simulation112 Vector Arguments 88 Venapp Basics 15 Venapp Commands 45 Venapp Controls 27 Venapp Editing 20 Venapp Examples 71 Venapp Install Builder 139 Venapp Internal Activity 18 Venapp Introduction 10 Venapps 8 Vensim Application Distribution License .....................................................................................................................138 Vensim Application Runtime137, 138 Vensim Custom Definitions16 Vensim DLL 9 Vensim DLL Overview 106 Vensim DLL Runtime 138 Vensim Info 116 Vensim Interface 101 Vensim Minimal DLL 138 Vensim Model Reader79, 137 Vensim Runtime 137 vensim.ini 106 vensim_be_quiet 118, 119 vensim_check_status 119 vensim_command 120 vensim_continue_simulation121 vensim_external 86 vensim_finish_simulation 121 vensim_get_data 122, 123 vensim_get_dpval 123 vensim_get_dpvecvals 124 vensim_get_info 124 vensim_get_sens_at_time 126 vensim_get_substring126, 127 vensim_get_val 127, 128 vensim_get_varattrib128, 129 vensim_get_varnames 129 vensim_get_varoff 130 vensim_get_vecvals 130 vensim_set_parent_window131 vensim_show_sketch 132 vensim_start_simulation133, 134 vensim_synthesim_vals 134 vensim_tool_command 135 VensimContextAdd 136 VensimContextDrop 136 version_info 84 Visual Basic Example 109 void PASCAL vensim_transmit_dde ............................................................................................................................100

W
WBVAR - pos jst 44

157

Welcome Screen 71 WIPTOOL - txt pos com 44 WORKBENCH 67 WORKBENCH in Venapp 46 Writing to a Database 141

X
X

Y Width Height ............................................................................................................................................... 29

158

También podría gustarte