Simnon - Tutorial
Simnon - Tutorial
,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.
3:14
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
)XQGDPHQWDOV
This chapter gives an overview of system descriptions and interaction principles used in Simnon.
(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
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.
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
'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.
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.
(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
)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.
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
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.
*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
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
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
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
"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
'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
)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
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
"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
)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
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
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
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
ELSE uhigh)
3:35
uhigh:1 END
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
3:36
)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
$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.
3:38
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
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.
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
'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
$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
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
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
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
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
)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
)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
3:48
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.
3:49
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.
3:50
Please refer to the documentation for your specific client program for detailed information about its capabilities to send various message types to Simnon.
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
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 .
3:53
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>
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.
3:54
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 WQ YQ Y Y YQ YP YP YPQ
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.
3:55
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.
3:56
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.
3:57
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
([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.
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
)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
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
"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
[m/s] 22
Wind speed
18
110
-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
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
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
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.
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
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
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.
= = = = =
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
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
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
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
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
,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
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
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.
4:76
A thorough description of Simnon DDE functions, including diverge settings, is found in the chapter Data Exchange with Other Programs in this manual.
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.
4:77