You are on page 1of 65

3DUW  7XWRULDO

3DUW  7XWRULDO ,QWURGXFWLRQ

 ,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 giving examples. Chapter 3 shows how to solve simple differential equations. The solution of difference equations is described in Chapter 4. Chapter 5 describes the simulation of more complicated systems, which are composed of subsystems. Some advanced features are described in Chapter 6. A few remarks on the implementation are given in Chapter 7. Chapter 8 contains information on how Simnon can exchange data with other programs and computers. Some more advanced simulation examples are given in Chapter 9. Each chapter is provided with exercises. Do not forget to experiment on the screen as you progress with the reading. Remember that you can always use HELP and that a detailed description of the language construction is given in the reference section of this book. Also remember that a good way to learn Simnon is to 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 does not distinguish between upper and lower case letters.

 :KDW ,V 6LPXODWLRQ"


Simulation means to imitate the behaviour of a system. Through simulation it is possible to make investigations without having access to the real system. It is an experiment inside the computer. In the simulations, the effects of different initial conditions and parameter values can be studied. For instance, in a control system different regulator structures and parameter settings can be investigated. When the performance is satisfactory in the simulation, the regulator 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\QDPLFDO V\VWHPV. A typical example of a discrete event simulation is the simulation of queues and operating systems. Simnon is intended for the simulation of continuous time as well as discrete time dynamical systems. Numerical integration routines are used to simulate differential equations. Difference equations describing discrete time systems are solved by iterating the equations.

 :KDW &DQ 6LPQRQ 'R"


Simnon is designed for solving ordinary differential and difference equations and for simulating dynamical systems. The systems may be described as an interconnection of subsystems whose behaviour is characterised by differential equations or by difference equations. Models of this type are common in mathematics, biology, economics and in many branches of engineering. Simnon has an interactive implementation, which makes it easy for a user 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

3:14

3DUW  7XWRULDO ,QWURGXFWLRQ

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

3:15

3DUW  7XWRULDO )XQGDPHQWDOV

 )XQGDPHQWDOV
This chapter gives an overview of system descriptions and interaction principles used in Simnon.

 '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 HTXDWLRQ An ordinary differential equation is a simple form of a dynamical system. The generic form of differential equation is
dx = f(x, t) dt

(2.1)

