Simnon tutorial - Part 3 and 4 - UnivAQing.univaq.it/digennaro/Didattica/SNL/Materiale/Simnon -...

65
3DUW 7XWRULDO

Transcript of Simnon tutorial - Part 3 and 4 - UnivAQing.univaq.it/digennaro/Didattica/SNL/Materiale/Simnon -...

3DUW��7XWRULDO

3DUW��7XWRULDO����,QWURGXFWLRQ

3:14

����,QWURGXFWLRQ

The purpose of this tutorial is to provide an introduction to the simulation program Simnon.The conceptual framework is described in Chapter 2. The tutorial then proceeds by givingexamples. Chapter 3 shows how to solve simple differential equations. The solution ofdifference equations is described in Chapter 4. Chapter 5 describes the simulation of morecomplicated systems, which are composed of subsystems. Some advanced features aredescribed in Chapter 6. A few remarks on the implementation are given in Chapter 7. Chapter8 contains information on how Simnon can exchange data with other programs andcomputers. Some more advanced simulation examples are given in Chapter 9. Each chapter isprovided with exercises.

Do not forget to experiment on the screen as you progress with the reading. Rememberthat you can always use HELP and that a detailed description of the language construction isgiven in the reference section of this book. Also remember that a good way to learn Simnon isto start by learning a few commands and expand the vocabulary gradually.

All Simnon specific words are written in capital letters in the manual , but Simnon doesnot distinguish between upper and lower case letters.

������:KDW�,V�6LPXODWLRQ"

Simulation means to imitate the behaviour of a system. Through simulation it is possible tomake investigations without having access to the real system. It is an experiment inside thecomputer. In the simulations, the effects of different initial conditions and parameter valuescan be studied. For instance, in a control system different regulator structures and parametersettings can be investigated. When the performance is satisfactory in the simulation, theregulator may be tested on the real process. Simulation is also a good aid to train operators.For instance, pilots of aeroplanes are trained on a regular basis in simulators.

Simulations can be classified into GLVFUHWH�HYHQW�VLPXODWLRQV and VLPXODWLRQV�RI�G\QDPLFDOV\VWHPV. A typical example of a discrete event simulation is the simulation of queues andoperating systems. Simnon is intended for the simulation of continuous time as well asdiscrete time dynamical systems. Numerical integration routines are used to simulatedifferential equations. Difference equations describing discrete time systems are solved byiterating the equations.

������:KDW�&DQ�6LPQRQ�'R"

Simnon is designed for solving ordinary differential and difference equations and forsimulating dynamical systems. The systems may be described as an interconnection ofsubsystems whose behaviour is characterised by differential equations or by differenceequations. Models of this type are common in mathematics, biology, economics and in manybranches of engineering. Simnon has an interactive implementation, which makes it easy for auser to work with the system. The user interacts with the system by typing commands.Parameters, initial conditions and system descriptions can be modified interactively. The

3DUW��7XWRULDO����,QWURGXFWLRQ

3:15

results are displayed graphically or numerically on the screen. The layout can easily bemodified and the results can be documented using a hard copy facility. Simnon may be used ina very simple way to find solutions to difference or differential equations. This requires onlysix commands. There are over 40 commands in Simnon. The built-in macro facility lets youcreate your own commands.

3DUW��7XWRULDO����)XQGDPHQWDOV

3:16

����)XQGDPHQWDOV

This chapter gives an overview of system descriptions and interaction principles used inSimnon.

������'HVFULSWLRQV�RI�'\QDPLFDO�6\VWHPV

To use Simnon it is necessary to have a basic understanding of dynamical systems,in particular to be familiar with the notions of input, output, and state.

'LIIHUHQWLDO�HTXDWLRQAn ordinary differential equation is a simple form of a dynamical system. The generic form ofdifferential equation is

dx

dtf(x, t)= (2.1)