where [ is a vector of state variables. 'LIIHUHQFH HTXDWLRQ Simnon can also deal with difference equations. The generic form used is
x(t k +1 ) = f(x(t k ), t k ), k = 1,2,...

(2.2)

Here {t k :k = 1,2,...} is a sequence of discrete time instants called sampling times or sampling instants and [ is a vector of state variables. 6\VWHPV Simnon can also describe more complicated systems, which are interconnections of subsystems. The subsystems can be continuous time systems described by differential equations or discrete time systems described by difference equations. The generic form of a continuous time system is
dx = f(x, t) dt 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 is specified as a CONTINUOUS SYSTEM in Simnon. The analogous form for a discrete time system is x(t k +1 ) = f(x(t k ), u(t k ), t k ) y(t k ) = g(x(t k ), u(t k ), t k ) k = 1, 2, (2.4)

3:16

3DUW  7XWRULDO )XQGDPHQWDOV

The next sampling time WN+1 can be a function of, for instance, [(WN), X(WN), and WN. A system like (2.0) is specified as a DISCRETE SYSTEM. In Simnon the state variables of a discrete time system are viewed as piece-wise constant functions of time, which change abruptly at the sampling 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 the forms (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, text and numbers. It is also possible to get a hard copy of a picture and to list system descriptions and 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 VWUXFWXUH It is desirable that commands are both short and flexible. One possibility to achieve these conflicting goals is to use short forms where the arguments are omitted. The arguments are then given default values, which in many cases are the previously used values. Most commands also have initial default values given by the system. The idea is illustrated by an example. The different forms of the command SIMU, which executes a simulation of a system, 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 extended Backus-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 name of the command. The syntax is then shown in the extended Backus-Naur notation along with some examples. For example the command SIMU 0 100 simulates a system from time 0 to time 100. If we want to repeat the simulation a second time it suffices to write SIMU The 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, chapter 2.1.4 Simulate. It follows from the description that start and stop times and the initial time increment may be specified. It is also possible to mark curves by using the optional argument MARK. A simulation may also be continued by using the end conditions of a previous simulation as initial values. This is done by the command option CONT. The results of a simulation may also be stored in a file. The time spacing between the stored values is specified by <increment>. The command 3:17

3DUW  7XWRULDO )XQGDPHQWDOV

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

 ([HUFLVHV
2.1 You start Simnon simply by double clicking the icon simnon. You exit Simnon by typing STOP. Practice this. 2.2 The HELP command has an hierarchical structure. Try to find out about Simnon by using the command HELP. 2.3 Type HELP AXES to learn about the command AXES. Experiment with the command and find the same thing by using Help plot instead.

3:18

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV

 'LIIHUHQWLDO (TXDWLRQV
The solution of ordinary non-linear differential equations is a simple application of Simnon. In such 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 a calculator a function is activated by pushing a dedicated key. In Simnon functions are activated by typing a command on the keyboard. How Simnon may be used to solve an ordinary 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 d2 y dy + a(y 2 b) + y = 0 2 dt dt (3.1)

for different initial conditions and different values of the parameters D and E. The van der Pol equation is a model for an electronic oscillator. The solution to the problem can be divided into the following steps: 1. 2. 3. 4. Enter the system description Simulate Analyse the results Change parameters and initial conditions

where steps 2, 3 and 4 are iterated until a satisfactory result is obtained. The different steps will 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 the equation (3.1) is of second order an extra variable has to be introduced. Choosing this variable as dy x= the equation (3.1) can be written as dt dy dt = x dx = ax(b y 2 ) y dt CONTINUOUS SYSTEM vdpol
"The van der Pol equation STATE x y

(3.2)

3:19

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV DER dx dy dy=x dx=a*x*(b-y*y)-y a:1 b:1 END /LVWLQJ  Simnon system for Equation (3.2).

This is the standard state space form used by Simnon. The variables [ and \, which appear differentiated are the state variables of the system. A file, which describes the system, should now be prepared. This file, named vdpol, is given in Listing . The first line indicates that it is a continuous time system with the name vdpol. The state variables x and y and their derivatives, which are called dx and dy, are declared. The differential equations are then defined. Notice the strong similarity with equation (3.2). Finally, values are assigned to the parameters D and E. Simnon distinguishes between SDUDPHWHUV and YDULDEOHV. Parameters can be assigned values interactively using the command 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 command EDIT <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 is described in detail in the reference section. You can list a system description on the screen with the command LIST <filename>

 6LPXODWLRQ
To run the system vdpol it must first be activated. This is done by the command SYST vdpol If there are any errors during the activation an error message will be given and the error must 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 axes in a plot window. This is done with the command AXES H 0 20 V -6 6 which means that the ranges of the horizontal (H) and vertical (V) axes are chosen as [0, 20] and [-6, 6]. The command PLOT x y instructs 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 state variables. The command INIT x:1 assigns the initial value 1 to the state variable x. Initial values are automatically set to zero if no assignments are made. We are now ready to make a simulation. The command SIMU 0 20 performs a simulation from time 0 to time 20, and the result shown in Fig. is obtained. If you have forgotten the order given in the PLOT command you can check the current plot list by giving the command

3:20

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV

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

)LJXUH  Simulation of the van der Pol equation for D=1 and E=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. It is 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 simulation button in the toolbar will be modified to a red stop symbol. Click this button to stop the Simulation.

 &KDQJLQJ 3DUDPHWHUV


Suppose that it is of interest to explore how the solution to the differential equation depends on the parameters D and E. The command PAR b:2 assigns the value 2 to the parameter E. SIMU Just type SIMU to repeat the simulation over the same time interval as in the previous simulation. Current values of all states, derivatives, variables and parameters may be displayed. The command DISP displays all current data on the screen. Selective displays of the parameter a, the states x and y is done by the command DISP a x y The display may also be directed to the log file. A simple way to find out how the command DISP works is to type HELP DISP

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


3:21

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV

It may be useful to store some results, to compare results from different simulations and to plot different state variables in different diagrams. Suppose for example that we would like to compare the results for the parameter sets D=1, E=1 with those for D=1, E=2. Two data files are first generated. The command PAR a:1 PAR b:1 sets the parameters. The command STORE x y tells that the state variables x and y should be stored. The current list of variables to be stored is obtained by the command STORE ? The command SIMU/B1 then performs a simulation and stores x and y in a file called B1. The value of b is set to 2 by PAR b:2 and the command SIMU/B2 simulates and stores the results in file B2. The command SPLIT 2 1 splits the screen into two rows with one plotting area each. The command ASHOW x/B2 plots the variable x from file B2 in the first window using automatic scaling. The command ASHOW y/B2 plots 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 commands AREA 1 1 SHOW x/B1 AREA 2 1 SHOW y/B1 plots the variables x and y from file B1 in the first and second windows respectively. AREA selects the active plot area. The advantage of the combination of STORE and SHOW (or ASHOW) over the PLOT command is that several variables can be stored and displayed in different diagrams after the simulation. The disadvantage is that it is not possible to see the result until the simulation is finished. To document the results it is useful to generate a hardcopy of the curves obtained. The command HCOPY 3:22

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV

takes a snapshot of the graphs on the screen. Further details are obtained by giving the command HELP HCOPY. The command SPLIT 1 1 resets plotting to just one area in the current plot window.

)LJXUH  Phase plane plot of the van der Pol equation for D = 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 plane plots. This may be done simply by AXES H -4 4 V -3 3 SHOW y(x)/B1 This command plots y as a function of x. The result obtained by using this command is shown in Fig..

 *HQHUDOLWLHV
The general way of using Simnon as a "calculator for differential equations" will now be given. The generic form of a system description is given in Listing . CONTINUOUS SYSTEM <identifier> "General differential equation comment STATE < identifier > < identifier > DER < identifier > < identifier > declarations TIME < identifier > computation of auxiliary variables computation of derivatives body parameter assignment initial value assignment END 3:23

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV /LVWLQJ  Generic form of system description for simulation of differential equations.

The system description starts with CONTINUOUS SYSTEM <identifier>. It is terminated by 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 declared by 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. A time variable may be declared for simulation of time varying differential equations. This is done by the keyword TIME followed by an identifier. The body of the system description specifies the derivatives of the state variables in terms of state variables and parameters. Auxiliary variables may also be used. The body also contains assignment of parameters and initial values. Please note that a variable may only be defined once. The order of the statements in the body is unimportant. The statements will be sorted into appropriate order by the SYST command. ([SUHVVLRQV DQG RSHUDWRUV The expressions available in Simnon are similar to those in a procedural language like Algol or Pascal. An expression may be a numeric constant or a variable. It may also be combinations of variables, operators and functions. Conditional expressions of the form IF...THEN...ELSE are also permitted. Simnon has arithmetic, relational and logical operators. All variables are floating point numbers. The numbers are written in the conventional way as 4, 1.1, or 6E7. The result of a Boolean expression is 1.0 if it is true and 0.0 if it is false. $ULWKPHWLF RSHUDWRUV The arithmetic operators are addition, subtraction, multiplication, division and exponentiation. They are denoted as + - * / ^ respectively. For instance, 2a 5 v = b + c is written
v = -2 * a^5 / (b + c)

5HODWLRQDO RSHUDWRUV There are two relational operators, namely greater than, and smaller than. They are denoted by > < Please note that there is no equality. /RJLFDO RSHUDWRUV The logical operators are AND, OR, and NOT. )XQFWLRQV The standard mathematical functions are available. The details are given in the reference section. See Part IV-Section 2.6.

3:24

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV

 6XPPDU\
We have seen that Simnon can solve ordinary differential equations in a very simple way. To do this the differential equations are first written as a system of first order equations like
dx = f(x, t) dt

where [ and X are vectors. A continuous time system is then generated in Simnon by declaring the 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 ordinary mathematical expressions and assignments of parameters. There is no vector notation so all equations must be written in scalar notation. The command LIST can be used to list files. A simulation 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.

 ([HUFLVHV
3.1 3.2 3.3 3.4 Use EDIT or File|New|Continuous to enter the system description in Listing . Use the command LIST to list the system you have edited on the screen. Repeat the simulation described in this chapter on your own. Practice to interrupt a simulation.

3.5 Change parameters with the command PAR and initial conditions with the command INIT and investigate how the solutions to the van der Pol equations change. 3.6 3.7 SIMU. Experiment with the commands AXES, SPLIT, SHOW, ASHOW, and AREA. Use HELP to investigate the basic simulation commands AXES, PLOT, INIT, PAR, SYST, and

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 AREA. Use HELP to investigate the auxiliary commands STORE, SHOW, DISP, ASHOW, SPLIT, and

3.10 Look at the commands LIST, LP, and HCOPY and learn how to get hardcopies of listings and plots 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.

3:25

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV 3.12 The following equations called the Volterra-Lotka equations represent a simple model for the development of two competing species

dx dt = (a by)x dy = (cx d)y dt


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

dr dj 2 k dt r dt = r dj 2 dr dj 0 dt + r dt dt =
where U is the radius from the centre of the earth, the azimuth angle and N a gravitational constant. Write a Simnon system and simulate the equations. 3.15 Simulate the differential equations

dx = a(y x), x(0) = 8 dt dy = bx y xz, y(0) = 8 dt dz = cx + xy, z(0) = 24 dt


where D = 10, E = 28, and F = 8/3. Look in particular at ] as a function of [. The equation, which is 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 t STATE x vx y vy DER dx ax dy ay r1=sqrt(x*x+y*y) r2=sqrt((a-x)*(a-x)+y*y) dx=vx dy=vy F1=k*m1/(r1*r1) F2=k*m2/(r2*r2) ax=-F1*x/r1+F2*(a-x)/r2 ay=-F1*y/r1-F2*y/r2 "distance to the earth "distance to the moon "gravitational force of the earth "gravitational force of the moon "x-component of acceleration "y-component of acceleration

"The total energy is computed to check the results E=(vx*vx+vy*vy)/2-k*m1/r1-k*m2/r2 "Scaled variables used for plotting xs=x/a

3:26

3DUW  7XWRULDO 'LIIHUHQWLDO (TXDWLRQV

ys=y/a x:-6.37e6 vy:11080 k:6.67e-11 m1:5.977e24 m2:7.349e22 a:3.844e8 END


Write the differential equations that describe the system.

"satellite initially behind the earth "initial velocity [m/s] "gravitational constant [Nm^2/kg^2] "mass of the earth [kg] "mass of the moon [kg] "average distance from moon to earth [km]

3:27

3DUW  7XWRULDO 'LIIHUHQFH (TXDWLRQV

 'LIIHUHQFH (TXDWLRQV
It is also possible to simulate difference equations with Simnon. This is done analogously to the simulation of differential equations. An example is first given and the general principles are then stated.

 ([DPSOH
Consider the following difference equation
x k +1 = x k + rx k (1 x k ), k = 0,1,...

(4.1)

This is a simple model of a population dynamics. The variable [N denotes the number of individuals at time N in a normalised scale. There is an equilibrium value [=1 at which the population remains constant. For [N 0 the population increases by the factor 1+U in each generation. For [N>1 the population will decrease. Assume that it is of interest to investigate how the population changes with time. A difference equation is represented as a DISCRETE SYSTEM in Simnon. The description of a system which simulates the difference equation (4.1) is given in Listing 41. DISCRETE SYSTEM popdyn "Simple model for population dynamics STATE x NEW nx TIME k TSAMP ts nx=x+r*x*(1-x) ts=k+1 x:0.5 r:2 END
/LVWLQJ 41 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 the STATE declaration. The declaration NEW is used to declare the variable nx, which denotes the new value of the state variable i.e. [N+1. NEW is thus the analogy of DER for continuous time systems. When simulating difference equations it is necessary to provide a mechanism for making the 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 irregular sampling. The mechanism used to describe this in Simnon is to introduce a variable of the type TSAMP which gives the next sampling time. In Listing (4.1) the first assignment statement is simply a definition of the right hand side of the difference equation (4.1). The second line: ts=k+1 assigns the value k+1 to the TSAMP variable ts. This variable gives the time when the system is run the next time.

3:28

3DUW  7XWRULDO 'LIIHUHQFH (TXDWLRQV

)LJXUH 41 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 is thus executed by the commands SYST popdyn SPLIT 3 1 AXES H 0 80 V 0 2 PLOT x PAR r:0.2 SIMU 0 80 This generates the uppermost curve in Fig 41. The commands AXES PAR r:2.70 SIMU AXES PAR r:2.83 SIMU repeat the simulation for U = 2.70 and U = 2.83, and plot the corresponding curves shown in Fig 41. Notice that the behaviour of the solutions changes drastically with moderate changes in the parameters.

3:29

3DUW  7XWRULDO 'LIIHUHQFH (TXDWLRQV

)LJXUH 42 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 we want 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 polynomial TIME x TSAMP z f=x*(x+3)*(x+2)*(x-2)*(x-3) z=x+dx dx:0.05 END The commands SYST pol STORE f SIMU -3.6 3.6 ASHOW f will then generate the graph in Fig 42. Please note that the curve is not smooth because the function was defined using a discrete time system. The variables in a discrete time system are assumed to be constant between the sampling instants. If a smooth curve is desired it is better to 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 the lines arg ] = /2 and arg ] = 3/4 in the conformal map G(x) = e z = e x + iy = e x (cosy + isiny) This may be accomplished by the system DISCRETE SYSTEM expz 3:30

3DUW  7XWRULDO 'LIIHUHQFH (TXDWLRQV

"Generates the function exp(z) TIME r TSAMP s fi=alfa*pi/180 x=r*COS(fi) y=r*SIN(fi) ReG=EXP(x)*COS(y) ImG=EXP(x)*SIN(y) s=r+dr dr:0.01 pi:3.1415926 alfa:90 END The commands SYST expz AXES H -1 1 V 0 1.5 PLOT ImG(ReG) SIMU 0 3.14 PAR alpha: 135 SIMU 0 4.44 then generate the curves shown in Fig 43. DISCRETE SYSTEM <identifier> "General difference equation STATE < identifier >... < identifier > NEW < identifier >... < identifier > TIME < identifier > TSAMP < identifier > computation of auxiliary variables computations of new values of the states update the TSAMP variable parameter assignment initial value assignment END
/LVWLQJ 42 Structure of Simnon system for simulating difference equations.

comment

declarations

body

 *HQHUDOLWLHV
The general form of a description of a discrete time system is given in Listing 42. The standard form used in Simnon is a system of first order difference equations. It may be necessary to introduce auxiliary variables to obtain this form. The description of a discrete time system is analogous to a continuous time system. The only difference is that DER is replaced by NEW and that the sampling variable TSAMP must be declared and assigned.

3:31

3DUW  7XWRULDO 'LIIHUHQFH (TXDWLRQV

)LJXUH 43 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 system description DISCRETE SYSTEM is used instead of CONTINUOUS SYSTEM. The simulation commands are the same as for differential equations. The six basic commands AXES, PLOT, INIT, PAR, SYST, and SIMU and the six auxiliary commands STORE, SHOW, DISP, SPLIT, AREA, and HCOPY are very useful.

 ([HUFLVHV
4.1 The difference equation

x k +1 =

1 a xk + 2 xk

is a well known algorithm for computing the square root of D. Write a discrete system in Simnon and explore the algorithm. 4.2 Modify the simulation program in the previous exercise so that the stationary solution to the equation 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 government expenditures. 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 of the 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))e0.1(x(t)+ y(t)) y(t + 1) = x(t)

3:32

3DUW  7XWRULDO 'LIIHUHQFH (TXDWLRQV for different values of the parameter U. 4.5 Modify the simulation which gave Fig 42 so that a smooth curve is obtained.

3:33

3DUW  7XWRULDO 6\VWHPV

 6\VWHPV
Many systems can often be viewed as interconnections of subsystems, which are represented by differential or difference equations. The difference equations typically arise when modelling regulators implemented by digital computers. To represent subsystems, declarations of inputs and outputs are added to the system descriptions. The system descriptions are otherwise the same as the CONTINUOUS SYSTEM and the DISCRETE SYSTEM described previously in Chapters 3 and 4. A special type of system is introduced to describe the interconnections. This system is called a CONNECTING SYSTEM. The possibility of decomposing a model into subsystems may also be useful in other contexts, particularly when dealing with large systems. Consider the control system shown in Fig.51 which is a combination of two subsystems: a regulator, which is a discrete time system, and a process, which is a continuous time system. The subsystems can be described as follows DISCRETE SYSTEM pireg INPUT yr y OUTPUT u . . . END CONTINUOUS SYSTEM proc INPUT u OUTPUT y . . . END where the details of the system descriptions are omitted. The interconnections between the systems are described by a CONNECTING SYSTEM as follows CONNECTING SYSTEM conn "Connecting system for pireg and proc TIME t yr[pireg]=1 y[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 done on 06'26 machines because con is a reserved word that refers to the console device. See your 06'26 manual for this and other reserved words. Notice that states, variables, and parameters are local to each subsystem. Variables belonging to different subsystems can be addressed by appending the system name in square brackets to the variable name. Notice that expressions may be used to describe the interconnections. Constructions like y[pireg] = IF t1 THEN 0 ELSE SIN(k*y[proc]) are thus possible.

3:34

3DUW  7XWRULDO 6\VWHPV

The simulation of an interconnected system is done using the same commands as was used to simulate difference or differential equations. The only difference is that it is necessary to activate all subsystems that describe the interconnected system. This is done by the command SYST proc pireg conn The 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 51 Block diagram of an interconnected system.

 6LPXODWLRQ RI D 'LJLWDO &RQWURO 6\VWHP


A continuous time process controlled by a computer implemented regulator is conveniently described as an interconnected system. The process may be represented as a CONTINUOUS SYSTEM and the digital controller as a DISCRETE SYSTEM. Listing 51 describes a feedback loop consisting of a continuous time process called proc and 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 saturation INPUT u OUTPUT y STATE x DER dx upr=IF u<-0.1 THEN -0.1 ELSE (IF u<0.1 THEN u ELSE 0.1) dx=upr y=x END DISCRETE SYSTEM pireg "Discrete time PI regulator with anti-windup INPUT yr y OUTPUT u STATE i NEW ni TIME t TSAMP ts e=yr-y v=k*e+i u=IF v<ulow THEN ulow ELSE (IF v<uhigh THEN v ni=i+k*e*h/ti+u-v ts=t+h k:1 "regulator gain ti:1 "reset time h:0.5 "sampling period ulow:-1 "lower limit of control signal

ELSE uhigh)

3:35

3DUW  7XWRULDO 6\VWHPV

uhigh:1 END

"upper limit of control signal

CONNECTING SYSTEM conn "Connecting system for pireg and proc TIME t yr[pireg]=1 y[pireg]=y[proc] u[proc]=u[pireg] END
/LVWLQJ 51 Simnon description of a simple control loop consisting of a continuous time process and a discrete time PI regulator.

The following annotated dialogue illustrates how Simnon is used. &RPPDQG SYST proc pireg conn STORE yr y[proc] upr SIMU 0 40 SPLIT 2 1 ASHOW y yr ASHOW upr area. $FWLRQ Activate the system. Select variables to be stored. Simulate. Form two plot areas. Draw y and yr with automatic scaling in the first area. Draw upr with automatic scaling in second

Please note that the names are local to each subsystem. To distinguish between variables with the same name in different subsystem the name of the subsystem is appended to the variable name as in y[proc]. Variables can be transmitted between subsystem by declaring them as inputs and outputs. The results of the simulation are shown by the oscillatory curves in Fig 52. 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 discrete time system are defined for all times. They are constant between the sampling instants and they change abruptly at the sampling instants. These curves show that there is a considerable overshoot due to wind-up of the integral. This can be avoided by telling the regulator what the process limitations are. The commands PAR PAR ulow:-0.1 uhigh:0.1

change the necessary parameters. The commands SIMU AREA SHOW AREA SHOW 0 40 1 1 y 2 1 upr

show that the overshoot is reduced significantly. Compare Fig 52.

3:36

3DUW  7XWRULDO 6\VWHPV

)LJXUH 52 Results of simulation of process control with a PI regulator. The curves with a large overshoot correspond to an ordinary regulator. The welldamped set of curves 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 to model a subsystem represented by ordinary differential equations. A DISCRETE SYSTEM is used to model a subsystem described by difference equations. The CONNECTING SYSTEM describes how the subsystems are interconnected. The complete syntax for the system descriptions is given in the reference section in Part IV of this manual.

 ([HUFLVHV
5.1 Look at the syntax of the commands SYST and SIMU using HELP. What are the differences between 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 digital control example to find out what happens when you try to display or plot the variable. What diagnosis is produced? How can the variables be separated? 5.3 Consider the system in the example. Repeat the simulation on your own computer. Investigate the consequences of changing the sampling period h. 5.4 Study the general form of the system descriptions.

3:37

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

 $GYDQFHG )HDWXUHV
Simnon may be used in many different ways. So far we have described problems, which may be solved by using only a dozen commands. This is sufficient for many applications. For more demanding problems there are, however, several additional features. These may all be explored by using HELP or by reading the reference section in Part IV of this book. A brief description 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 may be retrieved by the command GET. These commands are very useful when working with large models, because parameters and initial values for different operating conditions can then be stored in files instead of in the system descriptions. Assume for example that the systems pireg, proc, and conn have been activated as in Section 5.1 by the command SYST pireg proc conn The command SAVE par51 then generates a file par51.t of the form [pireg] i:0. k:1. ulow:-1. uhigh:1. h:0.5 ti:1. [proc] x:0. [conn] The parameter values can be retrieved later by giving the command GET par51

 /DEHOOLQJ 3ORWV


When preparing plots for reports it is convenient to label the plots. This can be done using the commands 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 thus placed in a predefined place. It is also possible to place text at any place in a plot window using the command MARK. For instance MARK A 3 4

3:38

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

will move the text cursor to position x=3 and y=4 in the displayed coordinate system from the reference point. This is defined as the lower left corner of the plot area. The text cursor can also be moved relative to its current position by giving the command MARK R 1 -2 This will change the horizontal position with 1 unit and the vertical with -2 units. Text can be inserted at the current position by the command MARK "<string> The text string after the quote is then displayed. For instance the marking procedure can be done as follow. TEXT State variable x and y marked red and blue MARK A 22 1.2 MARK "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 of reading a sequence of commands from a file instead. This is done by the construction MACRO name arg1 arg2 ... Command1 Command2 END This implies that the commands 1 and 2 are not executed directly but stored in a file. The macros may also have arguments as shown above. The command sequence or macro is activated simply by typing name followed by possible arguments. Macros are very useful. Once created, a macro can be used like an ordinary Simnon command. The macros can thus be used to extend Simnon with user defined commands. This is convenient for implementation of a dialogue. Command sequences, that are commonly used, may be defined as macros. A simple macro call will then perform a whole sequence of commands. A typical example may be creation of standard plots for a given simulation. The usefulness of macros may be extended considerably by introducing commands to control the program flow in a macro, facilities for handling local and global variables and by allowing macros to have arguments. The macro facility used in Simnon has these features. By having commands for reading the keyboard and for writing on the screen it is also possible to implement question and answer dialogues using macros. The macros are also very convenient for documentation. When a successful simulation is completed we can just create a macro which contains the commands of a complete simulation. The simulation is then repeated simply by typing the name of the macro created. As an illustration we give the following macro which generates Fig 52. MACRO mpireg SYST proc pireg conn STORE yr y[proc] upr SIMU 0 40/wup PAR ulow:-0.1 PAR uhigh:0.1 3:39

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

SIMU /nowup SPLIT 2 1 ASHOW y yr/wup SHOW y/nowup TEXT Output y and yref MARK A 21 8.8 MARK "Time t ASHOW upr/wup SHOW upr/nowup TEXT Control variable u MARK A 21 1.2 MARK "Time t END Macros for generating all the figures in this tutorial are given in Appendix A. Even a casual user is strongly recommended to learn simple uses of the macro facility. More examples using macros are given in Chapter 9. It is possible to get help on user-defined programs and macros. For instance the command HELP mpireg gives the reply Generates Fig 52 The help given consists of the first contiguous block of comment lines in the program or macro.

 ([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 macro are two completely different things. In the first case, an auxiliary variable (or a parameter) is assigned a value in a system description. In the second case, a command variable is assigned a value in a macro or from the keyboard. Although the variables both happen to have the name x, they have nothing to do with each other. However, it would be valuable to be able to use simulated values to control simulation experiments, e.g. within macros. Simnon provides a means of FRS\LQJ simulated values from a system description to global command 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 calculated on the variable x: MACRO asweep LET avalue=0 "Initialize parameter value LET gvalue=0 "and goodness number FOR sweep=1.5 TO 2.5 STEP 0.2 PAR a[tank]: sweep "Change the parameter SIMU DISP x[tank] / x-tank "Copy x[tank] (from system "description) to x.tank (global "command variable) 3:40

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

LET r=x.tank*x.tank "Compute the goodness number IF r LT gvalue GOTO continue "Any improvement? LET avalue=sweep LET gvalue=r "number LABEL continue NEXT sweep "If so: Remember the current "parameter value and goodness

WRITE Optimal parameter value: avalue END

 2UJDQLVDWLRQ RI /DUJH 6LPXODWLRQV


There are several facilities which are useful when working with large systems or with large amounts of data. System descriptions and macros are stored as text files. Please note that lower case letters may be used to get a more readable code, although Simnon does not distinguish them from upper case letters. The subsystems also have a name which is the identifier given on the first line of the system description. Notice that the file name and the system name may be different. This is very useful when simulating different versions of a model because the same macros and the same connecting systems may be used provided that the names of the inputs and the outputs are the same. The selection of a particular model is made when the systems are activated by the command SYST. To illustrate the ideas consider the simulation in Section 5.1. Assume that we would like to perform the same simulation with a different process model. Let the new process model have a system name proc defined by the first line in the description. The system is stored in a file called proc2. Furthermore assume that the model has input u and output y. The systems are activated by the command SYST pireg proc2 conn where 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 ON SWITCH TRACE ON generate a file simnon.log of all commands in a session. A very convenient way to document a simulation is to create such a file and use it to edit suitable macros. It is also possible to enter text into the log file by using the command WRITE. System descriptions can be entered into the file by the command LIST and parameter values can be entered by the command DISP. By a proper use of these commands it is possible to create a file, which is a rough draft of a report for a simulation. The diagrams created in a simulation can also be given a useful format. The axes can be marked and text can be added by the commands MARK and TEXT. This feature has been used in the macros, which generate the curves in this tutorial. See Appendix A.

3:41

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

 ,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 to Fehlberg, RKF45. There is, however, several other integration algorithms implemented and the user can choose which one to use with the command ALGOR. Another way is to select Options... under Simulate in the menu where the algorithms are presented. The possible choices are EULER RKF23 RKF45 DOPRI45R Simple first order integration algorithm. A Runge-Kutta algorithm of order 2/3 due to Fehlberg. A Runge-Kutta algorithm of order 4/5 due to Fehlberg (default). 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 the fact that high order algorithms take longer steps and hence need fewer to solve a specific problem. Which algorithm to use depends on the circumstances, but in general a high order method should be preferred to a low order. (For a thorough discussion of different integration algorithms see the referenced books in Chapter 10 of this tutorial.) The current integration algorithm is displayed by giving the command ALGOR ?

$XWRPDWLF 6WHSVL]H $GMXVWPHQW DQG (UURU 7ROHUDQFH All the integration algorithms except EULER include algorithms for automatic step-size adjustment. The integration algorithm will internally try to estimate the error of the numerical solution, and choose a step-size such that this error does not exceed the error tolerance (the error tolerance is set using the ERROR command). The default value is 10-3. The current value is 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 is necessary to choose it as short as the shortest step-size needed during the whole integration interval. It is often very inefficient to use this step-size throughout the whole simulation interval. Automatic step-size adjustment normally works very well. There are, however, cases where the standard algorithm may fail. The implementation of the DOPRI45R algorithm includes a new regulator algorithm for step-size adjustment. This algorithm is superior to the standard algorithm in RKF23 and RKF45, and will in general handle the cases where the default algorithm fails. It is important to note that keeping the error estimate below the error tolerance does not imply 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 the error tolerance. It is therefore good practice to simulate a problem at several tolerance levels and compare the results in order to get convinced that the solution is sufficiently accurate.

3:42

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

The EULER algorithm uses a fixed step-size. It is up to the user to choose a step-size so that the error in the numerical solution is acceptable. The step-size is chosen through the third argument in the SIMU command, i.e. SIMU 0 200 0.5 means simulate from 0 to 200 using the step-size 0.5. If the third argument is omitted, it will be inherited from the previous SIMU command. Specifying a value of zero causes SIMU to adjust 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 algorithm with automatic step-size adjustment it is interpreted as the maximum allowed step-size. This user-imposed limit on the step-size may force the integration algorithm to use shorter (and thus more) steps than necessary when solving the differential equation. Consequently, the integration will take unnecessary long time. If the aim is a solution with better accuracy then use the ERROR command instead of limiting the step-size. A high order integration algorithm will due to its better accuracy in general take longer steps than a low order algorithm. When simulating combinations of discrete and continuous systems the integration algorithm can never take longer steps than the sampling interval. If the sampling 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 example from astronomy, the restricted three-body problem, will be studied. Consider two bodies with masses 1- and , and a third body with negligible mass moving around in a plane. The equations are
y1 = y1 + 2y 2 (1- ) y 2 = y 2 2y1 (1- ) D1 = (y1 + ) + y 2
2

y (1 ) y1 + 1 D1 D2 y2 y 2 D1 D2

D 2 = (y1 (1 )) + y 2
2

3/ 2

3/ 2

y1 = 0.012277471

Using the initial values


y1(0) = 0.994 y2 (0) = 0 y1(0) = 0 y2 (0) = 2.001585106

results in a periodic orbit with period 7 = 17.065216560. It should be remarked that this problem is very sensitive to small changes in the initial values. The single precision calculation 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 61) from 0 to 7 using the standard Simnon set-up, i.e. an error tolerance at 10-3, the integration algorithm RKF45, and no third argument in the SIMU command. The result is shown as curve 1 in Figure 61. The curve is clearly not periodic, and although the error estimate was kept below

3:43

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

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

)LJXUH 61 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.2 STATE y1 y1dot y2 y2dot DER dy1 dy1dot dy2 dy2dot dy1 = y1dot dy2 = y2dot dy1dot = y1+2*y2dot-(1-mu)*(y1+mu)/d1-mu*(y1-(1-mu))/d2 dy2dot = y2-2*y1dot-(1-mu)*y2/d1-mu*y2/d2 d1 = ((y1+mu)*(y1+mu)+y2*y2)^(3/2) d2 = ((y1-(1-mu))*(y1-(1-mu))+y2*y2)^(3/2) mu : 0.012277471 y1 : 0.994 y1dot : 0 y2 : 0 y2dot : -2.001585106 END
/LVWLQJ 61 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 61 shows a notable improvement re-made over the previous simulation. To improve the accuracy by limiting the step-size, i.e. supplying a third argument to the SIMU command it is necessary to limit the step-size to a very small value, and consequently the simulation will take a very long time. ([DPSOH  'LIIHUHQW LQWHJUDWLRQ DOJRULWKPV ALGOR

Again, consider the astronomy example in Example 6.1. Figure 62 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 the SIMU command. Still, the result from RKF23 is inferior to the one from RKF45. The reason is that RKF23 has lower order than RKF45 and therefore requires more steps to solve the problem. Both methods will at each step keep the error estimate close to the error tolerance,

3:44

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

but since the number of steps are larger for RKF23 the resulting global error will also be larger. The previous example should not be regarded as a general criticism against RKF23. The result only reflects the order difference between RKF45 and RKF23. A step in RKF23 requires less computations than one in RKF45, and there are situations where this would make RKF23 favourable to RKF45. Suppose, for instance, that the problem includes a discrete system with short sampling interval. If the sampling interval is so short that it restricts the step-size of RKF45 then it would be better to instead use RKF23, since that would require less computation, thus making the simulation run faster. 'LVFRQWLQXLWLHV Simnon allows the user to define systems with discontinuities, e.g. dx = if t<t1 then amp1 else amp2 Such systems are hard to integrate numerically. The numeric solution to the problem is only calculated at discrete points, and the result may be different depending on how these points are related to the time instant of the discontinuity. If the time instant of a discontinuity is known it is good advice to place the generation of that signal in a discrete system. When Simnon integrates combinations of continuous and discrete systems it will integrate up to the sampling instance of the discrete system, execute the code in it, and then continue the integration up to the next sampling. Hence, by choosing the sampling instances of the system containing the discontinuous signals sensibly, it is possible to make Simnon always handle these signals correctly. ([DPSOH  'LVFRQWLQXRXV LQSXW VLJQDO Consider a first order system with two input signals x= x + p1 + p 2 40 10 < t < 10.025 p1 = 0 otherwise 40 20 < t < 20.025 p2 = 0 otherwise Both p1(t) and p2(t) are short pulses with energy equal to one, and when simulating the system from 0 to 30 one expect to see the impulse response of the first order system, once at W=10 and once W=20. The simulation was made (the Simnon code is listed in Listing 62) and the resulting [ is plotted in the upper diagram of Figure 63. Only the first pulse response appears in the plot. The reason is that the differential equation is easy to integrate numerically and consequently Simnon will use long steps. These steps are much longer than the duration of the pulses 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 was put in a separate discrete system. This discrete system calculates its sampling instances so that it will be sampled only when p1(t) changes value. Simnon integrates up to these time instances, notices the change, and then continues the integration.

3:45

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

)LJXUH 62 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 the maximum step-size. The lower diagram of Figure 63 shows the result of SIMU 0 30 0.025, i.e. the step-size is restricted to a maximum value which is equal to the pulse duration. Simnon will now manage to detect also the second pulse, but the integration is very inefficient due to the small step-size. DISCRETE SYSTEM pulse "Generates discrete time pulse TIME t TSAMP ts OUTPUT p1 p1=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 ELSE 1E6) t1 : 10 eps1 : 0.025 END CONTINUOUS SYSTEM firstord "First order system TIME t INPUT p1 STATE x DER dx dx=-x+p1+p2 p2=IF t<t2 THEN 0 ELSE (IF t<t2+eps2 THEN 1/eps2 ELSE 0) t2 : 20 eps2 : 0.025 END

3:46

3DUW  7XWRULDO $GYDQFHG )HDWXUHV

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

CONNECTING SYSTEM conpulse "Connecting system for firstord and pulse p1[firstord]=p1[pulse] END
/LVWLQJ 62 Simnon code to implement the equations in Example 6.3.

 ([HUFLVHV
6.1 6.1 and 6.2. Test the relation between accuracy, error bound, and step-size by experimenting with Examples 6.2 Experiment with the system in Example 6.3 to find out how a discrete time system can be used to include discontinuities.

3:47

3DUW  7XWRULDO 6RUWLQJ DQG 6LPXODWLRQ

 6RUWLQJ DQG 6LPXODWLRQ


When using Simnon it is helpful to have some insight into how the program works. For example, when activating a collection of subsystems using the command SYST we may get a diagnosis "algebraic loop detected". This is explained in this chapter. Further the computations performed 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 to read one statement at a time from the files mentioned in the command line. If a statement is correct, it will be translated to instructions for the "Simnon machine", a hypothetical computer. (For the technically interested person, the Simnon machine has a pure stack architecture, and its instructions are referred to as Pseudo-code or just P-code.) When a subsystem is completely translated, Simnon checks that all local quantities are defined exactly once. 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. This allows the user to write the statements in an arbitrary order. (Section 7.2 describes a special situation, where the sorting fails.) The sorting also minimises the computation work for the simulation engine by treating time-invariant, initial, derivative, discrete and continuous computations separately. The P-code is finally translated into machine code, which permits very 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/dummy generates a file called dummy.t with the content: SORTED INITIAL EQUATIONS SORTED TIME-INDEP. EQUATIONS conn yr[pireg] = 1 SORTED DERIVATIVE EQUATIONS proc y = x conn 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 uhigh conn 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

3:48

3DUW  7XWRULDO 6RUWLQJ DQG 6LPXODWLRQ

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 are sorted so that the calculations may be performed in sequential order so that all variables needed at a particular stage have already been computed. The order of the sorting can be influence by the user by introducing the keywords INITIAL and SORT in the system descriptions. This means that all statements between the keywords are sorted as a group before the statements after the keyword SORT. This feature is useful, for example, when some calculations are required to obtain initial conditions for a simulation.

 $OJHEUDLF /RRSV


When systems are interconnected it may happen that the statements cannot be sorted so that the variables may be calculated sequentially. A simple example, which illustrates what may happen is given below. CONTINUOUS SYSTEM s1 INPUT u OUTPUT y y = u END CONTINUOUS SYSTEM s2 INPUT u OUTPUT y y = u END CONNECTING SYSTEM c yr = 1 u[s1] = yr + k*y[s2] u[s2] = y[s1] k: 0.5 END When the command SYST s1 s2 c is given the error diagnosis "algebraic loop detected" is given. The attempt to sort the statements results in s1 y = u c u[s2] = u[s1] s2 y = u c u[s1] = yr + k*y[s2] s1 y = u The variable u[s1] thus cannot be solved sequentially. A simple calculation shows that the variable is given by the following algebraic equation:

3:49

3DUW  7XWRULDO 6RUWLQJ DQG 6LPXODWLRQ

u[s1] = yr + k*u[s1] This explains the name algebraic loop. In this particular case it is easy to solve the equation for u[s1] if k 1. In the general case the algebraic equation may be non-linear. It is then difficult both to determine if a solution exists and to find it when it does. Simnon will not attempt to find a solution. It will just give an error message. The presence of an algebraic loop is 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 that the 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 its states will be updated. Connected derivatives and continuous time variables will also be computed. 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-order hold action). Continuous systems will now be processed collectively up to the nearest future sampling instant (or to the end of the simulation interval, whichever is closest). Two kinds of computations are made: function evaluations (static) and numerical integration of differential equations (dynamic).

3:50

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

 '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 sophisticated feature in Windows. In such links, data is shared among two or more programs. The program that supplies the data is called the VHUYHU, and the program that initiates the request for data and receives the data is called the FOLHQW. The DDE feature makes Simnon an excellent tool for simulators, where an animation program such as InTouch (Wonderware Corp, Irvine, California, USA) can be applied as a user 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 is supplied together with your client program to get full advantage of Simnons DDE capabilities.

 %ULHI ''( WHUPLQRORJ\


DDE is a form of inter-process communication that uses shared memory to exchange information between applications. Simnon acts as the DDE server and one or more applications are DDE clients. Basically, information can be exchanged between Simnon and the client(s) in the following ways: 5(48(67 Whenever Simnon receives a UHTXHVW from a client, information is transferred. $'9,&( If a client has specified that it wants to be DGYLVHG whenever information has been modified, the information is continually kept updated. 81$'9,&( Unadvice is used whenever a client wants to inform Simnon that advice of a variable is no longer wanted. 32.( For certain topics, Simnon accepts that the client can SRNH information to 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 information about its capabilities to send various message types to Simnon.

 ''( OLQNV LQ 6LPQRQ


3:51

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

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: Item 6\V,WHPV 7RSLFV )RUPDWV FRPPDQG! +HOS 6\V,WHPV 6\VW6WDWXV 6LPX6WDWXV 3URJUHVV 6WHS 6WHS'LYHUJH 7LPH%HJLQ 7LPH(QG 7LPH 7LPH'LYHUJH 9DOXH'LYHUJH FRPPDQG! 6\V,WHPV_WLPH! 6\V,WHPV_VWDWH! 6\V,WHPV_LQSXW! 6\V,WHPV_RXWSXW! 6\V,WHPV_LQLW! 6\V,WHPV_GHU! 6\V,WHPV_QHZ! 6\V,WHPV_WVDPS! 6\V,WHPV_SDU! 6\V,WHPV_YDU! Description List of all available items in topic System List of all available topics List of all available formats Send command to Simnon Brief help information List of all available items in topic Data Status flag: 1 if SYST has been successfully completed, otherwise 0 Status flag: 1 if simulation is in progress, otherwise 0 Simulation progress in percent (0-100) Number of simulation steps since the simulation was started If poked; min. no. of simulation steps before each 6WHS DGYLFH Simulation begin time Simulation end time Simulation time If poked; min. time diverge before each 7LPH DGYLFH If poked; min. diverge before each 9DOXH DGYLFH Send command to Simnon Item list | Topic for WLPH variables Item list | Topic for VWDWH variables Item list | Topic for LQSXW variables Item list | Topic for RXWSXW variables Item list | Topic for LQLW values Item list | Topic for GHU variables Item list | Topic for QHZ variables Item list | Topic for WVDPS variables Item list | Topic for SDU parameters Item list | Topic for YDU auxiliary variables Note

Topic 6\VWHP 6\VWHP 6\VWHP 6\VWHP 6\VWHP 'DWD 'DWD 'DWD 'DWD 'DWD 'DWD 'DWD 'DWD 'DWD 'DWD 'DWD 'DWD 7LPH 6WDWH ,QSXW 2XWSXW ,QLW 'HU 1HZ 7VDPS 3DU 9DU Notes:

P P E

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

3:52

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

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


To transfer data from Simnon to a cell in Excel during simulation of the Lorenz equations (an example 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 6 LPXODWH_ %UHDN sent to topic System. This is a way to emulate menu commands. The & character precedes underscored menu characters, and is optional. 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 Simnons 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 correct use of the characters |, and .

 %ORFN ''(


%DFNJURXQG Normally, 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 the numeric information that you want to convey. Also, in some cases the number of DDE channels that can be opened simultaneously is limited. For this reason Simnon has, from version 3.0, a new proprietary function called Block DDE. When this is called, the message returned from Simnon contains information about two or more variables.

3:53

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

Example: You want to read an objects position in a three dimensional co-ordinate system during 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 every message. %ORFN ''( 6\QWD[ Topic Item %ORF N <variable list>

Descriptio Note n 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 is part of a sub system which has been SYSTed in Simnon. <variable type> can be omitted, as long as the type of the following variable(s) is (are) the same as last specified type. If the Simnon system name is part of the variable name, it should be placed within brackets ([ and ]) Example of <variable list>: VWDWH[>ORUHQ]HT@\]GHUG\>ORUHQ]HT@ The only limitation in the <variable list>specification is the length of the total string. It may not be longer than 255 characters. 5HWXUQ YDOXHV The return value from Simnon is a string containing the actual values for each variable, with space (ASCII character 20) as delimiter. Please note that when Simnon cannot return a certain value, the text NAN (Not A Number) is returned. Hence, the number of characters in a return string 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 is a two-way conversion utility between store files and printable form. The latter can be thought of as an "esperanto" between such diverse applications as CAD programs, maths/statistics packages, data bases, spread sheets, etc. Its simplicity also permits migration between different computers and operating systems. A printable time series file is also referred to as a flat ASCII file.

 ,PSRUWLQJ 7LPH 6HULHV


One important reason to import time series to Simnon is to validate models. This involves two steps.

3:54

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

First a time series has to be translated from printable form to Simnons binary store file format. 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 by calling the function RFILE from the model and by supplying the name of the time series file via the command SIMU. A printable time series file containing Q records of P variables should have the following organisation: W  Y  W  Y   W Q Y Q Y  Y  Y Q    YP  YP  YP Q

Here W denotes the time variable (which is recommended but not necessary, since the command IMPORT is capable of generating a time ramp). Y1, Y2, , and YP denote the recorded 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 column and two variables. To translate it into a store file named data1.d and naming the variables temp and flow, we type the Simnon command: IMPORT data1 < data1 1 2 temp 3 flow / 3 If we accept the default names v1 and v2 for the variables (they are only used by the commands ASHOW and SHOW anyway), it would have been sufficient to type: IMPORT data1 < data1 / 3 To plot v2 as function of v1, we type: ASHOW v2(v1)/data1 In order to drive a simulation from the variables v1 and v2, we need the discrete system ILOHUHDG 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 from the 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 inputs from the store file data1.d: SYST p1 fileread conn SIMU 0 10 // data1 Notice that the simulation will stop prematurely if the data file does not cover the entire simulation interval.

 ([SRUWLQJ 7LPH 6HULHV


A store file is translated into printable form by the command EXPORT. Suppose we have a store file named data2.d containing the variables x, y and z. The following command translates the entire contents of the store file data2.d into the printable time series file data2.t: EXPORT data2 < data2 Notice that the time column will appear as the first column in data2.t, x as the second, and so on. The time column will be omitted, if we instead type: EXPORT data2 < data2 -NOTIME

3:55

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

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 file would have been split into a number of physical lines, each one at most 80 characters long. If we would like to have longer physical lines, say 256 characters each, we type: EXPORT data2 < data2 / 256 Finally, if we would like to remove the limitation on the physical line length, we type: EXPORT data2 < data2 / 0 In 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 matrix named 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 program such as a word processor or presentation program. There are basically two ways to do this: use Windows Clip Board, or create a file from the plot. Using Windows Clip Board is of course straightforward. Just activate a plot (click on it to highlight 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 bitmap formats. EPS and HPGL files are vectorised, and give print quality output. For further information about this facility, see the +&23< description in the Command Language section of this manual.

 ,PSRUWLQJ /LQHDU 7LPHLQYDULDQW 6\VWHPV


Models comprise the highest level and the most difficult one to standardise. For that reason Simnon is limited to importing linear, time-invariant dynamic systems, either on state-space or on transfer function form.

 ,PSRUWLQJ )LUVW DQG 6HFRQG 2UGHU 7UDQVIHU )XQFWLRQV


Many simulation packages are block oriented, i.e., models are described as networks of interconnected building blocks, e.g. adders, multipliers, elementary functions, integrators, etc. Automatic control literature contains many examples of systems composed of first and second order linear transfer functions. This special case of a system description is fairly easy to translate 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 Simnon representation, we enter the Simnon command: SIMNONTF g82 1 0 0 1 0 .03 1 which yields the file g82.t containing: CONTINUOUS SYSTEM g82

3:56

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

STATE x DER 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 u OUTPUT y ndx=a*x+u y=b*x a: -33.3333 b: 33.3333 END In general, the transfer function
name(s) = g b 2s + b1s + b 0 a 2s + a1s + a 0

is introduced to Simnon by the command SIMNONTF name g b2 b1 b0 a2 a1 a0 For a discrete transfer function (sample and hold action), a 9th argument, the sampling interval, has to be supplied as well. Furthermore, if another two arguments, b21 and b20, are entered, an extra output corresponding to:
b 21s + b 20 a 2s + a1s + a 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 0DWODE


Linear time-invariant, dynamic systems can be transferred from Matlab to Simnon. Although Matlab also has simulation capabilities, Simnon offers faster turn-around, multi-rate sampling and the ability to combine continuous and discrete subsystems. Given a matrix-set $, % and & and, optionally, a '-matrix and an [0-vector in Matlab, the function simnon (which is a Matlab-function!) is invoked to produce a continuous or discrete system and, optionally, a template for a connecting system. ([DPSOH Consider the continuous system dx = [2,1,2,0]x + [0,1]uy = [10]u dt

3:57

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

By typing the Matlab command simnon(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 overrides INPUT u1 OUTPUT y1 STATE x1 x2 DER dx1 dx2 a1_1: -2 dx1=a1_1*x1-x2 dx2=x1+u1 y1=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) 1RWHV Simnon needs a connecting system to drive the input signals. For large systems auxiliary variables named _1, _2, etc. may appear. To omit an optional argument, do not enter it or specify it as [ ]. Typing help simnon within Matlab will display the above information on the screen.

3:58

3DUW  7XWRULDO ([DPSOHV

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

 6LPXODWLRQ RI D :LQG 3RZHU 3ODQW


A mathematical simulation of a large horizontal axis wind turbine system is presented in this section. The model is developed for a wind power plant in Maglarp, Sweden. The wind power plant is run by Sydkraft AB and has a rated power of 3 MW. The rotor has a diameter of 78 m and the height of the tower is 80 m. The model is discussed in detail in Mattsson (1984) and Bergman et al. (1983). See Chapter 10 of this tutorial. The intention is to show how a larger system can be modelled and simulated in Simnon. The model can be used to investigate situations such as synchronisation of the wind turbine against the utility grid, influence of wind 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 well structured approach. Particular attention should be given to the modularization. The model is divided into subsystems to make it easy to modify the model and adapt the complexity of a subsystem to the case to be simulated. To make the model manageable some simplifying assumptions are made. 1. 2. 3. 4. The synchronous generator is connected via an impedance to an infinite bus. The moment of inertia of the gearbox and shafts is neglected. The rotor is perpendicular to the wind. 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 91. The block diagram defines input and output connections for the different subsystems. The different subsystems are described as continuous time Simnon systems. To increase the flexibility, the inputs and outputs of the subsystems are chosen as unscaled physical quantities in SI units. However, to improve the numeric, scaled quantities are used inside the subsystems. Figure 92 shows a block diagram of the used voltage controller. Listing 91 is the Simnon system VOLTCONT, describing the controller. The voltage controller is a simple system with only three states. The listing 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. This makes it possible to use the same connecting system for simulation of different voltage regulators or other subsystems. The comments contain a short description and references to the author and articles. All the parameters are collected into one section, which gives the names and units for the parameters. The other Simnon programs needed for the simulation are included in the distribution kit of Simnon.

3:59

3DUW  7XWRULDO ([DPSOHV

)LJXUH 91 Block diagram showing the model structure of the wind power plant simulation.

)LJXUH 92 Block diagram of the voltage controller described in Listing 91.

The wind power plant is simulated using the macro in Listing 92. After the SYST command initial values are obtained from the file inival. The file gives, for instance, the initial values for the states and parameter values. The simulation shows the responses when the wind is changed. Figure 93 shows the wind disturbance, the generated power and the pitch angle of the 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 shows how a simulation can be documented for later inclusion in a report. Table 91 gives a summary of the complexity of the simulation. For instance, the total number of states is 36 and there are 139 parameters in the subsystems.

3:60

3DUW  7XWRULDO ([DPSOHV

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 DER xF xE

dxA dxF dxE terminal voltage [V] auxiliary input signal [V] generator field voltage [V] rectifier voltage [pu] internal state in feedback loop [pu] generator field voltage [pu]

"Inputs: " vt " vs "Outputs: " vf "States: " xA " xF " xE Verr dxA1 dxA2 dxA = = = =

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

SE = 0.17*xE*abs(xE) dxE = (xA - SE - KE*xE)/TE vf = Vnorm*xE bF = KF/TF dxF = (bF*xE - xF)/TF yF = xF - bF*xE "Parameters: Vref: 6800. Vnorm: 6600. KA: 400. "reference voltage [V] "base voltage [V] "regulator gain

3:61

3DUW  7XWRULDO ([DPSOHV

TA: VRmax: VRmin: KE: TE: KF: TF: END

0.02 7.3 -7.3 1.0 0.8 0.03 1.0

"regulator amplifier time constant [s] "maximum rectifier voltage [pu] "minimum rectifier voltage [pu] "exciter constant "exciter time constant [s] "regulator stabilizing circuit gain [s] "regulator stabilizing circuit time "constant [s]

/LVWLQJ 91 Listing of the program describing the voltage controller in Figure 93.

MACRO mwindpow SYST gust1 bus1 gen1 gear4 voltc1 servo1 turb6 pitchr2 cwind GET inival STORE Vvel Pep betadeg ERROR 0.0001 PAR tg0:1.0 SPLIT 3 1 AXES H 0 40 V 14 24 AXES V 90 140 AXES V -12 -2 AREA 2 1 PLOT Pep SIMU 0 40/simures AREA 1 1 SHOW vvel/simures AREA 3 1 SHOW betadeg/simures MARK A 2.33 14.64"1 13.5 MARK "[m/s] MARK A 2.33 9.53"1 9 MARK "[%] MARK A 2.33 4.42"1 4.5 MARK "[deg] MARK A 4.86 14.64"3 13.5 MARK "Wind speed MARK A 4.86 9.53"3 9 MARK "Generated power MARK A 4.86 4.42"3 4.5 MARK "Pitch angle END
/LVWLQJ 92 Listing of macro to simulate the wind power plant.

3:62

3DUW  7XWRULDO ([DPSOHV

[m/s] 22

Wind speed

18

14 0 [%] 130 Generated power 10 20 30 40

110

90 0 [deg] -4 Pitch angle 10 20 30 40

-8

-12 0 10 20 30 40

)LJXUH 93 Simulation of the responses to a wind disturbance of the wind power plant. 6\VWHP :,1' %86 *(1 *($5 92/7&217 6(592 785%,1) 3,7&+5(* 7RWDO 6WDWHV 0 0 7 1 3 1 11 13  9DULDEOHV 8 0 53 12 6 1 121 79  3DUDPHWHUV 9 9 22 9 10 3 29 48  ,QSXW 0 0 7 2 2 1 5 3  2XWSXW 3 3 6 2 1 1 2 1 

7DEOH 91 Summary of the number of states etc, for the wind power plant simulation.

3:63

3DUW  7XWRULDO ([DPSOHV

 8VLQJ 6LPQRQ IRU 2SWLPLVDWLRQ


Consider the problem where one regulator parameter has to be optimised based on evaluations of the results from several simulations of the step response of the control system. The optimisation is made by Golden Section. This algorithm is based on the assumption that there is only one local minimum of the loss function. Only function evaluations are used and no information about partial derivatives is used. 7KH 3UREOHP A motor for positioning is controlled using feedback from measurement of the angle \(W) and the velocity. The system is described by the differential equation for the motor
dy dy + = u(t) dt dt

and the regulator


u(t) = K(y r (t) y(t)) T dy dt

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 is evaluated according to the ITAE criteria.

J(T) = | y r ( ) y( )|d
0

7KH ,GHD %HKLQG WKH 2SWLPLVDWLRQ $OJRULWKP The optimisation algorithm is based on the only assumption that the loss function has one local minimum. The algorithm uses only information about the value of the loss function. No information about partial derivatives is used. Initially, an upper and lower bound of the parameter to be determined must be given . The algorithm evaluates the loss function for a small number of different values of the parameter in the interval. The algorithm is in fact optimal in the sense that it uses the least number of evaluations of the loss function for a given desired accuracy. The algorithm is easy to understand. The idea is shown in Figure 94. Start with three evaluations of the loss function -(3): at the end of the interval 3ORZ and 3KLJK, and at a third point 3PLQ. 3PLQ is the value of the parameter, that gives the current smallest value of the loss function. 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 optimal parameter can be reduced. The fourth point 3 is chosen symmetrical with respect to 3PLQ in the interval of uncertainty, since no a priori information about the location of the minimum is available.

3:64

3DUW  7XWRULDO ([DPSOHV

)LJXUH 94 The principle used in the golden search algorithm.

This rule to choose "the fourth point" in the remaining interval of uncertainty is applied in each iteration. Thus, the initial choice determines subsequent choices of 3 to be evaluated. A good choice of initial value is dependent on how many evaluations that should be made. An analysis shows that the optimal choice of initial value 30 when 1 evaluations should be done is
P0 0 = Plow + FN 1 (Phigh Plow ) FN

where )1 and )1-1 are two subsequent Fibonacci numbers. The final uncertainty of 3 is after 1 evaluations (3KLJK-3ORZ)/)1. These results can be found in for instance Luenberger (1984). 6WUXFWXUH RI WKH &RGH The performance of the control system should be evaluated by simulation for each value of the regulator parameter. The different simulations are used by the optimisation procedure and the results 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 system and 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 viewed as 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 algorithm linopt. Each step in the optimisation starts with a given value of the velocity feedback 7 from linopt, then the step response of the process is evaluated by loss, and the value of -() is obtained at the end of the step. linopt then uses the value -() to calculate the next value of to be tested, and the initial values of the process and loss are reset. Since loss depends on time, a local time tau is introduced, which is set to zero at the start of each step response. A practical device is the signal alarm. If the loss function -() grows above a certain level, alarm is set true and the output in process is frozen. In this way a poor choice of that gives unstable control actions will not cause overflow and terminate the whole simulation. The programs are found in Listings 93 - 96. The subsystem linopt can,

3:65

3DUW  7XWRULDO ([DPSOHV

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 be changed when linopt is used in another application. +RZ WR 5XQ WKH 2SWLPLVDWLRQ After the user has specified the loss function and how long simulation time that should be used for evaluation, it is only needed to give a simple command that runs the optimisation. A macro search has been written for this purpose. See Listing 98. The input parameters are the 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 the command SUSPEND is given. If the user decides there are too many evaluations and does not want to start the optimisation, he gives the command END. Otherwise, he gives the command RESUME and the optimisation is started with the calculated optimal starting point 30, and it runs to the end. It is a good idea to follow the optimisation and plot the different step responses for each value of the parameter as they are evaluated. After the optimisation the final step response can be inspected. It may also be interesting to take a look at the actual loss function -() and how the parameter converged. The macro msearch generates Figure 95 along these lines.

)LJXUH 95 The result of an optimisation of one parameter.

See Listing 97. Note the command TURN DARK ON, which affects how the diagrams are plotted. It implies that the lines are eliminated that combine the end point of one evaluation with the start point of the next. In Figure 95 the result from one optimisation is shown , where the optimal value of is searched over the interval [0,2]. To obtain the desired accuracy 12 evaluations of the loss function are made. The parameter converges to a value that gives the closed loop system a damping of about 0.75. Without velocity feedback (=0) the closed loop damping is 0.5. DISCRETE SYSTEM linopt "Discrete system to perform optimization of one parameter INPUT J OUTPUT Peval tbegin STATE Plo Phi Pmin P Jmin NEW qPlo qPhi qPmin qP qJmin 3:66

3DUW  7XWRULDO ([DPSOHV

TIME t TSAMP ts "Update the search state: left = P<mid decr = J<Jmin PloFix = 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 P newPhi = IF PhiFix THEN Phi ELSE IF decr THEN Pmin ELSE P newPmin = IF decr THEN P ELSE Pmin qJmin = IF t>0.5*teval AND decr THEN J ELSE Jmin qPlo = IF t>1.5*teval THEN newPlo ELSE Plo qPhi = IF t>1.5*teval THEN newPhi ELSE Phi qPmin = IF t>0.5*teval THEN newPmin ELSE Pmin qP = 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] = 0 x2[process] = 0 x1[loss] = 0 "New sample: ts = t+teval tbegin = t "Initial values that should be set by the user Plo : 0.0 "Lower bound of parameter Phi : 1.0 "Upper bound of parameter P : 0.61803 "Golden section ratio Jmin : 1E33 "Max real value teval: 20 "Simulation time for evaluation END
/LVWLQJ 93 Simnon code /,1237 for the optimisation algorithm.

CONTINUOUS SYSTEM process "Motor process with proportional and derivative controller INPUT T alarm OUTPUT e STATE x1 x2 DER dx1 dx2 "Process: dx1 = IF alarm<0.5 THEN -a*x1 + u ELSE 0 dx2 = IF alarm<0.5 THEN x1 ELSE 0 y = x2 "Regulator: u = K*e-T*x1 "Output: e = yr-y

3:67

3DUW  7XWRULDO ([DPSOHV

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


/LVWLQJ 94Code for the motor control system SURFHVV.

CONTINUOUS SYSTEM loss "Evaluates the ITAE loss function INPUT e tau OUTPUT J alarm STATE x1 DER dx1 "Loss ITAE: dx1 = IF NOT alarm THEN tau*abs(e) ELSE 0 J = x1 "Alarm test: alarm = IF J>Jmax THEN 1 ELSE 0 "Parameters: Jmax : 1000 END
/LVWLQJ 95 Code for the loss function ORVV.

CONNECTING SYSTEM tune TIME t T[process] e[loss] J[linopt] tau[loss] alarm[process] END
/LVWLQJ 96 Simnon connecting system WXQH.

= = = = =

Peval[linopt] e[process] J[loss] t-tbegin[linopt] alarm[loss]

MACRO msearch SPLIT 2 2 AXES v -0.1 1.2 h 0 20 TEXT All step responses AXES v -0.1 1.2 h 220 240 TEXT Optimal step response AXES v 0 5 h 0 2.0 TEXT Loss function J(T) AXES v 0 2 h 0 240 TEXT Convergence of T SYST process loss linopt tune STORE y[process] tau J[loss] T[process]

3:68

3DUW  7XWRULDO ([DPSOHV

ERROR 0.0001 AREA 1 1 PLOT y(tau) TURN DARK ON search 0 2 0.01 AREA 1 2 SHOW J(T) AREA 2 1 SHOW 220 240 y AREA 2 2 TURN DARK OFF SHOW T END
/LVWLQJ 97 The macro that generates Figure 95.

MACRO search plow phigh acc; nmax "Generates the number of evaluations and starting value for "optimization of one parameter LET 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 number LET qf2.=f1.+f2. "of evaluations LET qf1.=f2. LET f1.=qf1. LET f2.=qf2. LET x.=f1./f2. LET uncn.=unc0./f1. LET n.=i IF uncn. LE acc GOTO exit NEXT i LABEL exit WRITE Required number of evaluations : n. SUSPEND LET p0.=x.*unc0. LET p0.=plow+p0. INIT p:p0. INIT pmin:p0. INIT phi:phigh INIT plo:plow DISP teval/teval LET toptim.=n.*teval. SIMU 0 toptim.

3:69

3DUW  7XWRULDO ([DPSOHV

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

3:70

3DUW  7XWRULDO 5HIHUHQFHV

 5HIHUHQFHV
Simnon inherited many ideas from the tradition of analogue and digital simulation in the control 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 simulation languages like CSMP and CSSL were implemented using batch calculations. The languages also inherited several constraints from the analogue simulators. For example the state space notation which is so natural was not supported by proper language constructs. When Simnon was developed the main idea was to provide a tool which supports the state space notation with good man-machine interaction based on interactive computing. Integration of ordinary differential equations is a key feature of Simnon. A good introduction 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. NRSETT,and G. WANNER (1987): 6ROYLQJ 2UGLQDU\ 'LIIHUHQWLDO (TXDWLRQV ,1RQVWLII 3UREOHPV, Springer-Verlag, Berlin. Examples of simulation of control systems are given in the textbook: STRM, K.J.,and B. WITTENMARK (1990): &RPSXWHU &RQWURO 6\VWHPV, 2nd edition, PrenticeHall, New Jersey. All graphs giving simulation results in the book are generated by macros in Simnon. The user can easily reproduce and modify the simulations. The macros are also available on disk from SSPA Systems, Gteborg Sweden The 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 for a Wind Turbine System", -RXUQDO RI (QHUJ\, 7, No.4, July--August, 319--324.

3:71

3DUW  7XWRULDO 5HIHUHQFHV

The optimization procedure used in Chapter 9 is based on: LUENBERGER, D. G. (1984): /LQHDU DQG 1RQOLQHDU 3URJUDPPLQJ, Addison and Wesley, Reading, MA.

3:72

3DUW  5HDO 7LPH 6LPXODWLRQ

3DUW  5HDO 7LPH 6LPXODWLRQ ,QWURGXFWLRQ

 ,QWURGXFWLRQ
A PC running Simnon with 5HDO 7LPH &DSDELOLW\ can be used to control a physical process. In this way a new regulator algorithm can be tested with greater realism than an off-line simulation could offer. Conversely, the PC could emulate a physical process thats too delicate to tamper with. Hopefully, this could let you test control hardware in a more convenient way than 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 Synchronisation Threshold. Chapter 5 is a summary of Diverge Setting technique. Chapter 6 finally is a general discussion about real time simulation performance and the factors that influence the overall performance. An important feature in Simnon/PCW related to real time simulation is DDE linking to other programs. Read the chapter Data Exchange with Other Programs in this manual to learn more about this.

4:74

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

 5HDO WLPH VLPXODWLRQ XQGHU :LQGRZV

tA tB tD tE Simnon calculations during normal real time simulation

tG

tB tC tD tE tF tG tH tA Simnon calculations during real time simulation where another Windows process interferes with the time syncronisation
tA-B: Simnon calculation tB-D: Time period when Simnon is ready to permit external processes to be activated (Yields are offered to Windows) tC: External process invoked. Must take place before tD to be permitted by Simnon tC-F: External process running. tD-E: Yield treshold. tE: By Simnon requested moment for beginning of next step calculation tE-G: Syncronisation treshold tF: External process returns control to Simnon. As tF comes later than tE but before tG, a new calculation is started immediately. If tF had come after tG, the simulation had been interrupted with message Syncronisation error tF-H: Simnons next calculation

Real Time simulation under Windows is quite different from ordinary real time processes run in a PC. The major difference is found already in the basic principle of Windows. While any program run under DOS has full control over the process and processor, in Windows the operating system is always ready to accept calls from sleeping processes, these calls often being initiated by mouse movements and clicks. Such a call can cause problems with the time synchronisation. For example, you can hardly 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. Yield threshold and synchronisation threshold control the programs behaviour between simulation

4:75

3DUW  5HDO 7LPH 6LPXODWLRQ <LHOG WKUHVKROG

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

 <LHOG WKUHVKROG
Between simulation steps, an ongoing simulation can yield to other processes, that may be called by the operator or by the computer itself. The \LHOG WKUHVKROG is a safety margin set in Simnon, 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 process call until the next Simnon calculation is scheduled.

 6\QFKURQLVDWLRQ WKUHVKROG
When an external process returns the control to Simnon, we must ensure that a proper synchronisation is re-established between the simulation and the real time, represented by the clock built into the computer. If the return comes after a new simulation step has been scheduled, a synchronisation error occurs. It is up to the operator to decide the maximum acceptable level of this error. This is called 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 command VLPXODWH_VLPXODWH. When Simnon encounters a synchronisation error that lays within the set threshold, the program automatically tries to catch up with the real time. Synchronisation errors are not lost during the further process consider the synchronisation threshold as the maximum integrated 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 by means of DDE-links. Simnon is the server, and the program that receives the data is called client. It is important to understand that from Simnons point of view this process is similar to a subroutine call, and hence not a yield. The time consumed by the client is in the diagram above a part of Simnons 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. These are 6WHS GLYHUJH sets how many integration steps that should be done between each DDE update. 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.

4:76

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

A thorough description of Simnon DDE functions, including diverge settings, is found in the chapter 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 without loosing 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 have time consuming processes like interpretative animation programs or human interaction with Simnon via DDE (parameter changes etc), chances are great that you must increase the synchronisation threshold. If an animation is made by the client program, the performance of the 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 the Command 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 error that was encountered. Use these data to adjust your simulation settings to fit your particular needs.

4:77

You might also like