where [ is a vector of state variables.

'LIIHUHQFH�HTXDWLRQSimnon can also deal with difference equations. The generic form used is

x(t ) f(x(t ), t ), k 1,2,...k 1 k k+ = = (2.2)

Here {t :k 1,2,...}k = is a sequence of discrete time instants called sampling times or samplinginstants and [ is a vector of state variables.

6\VWHPVSimnon can also describe more complicated systems, which are interconnections ofsubsystems. The subsystems can be continuous time systems described by differentialequations or discrete time systems described by difference equations.The generic form of a continuous time system is

dx

dtf(x, t)

y g(x, u, t)

=

=

(2.3)

where X is a vector of inputs, \ a vector of outputs and [ is the state vector. A system like 2.0 isspecified as a CONTINUOUS SYSTEM in Simnon. The analogous form for a discrete timesystem is

x(t ) f(x(t ), u(t ), t )

y(t ) g(x(t ), u(t ), t )k 1 k k k

k k k k

+ ==

k = 1, 2, … (2.4)

3DUW��7XWRULDO����)XQGDPHQWDOV

3:17

The next sampling time WN+1 can be a function of, for instance, [(WN), X(WN), and WN. A systemlike (2.0) is specified as a DISCRETE SYSTEM. In Simnon the state variables of a discretetime system are viewed as piece-wise constant functions of time, which change abruptly at thesampling instants.

Simnon allows a system or a subsystem to be described by either of the forms (2.3) or(2.4). It is also possible to have interconnected systems where the subsystems can have theforms (2.3) or (2.4). Connections are described as a CONNECTING SYSTEM.

������,QWHUDFWLRQ�3ULQFLSOHV

Simnon displays information to the user via a graphical screen, which can show curves, textand numbers. It is also possible to get a hard copy of a picture and to list system descriptionsand display data. Simnon receives information from the user by commands from the keyboard.The commands have the form

COM ARG1 ARG2 ...where COM is the name of the command and ARG1, ARG2, etc. are the arguments.

&RPPDQG�VWUXFWXUHIt is desirable that commands are both short and flexible. One possibility to achieve theseconflicting goals is to use short forms where the arguments are omitted. The arguments arethen given default values, which in many cases are the previously used values. Mostcommands also have initial default values given by the system. The idea is illustrated by anexample. The different forms of the command SIMU, which executes a simulation of asystem, are found from

SIMU [<start time> <stop time> [<increment>][-{CONT|MARK}] [/<filename>[<increment>]]

This description is called the extended Backus-normal form (EBNF), or the extendedBackus-Naur form. The symbol <...> denotes an argument i.e., a number or an identifier.The symbol [a1 a2 ...] denotes options which may or may not appear and {a1| a2|...} denotes options where one alternative must appear. An asterisk (*) denotes repetitions.The syntax for any command is obtained by typing the command HELP followed by the nameof the command. The syntax is then shown in the extended Backus-Naur notation along withsome examples.

For example the commandSIMU 0 100

simulates a system from time 0 to time 100. If we want to repeat the simulation a second timeit suffices to write

SIMUThe previous values of the arguments, i.e., 0 and 100, are then used.

You can also use the menu to run a simulation and this is described in Part 2, chapter2.1.4 Simulate.

It follows from the description that start and stop times and the initial time increment maybe specified. It is also possible to mark curves by using the optional argument MARK. Asimulation may also be continued by using the end conditions of a previous simulation asinitial values. This is done by the command option CONT. The results of a simulation may alsobe stored in a file. The time spacing between the stored values is specified by <increment>.

The command

3DUW��7XWRULDO����)XQGDPHQWDOV

3:18

SIMU ?gives the current values of the simulation times and increments.

������([HUFLVHV2.1 You start Simnon simply by double clicking the icon simnon. You exit Simnon by typingSTOP. Practice this.

2.2 The HELP command has an hierarchical structure. Try to find out about Simnon by using thecommand HELP.

2.3 Type HELP AXES to learn about the command AXES. Experiment with the command and findthe same thing by using Help plot instead.

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:19

����'LIIHUHQWLDO�(TXDWLRQV

The solution of ordinary non-linear differential equations is a simple application of Simnon. Insuch an application Simnon can be viewed simply as a calculator for differential equations.There are two minor differences compared with a calculator. Simnon can display curves. In acalculator a function is activated by pushing a dedicated key. In Simnon functions areactivated by typing a command on the keyboard. How Simnon may be used to solve anordinary differential equation is illustrated by an example.

������7KH�3UREOHP

Suppose that we would like to know the character of the solution to the van der Pol equation

d y

dta(y b)

dy

dty 0

2

22+ − + = (3.1)

for different initial conditions and different values of the parameters D and E. The van der Polequation is a model for an electronic oscillator. The solution to the problem can be dividedinto the following steps:

1. Enter the system description2. Simulate3. Analyse the results4. Change parameters and initial conditions

where steps 2, 3 and 4 are iterated until a satisfactory result is obtained. The different stepswill now be described in some detail.

������(QWHU�WKH�6\VWHP�'HVFULSWLRQ

The equation (3.1) is first rewritten as a system of first order differential equations. Since theequation (3.1) is of second order an extra variable has to be introduced. Choosing this variableas

xdy

dt= the equation (3.1) can be written as

dy

dtx

dx

dtax(b y ) y2

=

= − −

(3.2)

CONTINUOUS SYSTEM vdpol"The van der Pol equationSTATE x y

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:20

DER dx dydy=xdx=a*x*(b-y*y)-ya:1b:1END

/LVWLQJ���� Simnon system for Equation (3.2).

This is the standard state space form used by Simnon. The variables [ and \, which appeardifferentiated are the state variables of the system.

A file, which describes the system, should now be prepared. This file, named vdpol, isgiven in Listing ���. The first line indicates that it is a continuous time system with the namevdpol. The state variables x and y and their derivatives, which are called dx and dy, aredeclared. The differential equations are then defined. Notice the strong similarity withequation (3.2). Finally, values are assigned to the parameters D and E. Simnon distinguishesbetween SDUDPHWHUV and YDULDEOHV. Parameters can be assigned values interactively using thecommand PAR. The notation :́´ is used to assign parameter values in a system description.Variables are defined using the notation ´=´.

The file can be edited using the commandEDIT <filename>

where the argument <filename> is an identifier.When you refer to files in Simnon you should not enter any file extension. The files that

you edit are automatically given the extension .T. The syntax of the system descriptions isdescribed in detail in the reference section. You can list a system description on the screenwith the command

LIST <filename>

������6LPXODWLRQ

To run the system vdpol it must first be activated. This is done by the commandSYST vdpol

If there are any errors during the activation an error message will be given and the errormust be corrected. After the correction a new SYST command must be given.

If we would like to see the solution curves as they are integrated we must first draw axesin a plot window. This is done with the command

AXES H 0 20 V -6 6which means that the ranges of the horizontal (H) and vertical (V) axes are chosen as [0, 20]and [-6, 6]. The command

PLOT x yinstructs the program to plot the variables x and y as functions of time during the simulation.To perform a simulation it is necessary to give appropriate initial conditions to the statevariables. The command

INIT x:1assigns the initial value 1 to the state variable x. Initial values are automatically set to zero ifno assignments are made. We are now ready to make a simulation. The command

SIMU 0 20performs a simulation from time 0 to time 20, and the result shown in Fig.��� is obtained. Ifyou have forgotten the order given in the PLOT command you can check the current plot listby giving the command

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:21

PLOT ?How to label the plots is described in Section 6.2.

)LJXUH���� Simulation of the van der Pol equation for D=1 andE=1 with initial values [(0)=1 and \(0)=0. The state variables[ and \�are plotted as functions of time.

������+RZ�WR�,QWHUUXSW�D�6LPXODWLRQ

Sometimes when you make a simulation you will find that it does not proceed as expected. Itis then useful to be able to break the operation immediately. The status line will contain a"progress bar", showing how far the simulation has gone. At the same time the simulationbutton in the toolbar will be modified to a red stop symbol. Click this button to stop theSimulation.

������&KDQJLQJ�3DUDPHWHUV

Suppose that it is of interest to explore how the solution to the differential equation dependson the parameters D and E. The command

PAR b:2assigns the value 2 to the parameter E.

SIMUJust type SIMU to repeat the simulation over the same time interval as in the previoussimulation.

Current values of all states, derivatives, variables and parameters may be displayed. Thecommand

DISPdisplays all current data on the screen. Selective displays of the parameter a, the states x andy is done by the command

DISP a x yThe display may also be directed to the log file. A simple way to find out how the

command DISP works is to typeHELP DISP

������6WRULQJ�DQG�'LVSOD\LQJ�5HVXOWV�RI�D�6LPXODWLRQ

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:22

It may be useful to store some results, to compare results from different simulations and toplot different state variables in different diagrams. Suppose for example that we would like tocompare the results for the parameter sets D=1, E=1 with those for D=1, E=2. Two data files arefirst generated. The command

PAR a:1PAR b:1

sets the parameters. The commandSTORE x y

tells that the state variables x and y should be stored. The current list of variables to be storedis obtained by the command

STORE ?The command

SIMU/B1then performs a simulation and stores x and y in a file called B1. The value of b is set to 2 by

PAR b:2and the command

SIMU/B2simulates and stores the results in file B2. The command

SPLIT 2 1splits the screen into two rows with one plotting area each. The command

ASHOW x/B2plots the variable x from file B2 in the first window using automatic scaling. The command

ASHOW y/B2plots the variable y from file B2 in the second window.

)LJXUH���� Solution of the van der Pol equation for E = 1 and E = 2.

The commandsAREA 1 1SHOW x/B1AREA 2 1SHOW y/B1

plots the variables x and y from file B1 in the first and second windows respectively. AREAselects the active plot area. The advantage of the combination of STORE and SHOW (orASHOW) over the PLOT command is that several variables can be stored and displayed indifferent diagrams after the simulation. The disadvantage is that it is not possible to see theresult until the simulation is finished.

To document the results it is useful to generate a hardcopy of the curves obtained. Thecommand

HCOPY

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:23

takes a snapshot of the graphs on the screen. Further details are obtained by giving thecommand

HELP HCOPY.The command

SPLIT 1 1resets plotting to just one area in the current plot window.

)LJXUH���� Phase plane plot of the van der Pol equation forD = 1, E = 1, [(0) = 1, \(0) = 0.

������3KDVH�3ODQH�3ORWV

For second order differential equations it is often useful to visualise the results as phase planeplots. This may be done simply by

AXES H -4 4 V -3 3SHOW y(x)/B1

This command plots y as a function of x. The result obtained by using this command isshown in Fig.���.

������*HQHUDOLWLHV

The general way of using Simnon as a "calculator for differential equations" will now begiven. The generic form of a system description is given in Listing ���.

CONTINUOUS SYSTEM <identifier>"General differential equation comment

STATE < identifier > ¼ < identifier >

DER < identifier > ¼ < identifier >

TIME < identifier >

declarations

computation of auxiliary variables

computation of derivatives

parameter assignment

initial value assignment

body

END

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:24

/LVWLQJ���� Generic form of system description for simulation of differential equations.

The system description starts with CONTINUOUS SYSTEM <identifier>. It is terminatedby a line which contains END. An identifier is a letter followed by at most 7 letters and digits.Both upper and lower case letters may be used. Simnon does not distinguish between them.The system description has two parts, a declaration part and a body.

There are three types of declarations. The state variables and their derivatives are declaredby the keywords STATE and DER followed by a list of the state variables and the derivatives.The derivatives and the state variables are associated by their sequential order in the lists. Atime variable may be declared for simulation of time varying differential equations. This isdone by the keyword TIME followed by an identifier.

The body of the system description specifies the derivatives of the state variables in termsof state variables and parameters. Auxiliary variables may also be used. The body alsocontains assignment of parameters and initial values. Please note that a variable may only bedefined once. The order of the statements in the body is unimportant. The statements will besorted into appropriate order by the SYST command.

([SUHVVLRQV�DQG�RSHUDWRUVThe expressions available in Simnon are similar to those in a procedural language like Algolor Pascal. An expression may be a numeric constant or a variable. It may also be combinationsof variables, operators and functions. Conditional expressions of the formIF...THEN...ELSE are also permitted. Simnon has arithmetic, relational and logicaloperators. All variables are floating point numbers. The numbers are written in theconventional way as 4, 1.1, or 6E7. The result of a Boolean expression is 1.0 if it is true and0.0 if it is false.

$ULWKPHWLF�RSHUDWRUVThe arithmetic operators are addition, subtraction, multiplication, division and exponentiation.They are denoted as

+ - * / ^respectively. For instance,

v = - 2a

b + c

5

is written

v = -2 * a^5 / (b + c)

5HODWLRQDO�RSHUDWRUVThere are two relational operators, namely greater than, and smaller than. They are denoted by

> <Please note that there is no equality.

/RJLFDO�RSHUDWRUVThe logical operators are AND, OR, and NOT.

)XQFWLRQVThe standard mathematical functions are available. The details are given in the referencesection. See Part IV-Section 2.6.

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:25

������6XPPDU\

We have seen that Simnon can solve ordinary differential equations in a very simple way. Todo this the differential equations are first written as a system of first order equations like

dx

dtf(x, t)=

where [ and X are vectors. A continuous time system is then generated in Simnon by declaringthe state variables, i.e., the components of the vector [, and their derivatives. The function I,which defines the right hand side of the differential equation, is then introduced using ordinarymathematical expressions and assignments of parameters. There is no vector notation so allequations must be written in scalar notation. The command LIST can be used to list files. Asimulation may be performed by as few as six basic commands, namely: SYST, AXES, PLOT,INIT, PAR, and SIMU.

In order to edit, manipulate and document results from several different simulations it is,however, also useful to use six additional commands, namely STORE, SHOW, DISP, SPLIT,AREA, and HCOPY.

The HELP command acts as a condensed reference manual.

�������([HUFLVHV3.1 Use EDIT or File|New|Continuous to enter the system description in Listing ���.

3.2 Use the command LIST to list the system you have edited on the screen.

3.3 Repeat the simulation described in this chapter on your own.

3.4 Practice to interrupt a simulation.

3.5 Change parameters with the command PAR and initial conditions with the command INIT andinvestigate how the solutions to the van der Pol equations change.

3.6 Experiment with the commands AXES, SPLIT, SHOW, ASHOW, and AREA.

3.7 Use HELP to investigate the basic simulation commands AXES, PLOT, INIT, PAR, SYST, andSIMU.

3.8 Introduce a formal error in the program in Listing ��� by changing the assignment of dx to dx =a*x*(b-y*y-y). Try to activate the incorrect program using the SYST command.

3.9 Use HELP to investigate the auxiliary commands STORE, SHOW, DISP, ASHOW, SPLIT, andAREA.

3.10 Look at the commands LIST, LP, and HCOPY and learn how to get hardcopies of listings andplots on your system.

3.11 Consider the following van der Pol equationε y'' + (y² - 1) y' + y = a

Investigate the limit cycles obtained for ε= 0.05 and 0.993 < a < 1.

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:26

3.12 The following equations called the Volterra-Lotka equations represent a simple model for thedevelopment of two competing species

dx

dt(a by)x

dy

dt(cx d)y

= −

= −

3.13 Make a Simnon system to study the equations. Start with the following nominal values: D = 2.7, E= 0.7, F = 1 and G = 3.

3.14 A simple model for an orbiting satellite is given by

d²r

dt²r

dj

dt

k

r²d²j

dt²

2

r

dr

dt

dj

dt0

2

= −

+ =

where U is the radius from the centre of the earth, ϕ the azimuth angle and N a gravitationalconstant. Write a Simnon system and simulate the equations.

3.15 Simulate the differential equations

dx

dta(y x), x(0) 8

dy

dtbx y xz, y(0) 8

dz

dtcx xy, z(0) 24

= − = −

= − − = −

= − + =

where D = 10, E = 28, and F = 8/3. Look in particular at ] as a function of [. The equation, whichis called the Lorenz equation, is an example of a deterministic system, which has a very irregular (chaotic)behaviour.

3.16 A Simnon system, which describes a three-body problem, is listed below

CONTINUOUS SYSTEM threbod"A planar threebody system

TIME tSTATE x vx y vyDER dx ax dy ay

r1=sqrt(x*x+y*y) "distance to the earthr2=sqrt((a-x)*(a-x)+y*y) "distance to the moondx=vxdy=vyF1=k*m1/(r1*r1) "gravitational force of the earthF2=k*m2/(r2*r2) "gravitational force of the moonax=-F1*x/r1+F2*(a-x)/r2 "x-component of accelerationay=-F1*y/r1-F2*y/r2 "y-component of acceleration

"The total energy is computed to check the resultsE=(vx*vx+vy*vy)/2-k*m1/r1-k*m2/r2

"Scaled variables used for plottingxs=x/a

3DUW��7XWRULDO����'LIIHUHQWLDO�(TXDWLRQV

3:27

ys=y/a

x:-6.37e6 "satellite initially behind the earthvy:11080 "initial velocity [m/s]

k:6.67e-11 "gravitational constant [Nm^2/kg^2]m1:5.977e24 "mass of the earth [kg]m2:7.349e22 "mass of the moon [kg]a:3.844e8 "average distance from moon to earth [km]

END

Write the differential equations that describe the system.

3DUW��7XWRULDO����'LIIHUHQFH�(TXDWLRQV

3:28

����'LIIHUHQFH�(TXDWLRQV

It is also possible to simulate difference equations with Simnon. This is done analogously tothe simulation of differential equations. An example is first given and the general principlesare then stated.

������([DPSOH

Consider the following difference equation

x x rx (1 x ), k 0,1,...k 1 k k k+ = + − = (4.1)

This is a simple model of a population dynamics. The variable [N�denotes the number ofindividuals at time N in a normalised scale. There is an equilibrium value [=1 at which thepopulation remains constant. For [N ≈ 0 the population increases by the factor 1+U in eachgeneration. For [N>1 the population will decrease. Assume that it is of interest to investigatehow the population changes with time. A difference equation is represented as a DISCRETESYSTEM in Simnon. The description of a system which simulates the difference equation (4.1)is given in Listing 4�1.

DISCRETE SYSTEM popdyn"Simple model for population dynamicsSTATE xNEW nxTIME kTSAMP tsnx=x+r*x*(1-x)ts=k+1x:0.5r:2END

/LVWLQJ�4�1 Simnon system for simulation of the difference equation (4.1).

The state variable is declared in the same way as for a continuous time system using theSTATE declaration. The declaration NEW is used to declare the variable nx, which denotes thenew value of the state variable i.e. [N+1. NEW is thus the analogy of DER for continuous timesystems.

When simulating difference equations it is necessary to provide a mechanism for makingthe state variables change at certain sampling times. For example the state variable in equation(4.1) changes periodically at N = 1, 2,... In the general case there may, however, be irregularsampling. The mechanism used to describe this in Simnon is to introduce a variable of thetype TSAMP which gives the next sampling time. In Listing (4.1) the first assignmentstatement is simply a definition of the right hand side of the difference equation (4.1). Thesecond line: ts=k+1 assigns the value k+1 to the TSAMP variable ts. This variable givesthe time when the system is run the next time.

3DUW��7XWRULDO����'LIIHUHQFH�(TXDWLRQV

3:29

)LJXUH�4�1 Simulation of population dynamics with U=0.2, 2.7, and 2.83.

������6LPXODWLRQ

Discrete time systems are run in the same way as continuous time systems. A simulation isthus executed by the commands

SYST popdynSPLIT 3 1AXES H 0 80 V 0 2PLOT xPAR r:0.2SIMU 0 80

This generates the uppermost curve in Fig 4�1. The commands

AXESPAR r:2.70SIMUAXESPAR r:2.83SIMU

repeat the simulation for U = 2.70 and U = 2.83, and plot the corresponding curves shown inFig 4�1. Notice that the behaviour of the solutions changes drastically with moderate changesin the parameters.

3DUW��7XWRULDO����'LIIHUHQFH�(TXDWLRQV

3:30

)LJXUH�4�2 Graph of the function I([) = [([+3)([+2)([-2)([-3) generated by Simnon.

������*UDSKV�RI�)XQFWLRQV

Simnon is conveniently used to obtain a graph of a function. Assume for example that wewant a graph of the polynomial

f(x) x(x 3)(x 2)(x 2)(x 3)= + + − −

This is accomplished by the following system.

DISCRETE SYSTEM pol"Defines a polynomialTIME xTSAMP zf=x*(x+3)*(x+2)*(x-2)*(x-3)z=x+dxdx:0.05END

The commands

SYST polSTORE fSIMU -3.6 3.6ASHOW f

will then generate the graph in Fig 4�2. Please note that the curve is not smooth because thefunction was defined using a discrete time system. The variables in a discrete time system areassumed to be constant between the sampling instants. If a smooth curve is desired it is betterto use continuous systems.

Simnon is also conveniently used to generate level curves, field plots and conformal maps.To illustrate such applications consider for example the problem of finding the image of thelines arg ] = π/2 and arg ] = 3π/4 in the conformal map

G(x) e e e (cosy isiny)z x iy x= = = ++

This may be accomplished by the system

DISCRETE SYSTEM expz

3DUW��7XWRULDO����'LIIHUHQFH�(TXDWLRQV

3:31

"Generates the function exp(z)TIME rTSAMP sfi=alfa*pi/180x=r*COS(fi)y=r*SIN(fi)ReG=EXP(x)*COS(y)ImG=EXP(x)*SIN(y)s=r+drdr:0.01pi:3.1415926alfa:90END

The commands

SYST expzAXES H -1 1 V 0 1.5PLOT ImG(ReG)SIMU 0 3.14PAR alpha: 135SIMU 0 4.44

then generate the curves shown in Fig 4�3.

DISCRETE SYSTEM <identifier>"General difference equation commentSTATE identifier ... identifier

NEW identifier ... identifier

TIME identifier

TSAMP identifier

< > < >< > < >< >

< >

declarations

computation of auxiliary variables

computations of new values of the states

update the TSAMP variable

parameter assignment

initial value assignment

body

END/LVWLQJ�4�2 Structure of Simnon system for simulating difference equations.

������*HQHUDOLWLHV

The general form of a description of a discrete time system is given in Listing 4�2. Thestandard form used in Simnon is a system of first order difference equations. It may benecessary to introduce auxiliary variables to obtain this form. The description of a discretetime system is analogous to a continuous time system.

The only difference is that DER is replaced by NEW and that the sampling variable TSAMPmust be declared and assigned.

3DUW��7XWRULDO����'LIIHUHQFH�(TXDWLRQV

3:32

)LJXUH 4�3 Graph of the map of the rays arg ] = π/2 and arg ] = 3π/4 in the map *(]) = H].

������6XPPDU\

Difference equations are simulated in the same way as differential equations. The systemdescription DISCRETE SYSTEM is used instead of CONTINUOUS SYSTEM. Thesimulation commands are the same as for differential equations. The six basic commandsAXES, PLOT, INIT, PAR, SYST, and SIMU and the six auxiliary commands STORE, SHOW,DISP, SPLIT, AREA, and HCOPY are very useful.

������([HUFLVHV4.1 The difference equation

x1

2x

a

xk 1 kk

+ = +

is a well known algorithm for computing the square root of D. Write a discrete system in Simnonand explore the algorithm.

4.2 Modify the simulation program in the previous exercise so that the stationary solution to theequation is computed and plotted.

4.3 The following is a simple Keynesian model of a macro economic system

y(t) c(t) i(t) g(t)

c(t) ay(t 1)

i(t) b(c(t) c(t 1))

= + += −= − −

where \ is the gross national product, F consumption, L investment and J governmentexpenditures. Write the equations as a system of first order difference equations and simulate the equations.Investigate the response of the system to a sudden increase in government spending. What are the influences ofthe parameters D and E? Try the values D = 0.75 and E = 0.5, 1 and 2.

4.4 Investigate the properties of the following difference equation

x(t 1) r(x²(t) y²(t))e

y(t 1) x(t)

0.1(x²(t) y²(t))+ = ++ =

− +

3DUW��7XWRULDO����'LIIHUHQFH�(TXDWLRQV

3:33

for different values of the parameter U.

4.5 Modify the simulation which gave Fig 4�2 so that a smooth curve is obtained.

3DUW��7XWRULDO����6\VWHPV

3:34

����6\VWHPV

Many systems can often be viewed as interconnections of subsystems, which are representedby differential or difference equations. The difference equations typically arise whenmodelling regulators implemented by digital computers. To represent subsystems, declarationsof inputs and outputs are added to the system descriptions. The system descriptions areotherwise the same as the CONTINUOUS SYSTEM and the DISCRETE SYSTEM describedpreviously in Chapters 3 and 4. A special type of system is introduced to describe theinterconnections. This system is called a CONNECTING SYSTEM. The possibility ofdecomposing a model into subsystems may also be useful in other contexts, particularly whendealing with large systems.

Consider the control system shown in Fig.5�1 which is a combination of two subsystems: aregulator, which is a discrete time system, and a process, which is a continuous time system.The subsystems can be described as follows

DISCRETE SYSTEM piregINPUT yr yOUTPUT u...END

CONTINUOUS SYSTEM procINPUT uOUTPUT y...END

where the details of the system descriptions are omitted. The interconnections between thesystems are described by a CONNECTING SYSTEM as follows

CONNECTING SYSTEM conn"Connecting system for pireg and procTIME tyr[pireg]=1y[pireg]=y[proc]u[proc]=u[pireg]END

It may be tempting to place a connecting system in a file called con. This cannot be doneon 06�'26 machines because con is a reserved word that refers to the console device. Seeyour 06�'26 manual for this and other reserved words. Notice that states, variables, andparameters are local to each subsystem. Variables belonging to different subsystems can beaddressed by appending the system name in square brackets to the variable name. Notice thatexpressions may be used to describe the interconnections. Constructions like

y[pireg] = IF t1 THEN 0 ELSE SIN(k*y[proc])are thus possible.

3DUW��7XWRULDO����6\VWHPV

3:35

The simulation of an interconnected system is done using the same commands as was usedto simulate difference or differential equations. The only difference is that it is necessary toactivate all subsystems that describe the interconnected system. This is done by the command

SYST proc pireg connThe connecting system must be the last subsystem in the list. The order of the subsystems

is otherwise irrelevant. Continuous and discrete systems may be mixed freely.

Regulator Process

)LJXUH�5�1 Block diagram of an interconnected system.

������6LPXODWLRQ�RI�D�'LJLWDO�&RQWURO�6\VWHP

A continuous time process controlled by a computer implemented regulator is convenientlydescribed as an interconnected system. The process may be represented as a CONTINUOUSSYSTEM and the digital controller as a DISCRETE SYSTEM.

Listing 5�1 describes a feedback loop consisting of a continuous time process called procand a digital PI regulator called pireg. The process is an integrator with input saturation.The interconnections are described by the connecting system conn.

CONTINUOUS SYSTEM proc"Integrator with input saturationINPUT uOUTPUT ySTATE xDER dxupr=IF u<-0.1 THEN -0.1 ELSE (IF u<0.1 THEN u ELSE 0.1)dx=upry=xEND

DISCRETE SYSTEM pireg"Discrete time PI regulator with anti-windupINPUT yr yOUTPUT uSTATE iNEW niTIME tTSAMP tse=yr-yv=k*e+iu=IF v<ulow THEN ulow ELSE (IF v<uhigh THEN v ELSE uhigh)ni=i+k*e*h/ti+u-vts=t+hk:1 "regulator gainti:1 "reset timeh:0.5 "sampling periodulow:-1 "lower limit of control signal

3DUW��7XWRULDO����6\VWHPV

3:36

uhigh:1 "upper limit of control signalEND

CONNECTING SYSTEM conn"Connecting system for pireg and procTIME tyr[pireg]=1y[pireg]=y[proc]u[proc]=u[pireg]END

/LVWLQJ�5�1 Simnon description of a simple control loop consisting of a continuous time process and a discretetime PI regulator.

The following annotated dialogue illustrates how Simnon is used.

&RPPDQG $FWLRQSYST proc pireg conn Activate the system.STORE yr y[proc] upr Select variables to be stored.SIMU 0 40 Simulate.SPLIT 2 1 Form two plot areas.ASHOW y yr Draw y and yr with automatic scaling

in the first area.ASHOW upr Draw upr with automatic scaling in secondarea.

Please note that the names are local to each subsystem. To distinguish between variableswith the same name in different subsystem the name of the subsystem is appended to thevariable name as in y[proc]. Variables can be transmitted between subsystem by declaringthem as inputs and outputs.

The results of the simulation are shown by the oscillatory curves in Fig 5�2.The discrete nature of the control actions generated by the control computer are clearly

visible in the curves. It should be noticed that the outputs and the state variables of a discretetime system are defined for all times. They are constant between the sampling instants andthey change abruptly at the sampling instants. These curves show that there is a considerableovershoot due to wind-up of the integral. This can be avoided by telling the regulator what theprocess limitations are. The commands

PAR ulow:-0.1PAR uhigh:0.1

change the necessary parameters. The commands

SIMU 0 40AREA 1 1SHOW yAREA 2 1SHOW upr

show that the overshoot is reduced significantly. Compare Fig 5�2.

3DUW��7XWRULDO����6\VWHPV

3:37

)LJXUH�5�2 Results of simulation of process control with a PI regulator. The curveswith a large overshoot correspond to an ordinary regulator. The welldamped set ofcurves are obtained with a regulator with overshoot inhibition (anti reset wind-up).

������*HQHUDOLWLHV

Simnon allows three types of system descriptions, namely CONTINUOUS SYSTEM,DISCRETE SYSTEM, and CONNECTING SYSTEM. A CONTINUOUS SYSTEM is used tomodel a subsystem represented by ordinary differential equations. A DISCRETE SYSTEM isused to model a subsystem described by difference equations. The CONNECTING SYSTEMdescribes how the subsystems are interconnected. The complete syntax for the systemdescriptions is given in the reference section in Part IV of this manual.

������([HUFLVHV5.1 Look at the syntax of the commands SYST and SIMU using HELP. What are the differencesbetween simulation of a single system and an interconnected system?

5.2 Assume that the variable y is used in two subsystems in an interconnected system. Use the digitalcontrol example to find out what happens when you try to display or plot the variable. What diagnosis isproduced? How can the variables be separated?

5.3 Consider the system in the example. Repeat the simulation on your own computer. Investigatethe consequences of changing the sampling period h.

5.4 Study the general form of the system descriptions.

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:38

����$GYDQFHG�)HDWXUHV

Simnon may be used in many different ways. So far we have described problems, which maybe solved by using only a dozen commands. This is sufficient for many applications. For moredemanding problems there are, however, several additional features. These may all beexplored by using HELP or by reading the reference section in Part IV of this book. A briefdescription of some useful features will be given here to indicate some possibilities.

������6DYLQJ�DQG�5HWULHYLQJ�'DWD

The command SAVE stores the current parameters and initial values in a file. The values maybe retrieved by the command GET. These commands are very useful when working with largemodels, because parameters and initial values for different operating conditions can then bestored in files instead of in the system descriptions.

Assume for example that the systems pireg, proc, and conn have been activated as inSection 5.1 by the command

SYST pireg proc connThe command

SAVE par51then generates a file par51.t of the form

[pireg]i:0.k:1.ulow:-1.uhigh:1.h:0.5ti:1.[proc]x:0.[conn]

The parameter values can be retrieved later by giving the commandGET par51

������/DEHOOLQJ�3ORWV

When preparing plots for reports it is convenient to label the plots. This can be done using thecommands TEXT and MARK. With the command

TEXT ’<string>’the text defined by <string> is displayed at the top of the current plotting area. The text is thusplaced in a predefined place. It is also possible to place text at any place in a plot windowusing the command MARK. For instance

MARK A 3 4

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:39

will move the text cursor to position x=3 and y=4 in the displayed coordinate system from thereference point. This is defined as the lower left corner of the plot area. The text cursor canalso be moved relative to its current position by giving the command

MARK R 1 -2This will change the horizontal position with 1 unit and the vertical with -2 units. Text can beinserted at the current position by the command

MARK "<string>The text string after the quote is then displayed. For instance the marking procedure can bedone as follow.

TEXT ’State variable x and y marked red and blue’MARK A 22 1.2MARK "Time t

A more natural method is to control the co-ordinates for text interactively with the mouse.See the command GIN in the reference section in Part IV.

������0DFURV

Commands are normally read from the terminal. It is, however, useful to have the option ofreading a sequence of commands from a file instead. This is done by the construction

MACRO name arg1 arg2 ...Command1Command2END

This implies that the commands 1 and 2 are not executed directly but stored in a file. Themacros may also have arguments as shown above. The command sequence or macro isactivated simply by typing name followed by possible arguments.

Macros are very useful. Once created, a macro can be used like an ordinary Simnoncommand. The macros can thus be used to extend Simnon with user defined commands. Thisis convenient for implementation of a dialogue. Command sequences, that are commonlyused, may be defined as macros. A simple macro call will then perform a whole sequence ofcommands. A typical example may be creation of standard plots for a given simulation. Theusefulness of macros may be extended considerably by introducing commands to control theprogram flow in a macro, facilities for handling local and global variables and by allowingmacros to have arguments. The macro facility used in Simnon has these features. By havingcommands for reading the keyboard and for writing on the screen it is also possible toimplement question and answer dialogues using macros. The macros are also very convenientfor documentation. When a successful simulation is completed we can just create a macrowhich contains the commands of a complete simulation. The simulation is then repeatedsimply by typing the name of the macro created. As an illustration we give the followingmacro which generates Fig 5�2.

MACRO mpiregSYST proc pireg connSTORE yr y[proc] uprSIMU 0 40/wupPAR ulow:-0.1PAR uhigh:0.1

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:40

SIMU /nowupSPLIT 2 1ASHOW y yr/wupSHOW y/nowupTEXT ’Output y and yref’MARK A 21 8.8MARK "Time tASHOW upr/wupSHOW upr/nowupTEXT ’Control variable u’MARK A 21 1.2MARK "Time tEND

Macros for generating all the figures in this tutorial are given in Appendix A. Even acasual user is strongly recommended to learn simple uses of the macro facility. Moreexamples using macros are given in Chapter 9.

It is possible to get help on user-defined programs and macros. For instance the commandHELP mpireg

gives the replyGenerates Fig 5�2

The help given consists of the first contiguous block of comment lines in the program ormacro.

����� � ([FKDQJLQJ� 9DULDEOHV� EHWZHHQ� D� 6\VWHP'HVFULSWLRQ�DQG�D�0DFUR

Writing x=3 (or x:3) in a system description and LET x=3 from the keyboard or in a macroare two completely different things. In the first case, an auxiliary variable (or a parameter) isassigned a value in a system description. In the second case, a command variable is assigned avalue in a macro or from the keyboard. Although the variables both happen to have the namex, they have nothing to do with each other. However, it would be valuable to be able to usesimulated values to control simulation experiments, e.g. within macros.

Simnon provides a means of FRS\LQJ simulated values from a system description to globalcommand variables. By using the following form of DISP, the value of the simulated variable<variable> will be copied to the global command variable <ident 1>.[<ident 2>]:

DISP <variable> / <ident 1>[-<ident 2>].The macro below carries out a parameter sweep, i.e., varies the parameter a in the system

tank over an interval in order to find an optimal value, based on a goodness number calculatedon the variable x:

MACRO asweepLET avalue=0 "Initialize parameter valueLET gvalue=0 "and goodness number

FOR sweep=1.5 TO 2.5 STEP 0.2PAR a[tank]: sweep "Change the parameterSIMUDISP x[tank] / x-tank "Copy x[tank] (from system

"description) to x.tank (global "command variable)

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:41

LET r=x.tank*x.tank "Compute the goodness numberIF r LT gvalue GOTO continue "Any improvement?

LET avalue=sweep "If so: Remember the currentLET gvalue=r "parameter value and goodness

"numberLABEL continueNEXT sweep

WRITE ’Optimal parameter value: ’avalueEND

������2UJDQLVDWLRQ�RI�/DUJH�6LPXODWLRQV

There are several facilities which are useful when working with large systems or with largeamounts of data. System descriptions and macros are stored as text files. Please note thatlower case letters may be used to get a more readable code, although Simnon does notdistinguish them from upper case letters. The subsystems also have a name which is theidentifier given on the first line of the system description. Notice that the file name and thesystem name may be different. This is very useful when simulating different versions of amodel because the same macros and the same connecting systems may be used provided thatthe names of the inputs and the outputs are the same. The selection of a particular model ismade when the systems are activated by the command SYST. To illustrate the ideas considerthe simulation in Section 5.1. Assume that we would like to perform the same simulation witha different process model. Let the new process model have a system name proc defined by thefirst line in the description. The system is stored in a file called proc2. Furthermore assumethat the model has input u and output y. The systems are activated by the command

SYST pireg proc2 connwhere the connecting system conn and the regulator pireg are the ones used in Section 5.1.The simulation can now be performed with exactly the same commands as in Section 5.1.

������'RFXPHQWDWLRQ

It is often useful to keep a running log of an interactive session. The commands

SWITCH LOG ONSWITCH TRACE ON

generate a file simnon.log of all commands in a session. A very convenient way todocument a simulation is to create such a file and use it to edit suitable macros. It is alsopossible to enter text into the log file by using the command WRITE. System descriptions canbe entered into the file by the command LIST and parameter values can be entered by thecommand DISP. By a proper use of these commands it is possible to create a file, which is arough draft of a report for a simulation. The diagrams created in a simulation can also begiven a useful format. The axes can be marked and text can be added by the commands MARKand TEXT. This feature has been used in the macros, which generate the curves in this tutorial.See Appendix A.

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:42

������,QWHJUDWLRQ�$OJRULWKPV

Simnon uses numerical integration to solve the differential equations in a continuous system.The default integration method in Simnon is a Runge-Kutta algorithm of order 4/5 due toFehlberg, RKF45. There is, however, several other integration algorithms implemented andthe user can choose which one to use with the command ALGOR. Another way is to selectOptions... under Simulate in the menu where the algorithms are presented. Thepossible choices are

EULER Simple first order integration algorithm.RKF23 A Runge-Kutta algorithm of order 2/3 due to Fehlberg.RKF45 A Runge-Kutta algorithm of order 4/5 due to Fehlberg (default).DOPRI45R A state of the art Runge-Kutta algorithm of order 4/5 due to

Dormand and Prince.The accuracy of an integration algorithm is related to its order. High order implies better

accuracy, but it also requires more calculations at each step. This is compensated for by thefact that high order algorithms take longer steps and hence need fewer to solve a specificproblem. Which algorithm to use depends on the circumstances, but in general a high ordermethod should be preferred to a low order. (For a thorough discussion of different integrationalgorithms see the referenced books in Chapter 10 of this tutorial.)

The current integration algorithm is displayed by giving the commandALGOR ?

$XWRPDWLF�6WHS�VL]H�$GMXVWPHQW�DQG�(UURU�7ROHUDQFHAll the integration algorithms except EULER include algorithms for automatic step-sizeadjustment. The integration algorithm will internally try to estimate the error of the numericalsolution, and choose a step-size such that this error does not exceed the error tolerance (theerror tolerance is set using the ERROR command). The default value is 10-3. The current valueis displayed with the command

ERROR ?The algorithm can use long steps when the differential equation is easy to solve

numerically and short steps when it is hard to solve. However, with a fixed step-size it isnecessary to choose it as short as the shortest step-size needed during the whole integrationinterval. It is often very inefficient to use this step-size throughout the whole simulationinterval.

Automatic step-size adjustment normally works very well. There are, however, caseswhere the standard algorithm may fail. The implementation of the DOPRI45R algorithmincludes a new regulator algorithm for step-size adjustment. This algorithm is superior to thestandard algorithm in RKF23 and RKF45, and will in general handle the cases where thedefault algorithm fails.

It is important to note that keeping the error estimate below the error tolerance does notimply that the numerical solution will have an accuracy of the order of the error tolerance.Small errors may add up during the integration and eventually become much larger than theerror tolerance. It is therefore good practice to simulate a problem at several tolerance levelsand compare the results in order to get convinced that the solution is sufficiently accurate.

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:43

The EULER algorithm uses a fixed step-size. It is up to the user to choose a step-size sothat the error in the numerical solution is acceptable. The step-size is chosen through the thirdargument in the SIMU command, i.e.

SIMU 0 200 0.5means simulate from 0 to 200 using the step-size 0.5. If the third argument is omitted, it willbe inherited from the previous SIMU command. Specifying a value of zero causes SIMU toadjust the step-size to one hundredth of the simulation interval (this is the start-up default).If the third argument in the SIMU command is supplied when using an integration algorithmwith automatic step-size adjustment it is interpreted as the maximum allowed step-size. Thisuser-imposed limit on the step-size may force the integration algorithm to use shorter (andthus more) steps than necessary when solving the differential equation. Consequently, theintegration will take unnecessary long time. If the aim is a solution with better accuracy thenuse the ERROR command instead of limiting the step-size.

A high order integration algorithm will due to its better accuracy in general take longersteps than a low order algorithm. When simulating combinations of discrete and continuoussystems the integration algorithm can never take longer steps than the sampling interval. If thesampling interval is short, it may therefore be more efficient to use a low order algorithm.

([DPSOH���� 7KH�HUURU�WROHUDQFH��ERROR�To demonstrate how the ERROR command effects the accuracy of a simulation an examplefrom astronomy, the restricted three-body problem, will be studied. Consider two bodies withmasses 1-µ and µ, and a third body with negligible mass moving around in a plane. Theequations are

( ) ( )

( )

( )( )( )( )( )

y y 2y 1-y

D

y 1

D

y y 2y 1-y

D

y

D

D y + y

D y + y

y

1 1 21

1

1

2

2 2 12

1

2

2

1 1 2

2 1 2

1

’’ ’

’’ ’

.

/

/

= + − + −− −

= − − −

= +

= − −

=

µ µ µµ

µ µ

µ

µ

2 23 2

2 23 2

1

0 012277471

Using the initial values

y (0) 0.994

y (0) 0

y ’(0) 0

y ’(0) 2.0015851061

2

1

2

==

== −

results in a periodic orbit with period 7 = 17.065216560. It should be remarked that thisproblem is very sensitive to small changes in the initial values. The single precisioncalculation in Simnon is not sufficient to generate a periodic solution. The solution should,however, be close to the starting point at time 7.

The problem was simulated in Simnon (the Simnon code is shown in Listing 6�1) from 0to 7 using the standard Simnon set-up, i.e. an error tolerance at 10-3, the integration algorithmRKF45, and no third argument in the SIMU command. The result is shown as curve 1 inFigure 6�1. The curve is clearly not periodic, and although the error estimate was kept below

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:44

10-3 the final errors are much larger. The reason is that small errors in the beginning of thesimulation will propagate and eventually cause a large global error.

)LJXUH�6�1 The satellite orbit simulated using RKF45 and error tolerance 10-3 (1) and 10-4 (2).The state y2 is plotted as function of state y1.

CONTINUOUS SYSTEM orbit"Three body system for Fig 6.1 and 6.2STATE y1 y1dot y2 y2dotDER dy1 dy1dot dy2 dy2dotdy1 = y1dotdy2 = y2dotdy1dot = y1+2*y2dot-(1-mu)*(y1+mu)/d1-mu*(y1-(1-mu))/d2dy2dot = y2-2*y1dot-(1-mu)*y2/d1-mu*y2/d2d1 = ((y1+mu)*(y1+mu)+y2*y2)^(3/2)d2 = ((y1-(1-mu))*(y1-(1-mu))+y2*y2)^(3/2)mu : 0.012277471y1 : 0.994y1dot : 0y2 : 0y2dot : -2.001585106END

/LVWLQJ�6�1 Simnon code to implement the equations in Example 6.1.

The result can be improved by decreasing the error tolerance. Using ERROR it was set to 10-4

and the simulation was redone. The second curve in Figure 6�1 shows a notable improvementre-made over the previous simulation.

To improve the accuracy by limiting the step-size, i.e. supplying a third argument to theSIMU command it is necessary to limit the step-size to a very small value, and consequentlythe simulation will take a very long time.

([DPSOH���� 'LIIHUHQW�LQWHJUDWLRQ�DOJRULWKPV��ALGOR�

Again, consider the astronomy example in Example 6.1.Figure 6�2 shows the result of simulating it using RKF45 (curve 1) and RKF23 (curve 2).

In both cases the error tolerance was set to 10-4 and no third argument was supplied in theSIMU command. Still, the result from RKF23 is inferior to the one from RKF45. The reasonis that RKF23 has lower order than RKF45 and therefore requires more steps to solve theproblem. Both methods will at each step keep the error estimate close to the error tolerance,

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:45

but since the number of steps are larger for RKF23 the resulting global error will also belarger.

The previous example should not be regarded as a general criticism against RKF23. Theresult only reflects the order difference between RKF45 and RKF23. A step in RKF23requires less computations than one in RKF45, and there are situations where this wouldmake RKF23 favourable to RKF45. Suppose, for instance, that the problem includes adiscrete system with short sampling interval. If the sampling interval is so short that it restrictsthe step-size of RKF45 then it would be better to instead use RKF23, since that would requireless computation, thus making the simulation run faster.

'LVFRQWLQXLWLHVSimnon allows the user to define systems with discontinuities, e.g.

dx = if t<t1 then amp1 else amp2Such systems are hard to integrate numerically. The numeric solution to the problem is onlycalculated at discrete points, and the result may be different depending on how these pointsare related to the time instant of the discontinuity. If the time instant of a discontinuity isknown it is good advice to place the generation of that signal in a discrete system. WhenSimnon integrates combinations of continuous and discrete systems it will integrate up to thesampling instance of the discrete system, execute the code in it, and then continue theintegration up to the next sampling. Hence, by choosing the sampling instances of the systemcontaining the discontinuous signals sensibly, it is possible to make Simnon always handlethese signals correctly.

([DPSOH�����'LVFRQWLQXRXV�LQSXW�VLJQDOConsider a first order system with two input signals

x’’ x p p

p40 10 t 10.025

0 otherwise

p40 20 t 20.025

0 otherwise

1 2

1

2

= − + +

=< <

=< <

Both p1(t) and p2(t) are short pulses with energy equal to one, and when simulating the systemfrom 0 to 30 one expect to see the impulse response of the first order system, once at W=10 andonce W=20. The simulation was made (the Simnon code is listed in Listing 6�2) and theresulting [ is plotted in the upper diagram of Figure 6�3. Only the first pulse response appearsin the plot. The reason is that the differential equation is easy to integrate numerically andconsequently Simnon will use long steps. These steps are much longer than the duration of thepulses and Simnon will pass the time of pulse 2 without noticing it. The code to generate p1(t)is identical to the one for p2(t), but instead of being included in the continuous system it wasput in a separate discrete system. This discrete system calculates its sampling instances so thatit will be sampled only when p1(t) changes value. Simnon integrates up to these timeinstances, notices the change, and then continues the integration.

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:46

)LJXUH�6�2 The astronomy example simulated using 5.)�� (1) and 5.)�� (2).

In both cases the error tolerance was set to 10-4, and y2 is plotted as a function of y1.

Simnon could be forced to notice also the second pulse by manipulating the value of themaximum step-size. The lower diagram of Figure 6�3 shows the result of SIMU 0 300.025, i.e. the step-size is restricted to a maximum value which is equal to the pulseduration. Simnon will now manage to detect also the second pulse, but the integration is veryinefficient due to the small step-size.

DISCRETE SYSTEM pulse"Generates discrete time pulseTIME tTSAMP tsOUTPUT p1p1=IF t<t1 THEN 0 ELSE (IF t<t1+eps1 THEN 1/eps1 ELSE 0)ts = IF t<t1 THEN t1 ELSE (IF t<t1+eps1 THEN t1+eps1 ELSE1E6)t1 : 10eps1 : 0.025END

CONTINUOUS SYSTEM firstord"First order systemTIME tINPUT p1STATE xDER dxdx=-x+p1+p2p2=IF t<t2 THEN 0 ELSE (IF t<t2+eps2 THEN 1/eps2 ELSE 0)t2 : 20eps2 : 0.025END

3DUW��7XWRULDO����$GYDQFHG�)HDWXUHV

3:47

)LJXUH�6�3�The output of the first order system simulated using 5.)�� and errortolerance 10-3. The upper diagram shows the result of 6,08����� and the lower one theresult of 6,08�����������.

CONNECTING SYSTEM conpulse"Connecting system for firstord and pulsep1[firstord]=p1[pulse]END

/LVWLQJ�6�2 Simnon code to implement the equations in Example 6.3.

������([HUFLVHV6.1 Test the relation between accuracy, error bound, and step-size by experimenting with Examples6.1 and 6.2.

6.2 Experiment with the system in Example 6.3 to find out how a discrete time system can be used toinclude discontinuities.

3DUW��7XWRULDO����6RUWLQJ�DQG�6LPXODWLRQ

3:48

����6RUWLQJ�DQG�6LPXODWLRQ

When using Simnon it is helpful to have some insight into how the program works. Forexample, when activating a collection of subsystems using the command SYST we may get adiagnosis "algebraic loop detected". This is explained in this chapter. Further the computationsperformed at the simulation are explained.

������:KDW�+DSSHQV�:KHQ�D�6\VWHP�,V�$FWLYDWHG"

The activation of systems by the command SYST is central to Simnon. It causes Simnon toread one statement at a time from the files mentioned in the command line. If a statement iscorrect, it will be translated to instructions for the "Simnon machine", a hypotheticalcomputer. (For the technically interested person, the Simnon machine has a pure stackarchitecture, and its instructions are referred to as Pseudo-code or just P-code.) When asubsystem is completely translated, Simnon checks that all local quantities are defined exactlyonce. When all subsystems are translated, their interconnections are checked for consistency.

Once the P-code is complete, it will be sorted into a correct sequence for execution. Thisallows the user to write the statements in an arbitrary order. (Section 7.2 describes a specialsituation, where the sorting fails.) The sorting also minimises the computation work for thesimulation engine by treating time-invariant, initial, derivative, discrete and continuouscomputations separately. The P-code is finally translated into machine code, which permitsvery efficient simulations.

It is possible to store the sorted statements in a text file by using the optional argument/<filename>. The command

SYST pireg proc conn/dummygenerates a file called dummy.t with the content:

SORTED INITIAL EQUATIONS

SORTED TIME-INDEP. EQUATIONSconn yr[pireg] = 1

SORTED DERIVATIVE EQUATIONSproc y = xconn y[pireg] = y[proc]pireg e = yr - y v = k*e + i u = IF v<ulow THEN ulow ELSE IF v<uhigh THEN v ELSE uhighconn u[proc] = u[pireg]proc upr = IF u<-0.1 THEN -0.1 ELSE IF u<0.1 THEN u ELSE 0.1 dx = upr

SORTED CONTINUOUS EQUATIONS

SORTED DISCRETE EQUATIONS

3DUW��7XWRULDO����6RUWLQJ�DQG�6LPXODWLRQ

3:49

pireg ni = i + k*e*h/ti + u - v ts = t + h

The subsystem name is given to the left and the statement to the right. The statements aresorted so that the calculations may be performed in sequential order so that all variablesneeded at a particular stage have already been computed.

The order of the sorting can be influence by the user by introducing the keywordsINITIAL and SORT in the system descriptions. This means that all statements between thekeywords are sorted as a group before the statements after the keyword SORT. This feature isuseful, for example, when some calculations are required to obtain initial conditions for asimulation.

������$OJHEUDLF�/RRSV

When systems are interconnected it may happen that the statements cannot be sorted so thatthe variables may be calculated sequentially. A simple example, which illustrates what mayhappen is given below.

CONTINUOUS SYSTEM s1INPUT uOUTPUT yy = uEND

CONTINUOUS SYSTEM s2INPUT uOUTPUT yy = uEND

CONNECTING SYSTEM cyr = 1u[s1] = yr + k*y[s2]u[s2] = y[s1]k: 0.5END

When the commandSYST s1 s2 c

is given the error diagnosis "algebraic loop detected" is given. The attempt to sort thestatements results in

s1 y = uc u[s2] = u[s1]s2 y = uc u[s1] = yr + k*y[s2]s1 y = u

The variable u[s1] thus cannot be solved sequentially. A simple calculation shows that thevariable is given by the following algebraic equation:

3DUW��7XWRULDO����6RUWLQJ�DQG�6LPXODWLRQ

3:50

u[s1] = yr + k*u[s1]This explains the name algebraic loop. In this particular case it is easy to solve the equationfor u[s1] if k ≠ 1. In the general case the algebraic equation may be non-linear. It is thendifficult both to determine if a solution exists and to find it when it does. Simnon will notattempt to find a solution. It will just give an error message. The presence of an algebraic loopis often an indication of poor modelling.

������:KDW�+DSSHQV�:KHQ�D�6\VWHP�,V�6LPXODWHG"

When a simulation is triggered by the command SIMU, the following steps will be taken:Time-invariant computations are first made. Then initial computations follow, provided thatthe user did not inhibit them with the CONT (continued simulation) option.

The repetitive part of the simulation is now entered. If a discrete system is due, then itsstates will be updated. Connected derivatives and continuous time variables will also becomputed. Finally, the future values of the discrete states and the sampling time are computed.All variables in the discrete system are then kept intact until the next time it is due (zero-orderhold action).

Continuous systems will now be processed collectively up to the nearest future samplinginstant (or to the end of the simulation interval, whichever is closest). Two kinds ofcomputations are made: function evaluations (static) and numerical integration of differentialequations (dynamic).

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:51

����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

Since Simnon is a pure simulation tool, data exchange paths to other programs are desirable.The following methods for data exchange with other programs are supported by Simnon:

• DDE-links• Import and export of time series• Export of plots• Importing Linear, Time-invariant Systems

������'\QDPLF�'DWD�([FKDQJH��''(�OLQNV�

Simnon/PCW supports dynamic data exchange links to other programs. This is a sophisticatedfeature in Windows. In such links, data is shared among two or more programs. The programthat supplies the data is called the VHUYHU, and the program that initiates the request for dataand receives the data is called the FOLHQW.

The DDE feature makes Simnon an excellent tool for simulators, where an animationprogram such as InTouch (Wonderware Corp, Irvine, California, USA) can be applied as auser interface. The simulation can be controlled (Start, Stop and parameter change commands)from the interface, and the Simnon model gives the simulator realistic properties.

It is most important that you study and fully understand the DDE documentation that issupplied together with your client program to get full advantage of Simnon´s DDEcapabilities.

��������%ULHI�''(�WHUPLQRORJ\

DDE is a form of inter-process communication that uses shared memory to exchangeinformation between applications. Simnon acts as the DDE server and one or moreapplications are DDE clients. Basically, information can be exchanged between Simnon andthe client(s) in the following ways:

• 5(48(67 Whenever Simnon receives a UHTXHVW from a client, information istransferred.

• $'9,&( If a client has specified that it wants to be DGYLVHG wheneverinformation has been modified, the information is continually kept updated.

• 81$'9,&( Unadvice is used whenever a client wants to inform Simnon thatadvice of a variable is no longer wanted.

• 32.( For certain topics, Simnon accepts that the client can SRNH informationto the server.

• (;(&87( The client can request that Simnon H[HFXWHV a specified command.

Please refer to the documentation for your specific client program for detailed informationabout its capabilities to send various message types to Simnon.

��������''(�OLQNV�LQ�6LPQRQ

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:52

The DDE information is defined by three properties; 6HUYHU, 7RSLF and ,WHP.

• 6HUYHU is always 6LPQRQ• 7RSLF and ,WHP can be any of the following:

Topic Item Description Note

6\VWHP 6\V,WHPV List of all available items in topic System6\VWHP 7RSLFV List of all available topics6\VWHP )RUPDWV List of all available formats6\VWHP �FRPPDQG! Send command to Simnon E6\VWHP +HOS Brief help information'DWD 6\V,WHPV List of all available items in topic Data'DWD 6\VW6WDWXV Status flag: 1 if SYST has been successfully

completed, otherwise 0'DWD 6LPX6WDWXV Status flag: 1 if simulation is in progress,

otherwise 0'DWD 3URJUHVV Simulation progress in percent (0-100)'DWD 6WHS Number of simulation steps since the

simulation was started'DWD 6WHS'LYHUJH If poked; min. no. of simulation steps before

each 6WHS DGYLFHP

'DWD 7LPH%HJLQ Simulation begin time'DWD 7LPH(QG Simulation end time'DWD 7LPH Simulation time'DWD 7LPH'LYHUJH If poked; min. time diverge before each 7LPH

DGYLFHP

'DWD 9DOXH'LYHUJH If poked; min. diverge before each 9DOXHDGYLFH

P

'DWD �FRPPDQG! Send command to Simnon E7LPH 6\V,WHPV_�WLPH! Item list | Topic for WLPH variables6WDWH 6\V,WHPV_�VWDWH! Item list | Topic for VWDWH variables,QSXW 6\V,WHPV_�LQSXW! Item list | Topic for LQSXW variables2XWSXW 6\V,WHPV_�RXWSXW! Item list | Topic for RXWSXW variables,QLW 6\V,WHPV_�LQLW! Item list | Topic for LQLW values P'HU 6\V,WHPV_�GHU! Item list | Topic for GHU variables1HZ 6\V,WHPV_�QHZ! Item list | Topic for QHZ variables7VDPS 6\V,WHPV_�WVDPS! Item list | Topic for WVDPS variables3DU 6\V,WHPV_�SDU! Item list | Topic for SDU parameters P9DU 6\V,WHPV_�YDU! Item list | Topic for YDU auxiliary variables

Notes:

P: This item can be poked.E: Use EXECUTE communication mode to this topic to execute a Simnon command.

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:53

��������''(�OLQNV�EHWZHHQ�6LPQRQ�DQG�([FHO���DQ�H[DPSOH

To transfer data from Simnon to a cell in Excel during simulation of the Lorenz equations (anexample shipped with Simnon) you enter the following formula in the cell: 6LPQRQ_6WDWH�¶<>/25(1=(4@¶

A ‘progress bar’ that shows the simulation progress can easily be designed in Excel:

1. Enter� 6LPQRQ_'DWD�3URJUHVV in a cell.2. Make a bar diagram of the content of the cell. Scale 0-100.3. Ready!

��������''(�FRPPDQGV�WR�6LPQRQ

Commands WR Simnon can be sent in several ways:

• As a System Command, which is in the format”6LPQRQ_6\VWHP�6LPXODWH_%UHDN” sent to topic System. This is a way toemulate menu commands. The ‘&’ character precedes underscored menu characters, and isoptional.

• An alternative to sending a system command in this form is using the numeric equivalent,

as defined in the SADK documentation, e g ”6LPQRQ_6\VWHP����” which equals”Break Simulation”

• As a Command Line Command, corresponding to any command normally entered on

Simnon’s command line. The topic is Data, and the correct format is”6LPQRQ_'DWD�¶6LPX������¶” The command line prompt ‘!‘ may be included:”6LPQRQ_'DWD�¶!6LPX������¶”

If the command line prompt is included, a Simnon command can also be sent to topic System:”6LPQRQ_6\VWHP�¶!6LPX������¶”

Please refer to the documentation for your specific DDE client program regarding the correctuse of the characters |, � and ¶.

��������%ORFN�''(

%DFNJURXQGNormally, a DDE link supplies data from only one variable to the client.However, if you want to transfer a large amount of data, this method can be very inefficient,as a lot of computer capacity is consumed just for the communication itself, rather than on thenumeric information that you want to convey. Also, in some cases the number of DDEchannels that can be opened simultaneously is limited.

For this reason Simnon has, from version 3.0, a new proprietary function called ‘BlockDDE”. When this is called, the message returned from Simnon contains information abouttwo or more variables.

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:54

Example: You want to read an object’s position in a three dimensional co-ordinate systemduring a simulation:

Alternative 1: Create three different DDE links, transferring x, y and z respectively.Alternative 2: Create a Block DDE link, specifying that x, y and z all shall be part of everymessage.

%ORFN�''(�6\QWD[Topic Item Descriptio

nNote

%ORFN

<variablelist>

Item list

The <variable list> has the following syntax:

�YDULDEOH�W\SH!��YDULDEOH�QDPH!>�>@_>YDULDEOH�W\SH@��YDULDEOH�QDPH!@

where <variable type> is WLPH, SDU, YDU or VWDWH and <variable name> is any variable that ispart of a sub system which has been SYSTed in Simnon. <variable type> can be omitted, aslong as the type of the following variable(s) is (are) the same as last specified type. If theSimnon system name is part of the variable name, it should be placed within brackets (‘[‘ and‘]’)

Example of <variable list>:

VWDWH�[>ORUHQ]HT@�\�]�GHU�G\>ORUHQ]HT@

The only limitation in the <variable list>specification is the length of the total string. It maynot be longer than 255 characters.

5HWXUQ�YDOXHVThe return value from Simnon is a string containing the actual values for each variable, withspace (ASCII character 20) as delimiter. Please note that when Simnon cannot return a certainvalue, the text NAN (Not A Number) is returned. Hence, the number of characters in a returnstring can vary.

������7LPH�6HULHV

Time series are the inputs and outputs of a simulation. They are stored in a binary format,which only Simnon understands: the store file. The store files have the extension .D. There isa two-way conversion utility between store files and printable form. The latter can be thoughtof as an "esperanto" between such diverse applications as CAD programs, maths/statisticspackages, data bases, spread sheets, etc. Its simplicity also permits migration betweendifferent computers and operating systems. A printable time series file is also referred to as aflat ASCII file.

��������,PSRUWLQJ�7LPH�6HULHVOne important reason to import time series to Simnon is to validate models. This involves twosteps.

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:55

First a time series has to be translated from printable form to Simnon’s binary store fileformat. This is done with the command IMPORT. Then a simulation has to be carried out,where the time series file is made to drive the input signals of the model. This is done bycalling the function RFILE from the model and by supplying the name of the time series filevia the command SIMU.

A printable time series file containing Q records of P variables should have the followingorganisation:

W��� Y���� Y���� ��� YP���W��� Y���� Y���� ��� YP������W�Q� Y��Q� Y��Q� ��� YP�Q�

Here W denotes the time variable (which is recommended but not necessary, since thecommand IMPORT is capable of generating a time ramp). Y1, Y2, ���, and YP�denote therecorded variables. Thus a variable corresponds to a column and a time instant to a line.The format is free, which means that values are separated by one or more spaces, and that e.g.the values 12.34, 1.234e1, 1.234e+1, 1.234E+1 and 1234e-2 are identical.

Suppose that we have a printable time series file, named data1.t, with a time columnand two variables. To translate it into a store file named data1.d and naming the variablestemp and flow, we type the Simnon command:

IMPORT data1 < data1 1 2 temp 3 flow / 3If we accept the default names v1 and v2 for the variables (they are only used by thecommands ASHOW and SHOW anyway), it would have been sufficient to type:

IMPORT data1 < data1 / 3To plot v2 as function of v1, we type:

ASHOW v2(v1)/data1In order to drive a simulation from the variables v1 and v2, we need the discrete systemILOHUHDG described together with the function RFILE in the reference manual.

Assuming that we want to drive a process model called p1 with inputs u1 and u2 fromthe data file, we have to supply the following statements in a connecting system, named e.g.conn.

u1[p1]=v1[fileread]u2[p1]=v2[fileread]

The following commands activate the model and trigger a simulation that will read inputsfrom the store file data1.d:

SYST p1 fileread connSIMU 0 10 // data1

Notice that the simulation will stop prematurely if the data file does not cover the entiresimulation interval.

��������([SRUWLQJ�7LPH�6HULHVA store file is translated into printable form by the command EXPORT. Suppose we have astore file named data2.d containing the variables x, y and z. The following commandtranslates the entire contents of the store file data2.d into the printable time series filedata2.t:

EXPORT data2 < data2Notice that the time column will appear as the first column in data2.t, x as the second, andso on. The time column will be omitted, if we instead type:

EXPORT data2 < data2 -NOTIME

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:56

If we want to export at most 100 lines, starting at time 3.5, we type:EXPORT data2 < data2 100 3.5

If data2 had contained a large number of variables, then each logical line in the printable filewould have been split into a number of physical lines, each one at most 80 characters long. Ifwe would like to have longer physical lines, say 256 characters each, we type:

EXPORT data2 < data2 / 256Finally, if we would like to remove the limitation on the physical line length, we type:

EXPORT data2 < data2 / 0In order to utilise the printable time series file data2.t in Matlab, we enter Matlab and

type the following command:load data2.t

Notice that Matlab, in contrast to Simnon, requires the extension .t. Within Matlab a matrixnamed data2 will result. It will be organized exactly in the same way as the file data2.t.Other program packages have similar mechanisms for receiving tabular data.

������([SRUW�RI�3ORWV

Very often you want to export a plot, created in a Simnon plot window, into another programsuch as a word processor or presentation program. There are basically two ways to do this: useWindows Clip Board, or create a file from the plot.

Using Windows Clip Board is of course straightforward. Just activate a plot (click on it tohighlight its title bar), select (GLW_&RS\ from the menu and switch to the other application,where the plot now can be pasted into the document.

If you use the command +&23<, a file is created. This file can be in EPS, HPGL or bitmapformats. EPS and HPGL files are vectorised, and give print quality output. For furtherinformation about this facility, see the +&23< description in the Command Language sectionof this manual.

������,PSRUWLQJ�/LQHDU��7LPH�LQYDULDQW�6\VWHPVModels comprise the highest level and the most difficult one to standardise. For that reasonSimnon is limited to importing linear, time-invariant dynamic systems, either on state-space oron transfer function form.

��������,PSRUWLQJ�)LUVW�DQG�6HFRQG�2UGHU�7UDQVIHU�)XQFWLRQVMany simulation packages are block oriented, i.e., models are described as networks ofinterconnected building blocks, e.g. adders, multipliers, elementary functions, integrators, etc.Automatic control literature contains many examples of systems composed of first and secondorder linear transfer functions. This special case of a system description is fairly easy totranslate into the state space form required by Simnon by means of the macro SIMNONTF(Simnon Transfer Function).

As an example, consider the transfer function J82(V) = 1/(0.03V + 1). To create its Simnonrepresentation, we enter the Simnon command:

SIMNONTF g82 1 0 0 1 0 .03 1which yields the file g82.t containing:

CONTINUOUS SYSTEM g82

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:57

STATE xDER ndx

" S i m n o n (tm)" Department of Automatic Control," Lund Institute of Technology, Lund, SWEDEN" 1*(0 0 1)/(0 3.E-2 1); 0s; 0 0

INPUT uOUTPUT y

ndx=a*x+uy=b*x

a: -33.3333b: 33.3333END

In general, the transfer function

name(s) gb s² b s b

a s² a s a2 1 0

2 1 0

= + ++ +

is introduced to Simnon by the commandSIMNONTF name g b2 b1 b0 a2 a1 a0

For a discrete transfer function (sample and hold action), a 9th argument, the samplinginterval, has to be supplied as well. Furthermore, if another two arguments, b21 and b20, areentered, an extra output corresponding to:

b s b

a s² a s a21 20

2 1 0

++ +

will result without introducing extra states.Finally, the interactions between the transfer functions have to be expressed as a

CONNECTING SYSTEM. At present this has to be done manually.

��������,PSRUWLQJ�/LQHDU��7LPH�,QYDULDQW�'\QDPLF�6\VWHPV�IURP�0DWODELinear time-invariant, dynamic systems can be transferred from Matlab to Simnon. AlthoughMatlab also has simulation capabilities, Simnon offers faster turn-around, multi-rate samplingand the ability to combine continuous and discrete subsystems.

Given a matrix-set $, % and & and, optionally, a '-matrix and an [0-vector in Matlab, thefunction simnon (which is a Matlab-function!) is invoked to produce a continuous ordiscrete system and, optionally, a template for a connecting system.

([DPSOH

Consider the continuous systemdx

dt[ 2, 1,2,0]x [0,1]uy [10]u= − − + =

3DUW��7XWRULDO����'DWD�([FKDQJH�ZLWK�2WKHU�3URJUDPV

3:58

By typing the Matlab commandsimnon(’sc1’, 0, [-2, -1; 2, 0], [0; 1], [1, 0])

the Simnon system description file sc1.t will result:

CONTINUOUS SYSTEM sc1" Linear, time-invariant Simnon system" Note: Needs a CONNECTING system to drive input signals" Created in Matlab by simnon.m V1.00 at 1989-11-2 15:32:33" Dept. of Automatic Control" Lund Institute of Technology, Lund SWEDEN" **Code optimization attempted; opt=0 overridesINPUT u1OUTPUT y1STATE x1 x2DER dx1 dx2a1_1: -2dx1=a1_1*x1-x2dx2=x1+u1y1=x1" --3 redundant adds removed (37%)" --7 redundant mults removed (87%)END

The general syntax for the Matlab function simnon is:simnon(linsys,dt,a,b,c,d,x0,consys,opt)linsys name of Simnon linear system description (file linsys.t)dt sampling interval (0 for continuous time)a,b,c,d system matrices (d is optional; default 0)x0 initial state vector (row or column; optional; default 0)consys name of Simnon connecting system template; merely defining linsys

inputs as 0 (file consys.t; should be edited by the user; optional)opt optimisation = 0 or 1. If 1, redundant adds and mults will be removed;

use opt=0 if structure matters (optional; default 1)

1RWHVSimnon needs a connecting system to drive the input signals. For large systems auxiliaryvariables named _1, _2, etc. may appear. To omit an optional argument, do not enter it orspecify it as [ ].

Typing help simnon within Matlab will display the above information on the screen.

3DUW��7XWRULDO����([DPSOHV

3:59

����([DPSOHVIn this chapter two examples are given to illustrate the potential of Simnon. The first exampleis a simulation of a wind power plant. The attempt is to show how a larger simulation inSimnon may be organised. The full details of the process are, however, not discussed. In thesecond example it is shown how the command language can be used to make computations inconnection with simulations. A simple one-dimensional search is implemented to tune oneparameter in a system.

������6LPXODWLRQ�RI�D�:LQG�3RZHU�3ODQW

A mathematical simulation of a large horizontal axis wind turbine system is presented in thissection. The model is developed for a wind power plant in Maglarp, Sweden. The wind powerplant is run by Sydkraft AB and has a rated power of 3 MW. The rotor has a diameter of 78 mand the height of the tower is 80 m. The model is discussed in detail in Mattsson (1984) andBergman et al. (1983). See Chapter 10 of this tutorial. The intention is to show how a largersystem can be modelled and simulated in Simnon. The model can be used to investigatesituations such as synchronisation of the wind turbine against the utility grid, influence ofwind disturbances, and emergencies caused by faults in the plant or in the electrical network.

When developing a model for a complex system it is important to use a modular and wellstructured approach. Particular attention should be given to the modularization. The model isdivided into subsystems to make it easy to modify the model and adapt the complexity of asubsystem to the case to be simulated. To make the model manageable some simplifyingassumptions are made.

1. The synchronous generator is connected via an impedance to an infinite bus.2. The moment of inertia of the gearbox and shafts is neglected.3. The rotor is perpendicular to the wind.4. The blades of the rotor are torsionally rigid and the pitch servo is not affected by the wind.

The process can now be represented by the block diagram in Figure 9�1. The block diagramdefines input and output connections for the different subsystems. The different subsystemsare described as continuous time Simnon systems. To increase the flexibility, the inputs andoutputs of the subsystems are chosen as unscaled physical quantities in SI units. However, toimprove the numeric, scaled quantities are used inside the subsystems. Figure 9�2 shows ablock diagram of the used voltage controller. Listing 9�1 is the Simnon system VOLTCONT,describing the controller. The voltage controller is a simple system with only three states. Thelisting shows, however, how a large Simnon program may be structured. Notice, for instance,that the program is called VOLTCONT while the file is stored under the name VOLTC1. Thismakes it possible to use the same connecting system for simulation of different voltageregulators or other subsystems. The comments contain a short description and references tothe author and articles. All the parameters are collected into one section, which gives thenames and units for the parameters. The other Simnon programs needed for the simulation areincluded in the distribution kit of Simnon.

3DUW��7XWRULDO����([DPSOHV

3:60

)LJXUH�9�1 Block diagram showing the model structure of the wind power plant simulation.

)LJXUH�9�2 Block diagram of the voltage controller described in Listing 9�1.

The wind power plant is simulated using the macro in Listing 9�2. After the SYST commandinitial values are obtained from the file inival. The file gives, for instance, the initial valuesfor the states and parameter values. The simulation shows the responses when the wind ischanged. Figure 9�3 shows the wind disturbance, the generated power and the pitch angle ofthe rotor blades. The increase in the wind speed around W=10 increases the generated power,and the pitch angle is controlled to keep the generated power around 100%. The macro showshow a simulation can be documented for later inclusion in a report. Table 9�1 gives a summaryof the complexity of the simulation. For instance, the total number of states is 36 and there are139 parameters in the subsystems.

3DUW��7XWRULDO����([DPSOHV

3:61

CONTINUOUS SYSTEM VOLTCONT

"File: VOLTC1""Version: 1984-02-23""Author: Sven Erik Mattsson" Department of Automatic Control" Lund Institute of Technology, Sweden""Description:" IEEE Type 1 excitation system representation including" nonlinear saturation effects for a continuously acting" regulator and exciter without input filter.""Reference:" IEEE Committee Report (1968): Computer Representation" of Excitation Systems. IEEE Trans. on Power Apparatus" and Systems, Vol. PAS-87, June 1968, pp. 1460-1464.

INPUT vt vs

OUTPUT vf

STATE xA xF xE

DER dxA dxF dxE

"Inputs:" vt terminal voltage [V]" vs auxiliary input signal [V]

"Outputs:" vf generator field voltage [V]

"States:" xA rectifier voltage [pu]" xF internal state in feedback loop [pu]" xE generator field voltage [pu]

Verr = (Vref - vt + vs)/VnormdxA1 = (KA*(Verr+yF) - xA)/TAdxA2 = if (xA>VRmax and dxA1>0) then 0 else dxA1dxA = if (xA<VRmin and dxA2<0) then 0 else dxA2

SE = 0.17*xE*abs(xE)dxE = (xA - SE - KE*xE)/TEvf = Vnorm*xE

bF = KF/TFdxF = (bF*xE - xF)/TFyF = xF - bF*xE

"Parameters:Vref: 6800. "reference voltage [V]Vnorm: 6600. "base voltage [V]KA: 400. "regulator gain

3DUW��7XWRULDO����([DPSOHV

3:62

TA: 0.02 "regulator amplifier time constant [s]VRmax: 7.3 "maximum rectifier voltage [pu]VRmin: -7.3 "minimum rectifier voltage [pu]KE: 1.0 "exciter constantTE: 0.8 "exciter time constant [s]KF: 0.03 "regulator stabilizing circuit gain [s]TF: 1.0 "regulator stabilizing circuit time "constant [s]END

/LVWLQJ�9�1 Listing of the program describing the voltage controller in Figure 9�3.

MACRO mwindpowSYST gust1 bus1 gen1 gear4 voltc1 servo1 turb6 pitchr2 cwindGET inivalSTORE Vvel Pep betadegERROR 0.0001PAR tg0:1.0SPLIT 3 1AXES H 0 40 V 14 24AXES V 90 140AXES V -12 -2AREA 2 1PLOT PepSIMU 0 40/simuresAREA 1 1SHOW vvel/simuresAREA 3 1SHOW betadeg/simuresMARK A 2.33 14.64"1 13.5MARK "[m/s]MARK A 2.33 9.53"1 9MARK "[%]MARK A 2.33 4.42"1 4.5MARK "[deg]MARK A 4.86 14.64"3 13.5MARK "Wind speedMARK A 4.86 9.53"3 9MARK "Generated powerMARK A 4.86 4.42"3 4.5MARK "Pitch angle

END

/LVWLQJ�9�2 Listing of macro to simulate the wind power plant.

3DUW��7XWRULDO����([DPSOHV

3:63

0 10 20 30 40

14

18

22

0 10 20 30 40

90

110

130

0 10 20 30 40

-12

-8

-4

[m/s]

[%]

[deg]

Wind speed

Generated power

Pitch angle

)LJXUH�9�3 Simulation of the responses to a wind disturbance of the wind power plant.

6\VWHP 6WDWHV 9DULDEOHV 3DUDPHWHUV ,QSXW 2XWSXW:,1' 0 8 9 0 3%86 0 0 9 0 3*(1 7 53 22 7 6*($5 1 12 9 2 292/7&217 3 6 10 2 16(592 1 1 3 1 1785%,1) 11 121 29 5 23,7&+5(* 13 79 48 3 17RWDO �� ��� ��� �� ��

7DEOH�9�1 Summary of the number of states etc, for the wind power plant simulation.

3DUW��7XWRULDO����([DPSOHV

3:64

������8VLQJ�6LPQRQ�IRU�2SWLPLVDWLRQ

Consider the problem where one regulator parameter has to be optimised based on evaluationsof the results from several simulations of the step response of the control system. Theoptimisation is made by Golden Section. This algorithm is based on the assumption that thereis only one local minimum of the loss function. Only function evaluations are used and noinformation about partial derivatives is used.

7KH�3UREOHPA motor for positioning is controlled using feedback from measurement of the angle \(W) andthe velocity. The system is described by the differential equation for the motor

d²y

dt²

dy

dtu(t)+ =

and the regulator

u(t) K(y (t) y(t)) Tdy

dtr= − −

where \U is the reference value, Κ is the proportional gain and Τ is the velocity feedback. It is

assumed that Κ=1 and that the parameter Τ should be optimised. The step response isevaluated according to the ITAE criteria.

( ) ( )J(T) | y y |dr

0

t

= −∫ τ τ τ τ

7KH�,GHD�%HKLQG�WKH�2SWLPLVDWLRQ�$OJRULWKPThe optimisation algorithm is based on the only assumption that the loss function has onelocal minimum. The algorithm uses only information about the value of the loss function. Noinformation about partial derivatives is used. Initially, an upper and lower bound of theparameter to be determined must be given . The algorithm evaluates the loss function for asmall number of different values of the parameter in the interval. The algorithm is in factoptimal in the sense that it uses the least number of evaluations of the loss function for a givendesired accuracy.

The algorithm is easy to understand. The idea is shown in Figure 9�4. Start with threeevaluations of the loss function -(3): at the end of the interval 3ORZ and 3KLJK, and at a thirdpoint 3PLQ. 3PLQ is the value of the parameter, that gives the current smallest value of the lossfunction. Based on these values a fourth point 3 is chosen and the loss function is evaluated.Based on the value of the loss function at this point, the interval of uncertainty of the optimalparameter can be reduced. The fourth point 3 is chosen symmetrical with respect to 3PLQ inthe interval of uncertainty, since no a priori information about the location of the minimum isavailable.

3DUW��7XWRULDO����([DPSOHV

3:65

)LJXUH�9�4 The principle used in the golden search algorithm.

This rule to choose "the fourth point" in the remaining interval of uncertainty is applied ineach iteration. Thus, the initial choice determines subsequent choices of 3 to be evaluated. Agood choice of initial value is dependent on how many evaluations that should be made. Ananalysis shows that the optimal choice of initial value 30 when 1 evaluations should be doneis

P 0 PF

F(P P )0 low

N 1

Nhigh low= + −−

where )1 and )1-1 are two subsequent Fibonacci numbers. The final uncertainty of 3 is after1 evaluations (3KLJK-3ORZ)/)1. These results can be found in for instance Luenberger (1984).

6WUXFWXUH�RI�WKH�&RGHThe performance of the control system should be evaluated by simulation for each value of theregulator parameter. The different simulations are used by the optimisation procedure and theresults displayed. The macro facility in Simnon could be used to make the optimisation.However, it is more convenient to write the optimisation algorithm as a discrete time systemand let this subsystem control the start-up of each "simulation" of the control system. Thus,the many simulations are combined to one long simulation where the optimisation is viewedas a dynamical systems and for each step, the process is reset and the step response evaluated.

Three subsystems are connected by the connecting system tune. They are: process,which contains motor and regulator, the loss function loss, and the optimisation algorithmlinopt. Each step in the optimisation starts with a given value of the velocity feedback 7from linopt, then the step response of the process is evaluated by loss, and the valueof -(Τ) is obtained at the end of the step. linopt then uses the value -(Τ) to calculate thenext value of Τ to be tested, and the initial values of the process and loss are reset. Sinceloss depends on time, a local time tau is introduced, which is set to zero at the start of eachstep response. A practical device is the signal alarm. If the loss function -(Τ) grows above acertain level, alarm is set true and the output in process is frozen. In this way a poorchoice of Τ that gives unstable control actions will not cause overflow and terminate thewhole simulation. The programs are found in Listings 9�3 - 9�6. The subsystem linopt can,

3DUW��7XWRULDO����([DPSOHV

3:66

of course, be used in other applications where one parameter should be optimised. However,the reset of process and loss is done from linopt. Thus, these lines of the code must bechanged when linopt is used in another application.

+RZ�WR�5XQ�WKH�2SWLPLVDWLRQAfter the user has specified the loss function and how long simulation time that should beused for evaluation, it is only needed to give a simple command that runs the optimisation. Amacro search has been written for this purpose. See Listing 9�8. The input parameters arethe bounds 3ORZ and 3KLJK�and the desired accuracy of the optimal 3. Given this information,the number of evaluations needed is calculated and displayed for the user. At this point thecommand SUSPEND is given. If the user decides there are too many evaluations and does notwant to start the optimisation, he gives the command END. Otherwise, he gives the commandRESUME and the optimisation is started with the calculated optimal starting point 30, and itruns to the end.

It is a good idea to follow the optimisation and plot the different step responses for eachvalue of the parameter Τ�as they are evaluated. After the optimisation the final step responsecan be inspected. It may also be interesting to take a look at the actual loss function -(Τ) andhow the parameter Τ converged. The macro msearch generates Figure 9�5 along these lines.

)LJXUH�9�5 The result of an optimisation of one parameter.

See Listing 9�7. Note the command TURN DARK ON, which affects how the diagrams areplotted. It implies that the lines are eliminated that combine the end point of one evaluationwith the start point of the next. In Figure 9�5 the result from one optimisation is shown , wherethe optimal value of Τ is searched over the interval [0,2]. To obtain the desired accuracy 12evaluations of the loss function are made. The parameter Τ converges to a value that gives theclosed loop system a damping of about 0.75. Without velocity feedback (Τ=0) the closed loopdamping is 0.5.

DISCRETE SYSTEM linopt"Discrete system to perform optimization of one parameterINPUT JOUTPUT Peval tbeginSTATE Plo Phi Pmin P JminNEW qPlo qPhi qPmin qP qJmin

3DUW��7XWRULDO����([DPSOHV

3:67

TIME tTSAMP ts

"Update the search state:left = P<middecr = J<JminPloFix = IF t<1.5*teval THEN 1 ELSE MOD(left+decr+1,2)PhiFix = IF t<1.5*teval THEN 1 ELSE MOD(left+decr,2)unc = newPhi-newPlo "Uncertainity interval.mid = (Phi+Plo)/2 "Midpoint of the interval.newPlo = IF PloFix THEN Plo ELSE IF decr THEN Pmin ELSE PnewPhi = IF PhiFix THEN Phi ELSE IF decr THEN Pmin ELSE PnewPmin = IF decr THEN P ELSE PminqJmin = IF t>0.5*teval AND decr THEN J ELSE JminqPlo = IF t>1.5*teval THEN newPlo ELSE PloqPhi = IF t>1.5*teval THEN newPhi ELSE PhiqPmin = IF t>0.5*teval THEN newPmin ELSE PminqP = Peval"Calculate the new evaluation point Peval:Peval = IF t>0.5*teval THEN newPhi+newPlo-newPmin ELSE Pmin"Reset process and loss-function after each test:x1[process] = 0x2[process] = 0x1[loss] = 0"New sample:ts = t+tevaltbegin = t

"Initial values that should be set by the userPlo : 0.0 "Lower bound of parameterPhi : 1.0 "Upper bound of parameterP : 0.61803 "Golden section ratioJmin : 1E33 "Max real valueteval: 20 "Simulation time for evaluation

END

/LVWLQJ�9�3 Simnon code /,1237 for the optimisation algorithm.

CONTINUOUS SYSTEM process"Motor process with proportional and derivative controllerINPUT T alarmOUTPUT eSTATE x1 x2DER dx1 dx2

"Process:dx1 = IF alarm<0.5 THEN -a*x1 + u ELSE 0dx2 = IF alarm<0.5 THEN x1 ELSE 0y = x2

"Regulator:u = K*e-T*x1

"Output:e = yr-y

3DUW��7XWRULDO����([DPSOHV

3:68

"Parameters:a:1yr:1K:1

END

/LVWLQJ�9�4Code for the motor control system SURFHVV.

CONTINUOUS SYSTEM loss"Evaluates the ITAE loss functionINPUT e tauOUTPUT J alarmSTATE x1DER dx1

"Loss ITAE:dx1 = IF NOT alarm THEN tau*abs(e) ELSE 0J = x1

"Alarm test:alarm = IF J>Jmax THEN 1 ELSE 0

"Parameters:Jmax : 1000

END

/LVWLQJ�9�5�Code for the loss function ORVV.

CONNECTING SYSTEM tune

TIME tT[process] = Peval[linopt]e[loss] = e[process]J[linopt] = J[loss]tau[loss] = t-tbegin[linopt]alarm[process] = alarm[loss]

END

/LVWLQJ�9�6�Simnon connecting system WXQH.

MACRO msearchSPLIT 2 2AXES v -0.1 1.2 h 0 20TEXT ’All step responses’AXES v -0.1 1.2 h 220 240TEXT ’Optimal step response’AXES v 0 5 h 0 2.0TEXT ’Loss function J(T)’AXES v 0 2 h 0 240TEXT ’Convergence of T’

SYST process loss linopt tuneSTORE y[process] tau J[loss] T[process]

3DUW��7XWRULDO����([DPSOHV

3:69

ERROR 0.0001AREA 1 1PLOT y(tau)TURN DARK ONsearch 0 2 0.01AREA 1 2SHOW J(T)AREA 2 1SHOW 220 240 yAREA 2 2TURN DARK OFFSHOW T

END

/LVWLQJ�9�7 The macro that generates Figure 9�5.

MACRO search plow phigh acc; nmax"Generates the number of evaluations and starting value for"optimization of one parameterLET unc0.=phigh-plow "Initial uncertainty.LET f1.=1.LET f2.=1.FREE qfi.FREE qf2.FREE x. "Ratio fn-1/fn.FREE uncn. "Uncertainty after N evaluations.FREE n. "Required number of evaluations.FREE p0. "Initial optimization starting point.FREE teval. "Simulation time for evaluation.FREE toptim. "Total simulation time.DEFAULT nmax.=50 "Maximal number of evaluations.

FOR i=1. to nmax. "Calculation of required numberLET qf2.=f1.+f2. "of evaluationsLET qf1.=f2.LET f1.=qf1.LET f2.=qf2.LET x.=f1./f2.LET uncn.=unc0./f1.LET n.=iIF uncn. LE acc GOTO exitNEXT iLABEL exit

WRITE ’Required number of evaluations : ’n.SUSPENDLET p0.=x.*unc0.LET p0.=plow+p0.INIT p:p0.INIT pmin:p0.INIT phi:phighINIT plo:plowDISP teval/tevalLET toptim.=n.*teval.SIMU 0 toptim.

3DUW��7XWRULDO����([DPSOHV

3:70

END

/LVWLQJ�9�8 A macro that from a given parameter interval to search over and a desired final accuracy of theoptimisation, calculates the optimal starting point and runs the optimisation.

3DUW��7XWRULDO�����5HIHUHQFHV

3:71

�����5HIHUHQFHV

Simnon inherited many ideas from the tradition of analogue and digital simulation in thecontrol engineering field. An overview of digital simulation languages is given in the book:

KORN, G.A. (1978): 'LJLWDO�&RQWLQXRXV�6\VWHP�6LPXODWLRQ, Prentice Hall, Englewood Cliffs,New Jersey.

This book also contains much useful information on simulation. Early digital simulationlanguages like CSMP and CSSL were implemented using batch calculations. The languagesalso inherited several constraints from the analogue simulators. For example the state spacenotation which is so natural was not supported by proper language constructs. When Simnonwas developed the main idea was to provide a tool which supports the state space notationwith good man-machine interaction based on interactive computing.

Integration of ordinary differential equations is a key feature of Simnon. A goodintroduction to differential equations, which also deals with numerical aspects is:

SANCHEZ, D.A., R.C. ALLEN, and W.T. KYNER (1983): 'LIIHUHQWLDO�(TXDWLRQV�DQ,QWURGXFWLRQ, Addison-Wesley, Reading, Massachusetts.

A classic which treats integration methods in more detail is:

FORSYTHE, G.E., M.A. MALCOLM, C.B. MOLER (1977): &RPSXWHU�0HWKRGV�IRU�0DWKHPDWLFDO&RPSXWDWLRQV, Prentice-Hall Inc., Englewood Cliffs, New Jersey.

A thorough discussion of numerical solution of differential equations can also be found in:

HAIRER, E., S.P. NØRSETT,and G. WANNER (1987): 6ROYLQJ�2UGLQDU\�'LIIHUHQWLDO�(TXDWLRQV,���1RQVWLII�3UREOHPV,�Springer-Verlag, Berlin.

Examples of simulation of control systems are given in the textbook:

ÅSTRÖM, K.J.,and B. WITTENMARK (1990): &RPSXWHU�&RQWURO�6\VWHPV, 2nd edition, Prentice-Hall, New Jersey.

All graphs giving simulation results in the book are generated by macros in Simnon. The usercan easily reproduce and modify the simulations.

The macros are also available on disk from SSPA Systems, Göteborg SwedenThe wind power plant in Chapter 9 is further described in:

MATTSSON, S.E. (1984): 0RGHOOLQJ�DQG�&RQWURO�RI�/DUJH�+RUL]RQWDO�$[LV�:LQG�3RZHU�3ODQWV,PhD Thesis TFRT 1026, Department of Automatic Control, Lund Institute of Technology,Lund Sweden.

BERGMAN, S., S.E. MATTSSON and A.B. ÖSTBERG (1983): "A modular Simulation Model fora Wind Turbine System", -RXUQDO�RI�(QHUJ\, 7, No.4, July--August, 319--324.

3DUW��7XWRULDO�����5HIHUHQFHV

3:72

The optimization procedure used in Chapter 9 is based on:

LUENBERGER, D. G. (1984): /LQHDU�DQG�1RQOLQHDU�3URJUDPPLQJ, Addison and Wesley,Reading, MA.

3DUW��5HDO�7LPH�6LPXODWLRQ

3DUW��5HDO�7LPH�6LPXODWLRQ����,QWURGXFWLRQ

4:74

����,QWURGXFWLRQ

A PC running Simnon with 5HDO�7LPH�&DSDELOLW\ can be used to control a physical process. Inthis way a new regulator algorithm can be tested with greater realism than an off-linesimulation could offer. Conversely, the PC could emulate a physical process that’s too delicateto tamper with. Hopefully, this could let you test control hardware in a more convenient waythan before. As a result, development times will be shortened.

Simnon 3.0 has unique capabilities to carry out real time simulation under Windows.Chapter 2 presents some fundamentals with respect to Real Time Simulation under

Windows. Chapter 3 and 4 respectively explains Yield Threshold and SynchronisationThreshold. Chapter 5 is a summary of Diverge Setting technique. Chapter 6 finally is a generaldiscussion about real time simulation performance and the factors that influence the overallperformance.An important feature in Simnon/PCW related to real time simulation is DDE linking to otherprograms. Read the chapter Data Exchange with Other Programs in this manual to learn moreabout this.

3DUW��5HDO�7LPH�6LPXODWLRQ����5HDO�WLPH�VLPXODWLRQ�XQGHU�:LQGRZV

4:75

����5HDO�WLPH�VLPXODWLRQ�XQGHU�:LQGRZV

tA tB tD tE tG

Simnon calculations during ‘normal’ real time simulation

tA tB tC tD tE tF tG tHSimnon calculations during real time simulation where another Windowsprocess interferes with the time syncronisation

tA-B: Simnon calculationtB-D: Time period when Simnon is ready to permit external processes to be activated (Yields areoffered to Windows)tC: External process invoked. Must take place before tD to be permitted by SimnontC-F: External process running.tD-E: Yield treshold.tE: By Simnon requested moment for beginning of next step calculationtE-G: Syncronisation tresholdtF: External process returns control to Simnon. As tF comes later than tE but before tG, a newcalculation is started immediately. If tF had come after tG, the simulation had been interruptedwith message ‘Syncronisation error’tF-H: Simnon’s next calculation

Real Time simulation under Windows is quite different from ordinary real time processes runin a PC. The major difference is found already in the basic principle of Windows. While anyprogram run under DOS has full control over the process and processor, in Windows theoperating system is always ready to accept calls from “sleeping processes”, these calls oftenbeing initiated by mouse movements and clicks.

Such a call can cause problems with the time synchronisation. For example, you canhardly expect Simnon to run smoothly if you try to format a diskette during a simulation.Simnon has certain built in features that help the user to optimise the performance. Yieldthreshold and synchronisation threshold control the program’s behaviour between simulation

3DUW��5HDO�7LPH�6LPXODWLRQ����<LHOG�WKUHVKROG

4:76

steps, while diverge settings control how often DDE-messages are sent between Simnon andthe DDE client(s).

����<LHOG�WKUHVKROG

Between simulation steps, an ongoing simulation can yield to other processes, that may becalled by the operator or by the computer itself. The \LHOG�WKUHVKROG is a “safety margin” set inSimnon, and is represented by the period tD-tE in the diagram above.

This margin is the shortest time that may be left from the beginning of an external processcall until the next Simnon calculation is scheduled.

����6\QFKURQLVDWLRQ�WKUHVKROG

When an external process returns the control to Simnon, we must ensure that a propersynchronisation is re-established between the simulation and the real time, represented by theclock built into the computer.

If the return comes after a new simulation step has been scheduled, a synchronisation erroroccurs. It is up to the operator to decide the maximum acceptable level of this error. This iscalled V\QFKURQLVDWLRQ�WKUHVKROG (time period tE-tG in the diagram). Default is 1000 ms, and

new values can be entered in the dialog box that is opened by the menu commandVLPXODWH_VLPXODWH.

When Simnon encounters a synchronisation error that lays within the set threshold, theprogram automatically tries to catch up with the real time. Synchronisation errors are not“lost” during the further process – consider the synchronisation threshold as the maximumintegrated synchronisation error that is permitted at any moment during the total simulation.

����'LYHUJH�VHWWLQJV��''(�

One of the great features with Simnon is the possibility to export data during simulation bymeans of DDE-links. Simnon is the server, and the program that receives the data is calledclient.It is important to understand that from Simnon’s point of view this process is similar to asubroutine call, and hence not a yield. The time consumed by the client is in the diagramabove a part of Simnon’s calculation (it is part of the period tA-tB and/or tF- tH).

The number of DDE conversations can be controlled by means of diverge settings. Theseare

• 6WHS�GLYHUJH sets how many integration steps that should be done between each DDEupdate.

• 7LPH�GLYHUJH sets what time that must elapse between each DDE update. • 'DWD�GLYHUJH sets the minimum value by which any data variable (state, der, var) must be

changed before a DDE transmission is initiated.

3DUW��5HDO�7LPH�6LPXODWLRQ����3HUIRUPDQFH�GXULQJ�D�UHDO�WLPH�VLPXODWLRQ

4:77

A thorough description of Simnon DDE functions, including diverge settings, is found in thechapter Data Exchange with Other Programs in this manual.

����3HUIRUPDQFH�GXULQJ�D�UHDO�WLPH�VLPXODWLRQ

A common and justified question is how complicated a real time simulation can be withoutloosing the time synchronisation.

From the above, it can be seen that there are many parameters that influence the total picture:

• The complexity of your model that has been 6<67ed • Simulation step time • Simulation time (for a simulation run during a fixed time e g 6,08�����, Simnon sets

the initial integration step to 1% of the total time) • Integration algorithm. Some algorithms can take longer time than others • (UURU setting for the integrators • Yield threshold • Synchronisation threshold • Number of DDE-links • Diverge-settings (please refer to the chapter Data Exchange with Other Programs) • The DDE client performance • Hardware: processor, clock speed, graphics adapter

Probably the most important matter is what is the performance of the DDE clients. If you havetime consuming processes like interpretative animation programs or human interaction withSimnon via DDE (parameter changes etc), chances are great that you must increase thesynchronisation threshold. If an animation is made by the client program, the performance ofthe graphics adapter can be the most important item.

����5HDO�WLPH�VLPXODWLRQ�ORJ

As a service to the user, Simnon after each simulation reports the overall performance. In theCommand Dialog History box you will find how much of the yield threshold that was used,the number of yields that were offered to Windows and the maximum synchronisation errorthat was encountered.

Use these data to adjust your simulation settings to fit your particular needs.