Users Guide to Models in ATP.pdf

USERS GUIDE TO MODELS IN ATP April 1996 i ACKNOWLEDGMENTS The writing of this manual would not have been possible wi

Views 157 Downloads 6 File size 869KB

Report DMCA / Copyright

DOWNLOAD FILE

Recommend stories

Citation preview

USERS GUIDE TO MODELS IN ATP

April 1996

i

ACKNOWLEDGMENTS The writing of this manual would not have been possible without the participation of the many users of MODELS who, over the years, have contributed suggestions and prompted discussions on many aspects of the language and its use in ATP. These people certainly deserve a large share of the credit for the work that has been done.

USERS GUIDE TO MODELS IN ATP

ii

PREFACE This Users Guide has been written with the purpose of introducing the MODELS language for use with ATP. It is written mostly in a conversational style, as opposed to the more formal descriptions found in the MODELS Language Manual of the ATP Rule Book. The purpose of this guide is to explain how the MODELS language is held together, and to illustrate its usage with discussions and examples. I realize that a manual like this is never done. There are many aspects to using a programming language and to doing simulation. They are best understood through one's own experience and glimpses at the experience of others. We can continue adding examples to this Guide forever. This first version covers the basic aspects of using the MODELS language. The main features of the language are discussed in detail and illustrated with examples. The interface between MODELS and ATP is also discussed at length. What is not included are detailed examples of electrical and control components, descriptions which, in my opinion, are beyond the scope of this introduction. The objective of this manual is to explain the "how" and the "why" of using MODELS. The "what" of the applications belongs to one or more separate tutorials covering those subjects, for the application specialists to provide. As it is true for any tool, how much a program is used depends to a large extent on how much its features are understood. With the usual time pressure of our work, of course we wish to be able to use something like this instantly. Having the time to play with a new tool is a luxury we can't always afford. But one has to realize that any product that took a few years to prepare needs at least a few hours of exposure to it to get the whole picture. I hope that the time looking at this manual will be time well spent. Laurent Dubé, April 1996.

USERS GUIDE TO MODELS IN ATP

iii

OUTLINE Acknowledgments Preface Outline Contents Introduction 1. Basic aspects of the MODELS language 2. Writing a model 3. Writing expressions 4. Specifying simulation directives 5. Using a model 6. Using MODELS in ATP 7. Libraries of models and functions Appendix A – Syntax of the MODELS language Appendix B – Keywords of the MODELS language Appendix C – Pre-defined constants and variables Appendix D – Pre-defined functions Bibliography Index In closing ...

USERS GUIDE TO MODELS IN ATP

iv

CONTENTS

Acknowledgments .................................................................................................. i Preface .................................................................................................................. ii Outline .................................................................................................................. iii Contents ............................................................................................................... iv Introduction ...........................................................................................................1 1. Basic aspects of the MODELS language .....................................................1 1.1. Why use MODELS ....................................................................................2 1.1.1. MODELS in ATP ................................................................................2 1.1.2. Starting to use MODELS ...................................................................2 1.1.3. Overall form .......................................................................................2 1.1.4. Similar to a programming language ...................................................3 1.1.5. What's particular to MODELS ............................................................4 1.1.6. What about TACS? ...........................................................................5 1.1.7. Reasons for using MODELS in a project ...........................................5 1.2. Value-holding elements, and values .........................................................6 1.2.1. Kinds of value-holding elements ........................................................6 1.2.2. Scalars and arrays .............................................................................7 1.2.3. Use of arrays .....................................................................................8 1.2.4. Representation of numbers ...............................................................8 1.2.5. Limits .................................................................................................9 1.3. Notation, format, and conventions ............................................................9 1.3.1. Model, MODELS, and MODEL ..........................................................9 1.3.2. Equal sign and assignment sign ........................................................9 1.3.3. Parentheses, brackets, and braces .................................................10 1.3.4. Blank lines .......................................................................................10 1.3.5. Names .............................................................................................11 1.3.6. Delimiters.........................................................................................11 1.3.7. Comments .......................................................................................11 1.3.8. Line indentation ...............................................................................12 2. Writing a model ..............................................................................................13 2.1. Defining the value-holding elements .......................................................13 2.1.1. Defining constant elements .............................................................13 2.1.2. Defining data elements ....................................................................14 2.1.3. Defining input elements ...................................................................15 2.1.4. Defining variable elements ..............................................................16 2.1.5. Defining output elements .................................................................16 2.2. Defining the submodels ..........................................................................17 2.2.1. Locally-defined submodels ..............................................................17 2.2.2. Foreign submodels ..........................................................................18 2.2.3. External submodels .........................................................................21 2.3. Defining the functions .............................................................................23

USERS GUIDE TO MODELS IN ATP

v 2.3.1.Statement functions ...........................................................................23 2.3.2. Pointlist functions.............................................................................24 2.3.3. Foreign functions .............................................................................26 2.4. Writing the procedures ............................................................................28 2.4.1. The EXEC procedure ......................................................................28 2.4.2. The INIT procedure .........................................................................28 2.4.3. Named procedures ..........................................................................30 2.5. Writing the statements of a procedure ....................................................31 2.5.1. Value assignment statement ...........................................................32 2.5.2. Differential equation, Laplace and z transfer functions ....................33 2.5.3. Integral value assignment ................................................................38 2.5.4. History expression assignment ........................................................38 2.5.5. IF statement.....................................................................................39 2.5.6. WHILE statement ............................................................................42 2.5.7. FOR statement ................................................................................42 2.5.8. DO statement ..................................................................................44 2.5.9. REDO statement .............................................................................44 2.5.10. COMBINE statement .....................................................................45 2.5.11. ERROR statement .........................................................................51 2.5.12. USE statement ..............................................................................52 2.5.13. Call to a procedure ........................................................................52 2.5.14. Call to a pre-defined procedure .....................................................53 3. Writing expressions ........................................................................................54 3.1. Regular expressions ...............................................................................54 3.1.1. Referring to a named value-holding element ...................................54 3.1.2. Specifying a numerical value ...........................................................57 3.1.3. Using a value calculated by a function ............................................57 3.1.4. Using a value calculated by a procedure .........................................58 3.1.5. Logical and numerical operators......................................................58 3.1.6. Limits on a regular expression .........................................................59 3.1.7. Using expressions with arrays .........................................................60 3.2. Special expressions ................................................................................61 3.2.1. Linear sum .......................................................................................61 3.2.2. Polynomial of derivatives .................................................................62 3.2.3. Integral expression ..........................................................................62 4. Specifying simulation directives .....................................................................65 4.1. Specifying the time step range................................................................65 4.2. Specifying the input interpolation method ...............................................66 4.3. Specifying the size of the delay storage .................................................67 4.4. Specifying history expressions ................................................................68 5. Using a model ................................................................................................70 5.1. Assigning data values .............................................................................70 5.2. Assigning input values ............................................................................70 5.3. Retrieving output values .........................................................................71 5.4. Specifying simulation directives ..............................................................71 5.5. Calling a model more than once per time step .......................................72 5.6. State of a model......................................................................................73 USERS GUIDE TO MODELS IN ATP

vi 6. Using MODELS in ATP ..................................................................................75 6.1. The MODELS section of a data case......................................................75 6.1.1. Inputs from ATP...............................................................................76 6.1.2. Outputs to ATP ................................................................................82 6.1.3. Variables in the MODELS section ...................................................83 6.1.4. RECORD for printout/plotting ..........................................................84 6.1.5. Model descriptions ...........................................................................84 6.1.6. MODELS formatting vs. ATP formatting ..........................................86 6.2. Using a model in the MODELS section ...................................................86 6.3. Using a model with the type-94 component ............................................89 6.3.1. Thevenin, iterated, and Norton ........................................................91 6.3.2. Initializing the type-94 component ...................................................93 6.3.3. Foreign models with a type-94.........................................................94 6.4. Using MODELS with ATP's FREQUENCY SCAN ..................................95 6.5. Steady-state initialization ........................................................................96 6.6. List sizes in ATP for MODELS ................................................................98 7. Libraries of models and functions ..................................................................99 7.1. Signal sources ........................................................................................99 7.1.1. Examples of some common sources .............................................100 7.1.2. Sample data case ..........................................................................101 7.2. Library of complex-value functions .......................................................102 7.2.1. Examples of complex-value functions ...........................................103 7.2.2. Sample data case ..........................................................................104 7.3. Library of TACS-like devices .................................................................105 7.3.1. TACS type-50 frequency meter .....................................................105 7.3.2. TACS type-51 relay-operated switch .............................................106 7.3.3. TACS type-52 level-triggered switch..............................................107 7.3.4. TACS type-53 transport delay .......................................................107 7.3.5. TACS type-54 pulse delay .............................................................107 7.3.6. TACS type-55 digitizer ...................................................................109 7.3.7. TACS type-56 point-by-point nonlinearity ......................................109 7.3.8. TACS type-57 time-sequenced switch ...........................................110 7.3.9. TACS type-58 controlled integrator ...............................................110 7.3.10. TACS type-59 simple derivative ..................................................111 7.3.11. TACS type-60 input-IF component ..............................................111 7.3.12. TACS type-61 signal selector ......................................................111 7.3.13. TACS type-62 sample/hold and track/hold ..................................112 7.3.14. TACS type-63 instantaneous min/max ........................................113 7.3.15. TACS type-64 min/max tracking ..................................................114 7.3.16. TACS type-65 accumulator / counter...........................................115 7.3.17. TACS type-66 RMS value............................................................116 Appendix A – Syntax of the MODELS language .............................................117 MODELS section in ATP...............................................................................117 MODELS section input declaration ...........................................................117 MODELS section output declaration.........................................................117 MODELS section variable declaration ......................................................117 MODELS section model declaration .........................................................117 USERS GUIDE TO MODELS IN ATP

vii MODELS section USE statement .............................................................118 MODELS section RECORD directive .......................................................118 record element..........................................................................................118 Description of a local model ..........................................................................118 declaration in a model ..............................................................................118 declaration of a constant element.............................................................118 declaration of a data element ...................................................................119 declaration of an input element ................................................................119 declaration of an output element ..............................................................119 declaration of a variable element ..............................................................119 declaration of a function ...........................................................................119 declaration of a statement function...........................................................119 declaration of a point list function .............................................................119 declaration of a foreign function ...............................................................119 declaration of a submodel ........................................................................120 declaration of a local model ......................................................................120 declaration of a foreign model ..................................................................120 declaration of an external model ..............................................................120 simulation directive in a model..................................................................120 history directive .........................................................................................120 time step directive .....................................................................................120 input interpolation directive .......................................................................121 delay cells directive...................................................................................121 Procedure in a model ...............................................................................121 initialization procedure ..............................................................................121 execution procedure .................................................................................121 named procedure .....................................................................................121 Statement .....................................................................................................122 assignment statement ..............................................................................122 value assignment ......................................................................................122 differential equation ..................................................................................122 y, x ............................................................................................................122 D-polynomial .............................................................................................122 limits .........................................................................................................123 Laplace transfer function ..........................................................................123 y, x ............................................................................................................123 S-polynomial .............................................................................................123 limits .........................................................................................................123 z transfer function .....................................................................................123 y, x ............................................................................................................124 z-1-polynomial ..........................................................................................124 limits .........................................................................................................124 integral value reset assignment ................................................................124 history assignment ....................................................................................124 algorithm control statement ......................................................................124 IF statement..............................................................................................125 WHILE statement .....................................................................................125 USERS GUIDE TO MODELS IN ATP

viii FOR statement .........................................................................................125 DO statement ...........................................................................................125 REDO statement ......................................................................................125 COMBINE statement ................................................................................125 ERROR statement ....................................................................................126 USE statement .........................................................................................126 procedure call ...........................................................................................126 write-list ....................................................................................................126 Directive in a USE statement ........................................................................126 USE data directive ....................................................................................127 USE input directive ...................................................................................127 USE output directive .................................................................................127 USE history directive ................................................................................127 USE time step directive ............................................................................127 USE input interpolation directive...............................................................127 USE delay cells directive ..........................................................................127 Expression ....................................................................................................128 regular expression ....................................................................................128 sum expression in a value assignment .....................................................128 derivative expression in a value assignment ............................................128 integral expression in a value assignment ................................................128 Regular expression .......................................................................................128 logical term ...............................................................................................129 logical factor .............................................................................................129 logical relation ...........................................................................................129 relational operators ...................................................................................129 numerical expression ................................................................................129 numerical term ..........................................................................................129 numerical factor ........................................................................................129 exponent relation ......................................................................................129 modulo relation .........................................................................................130 value reference .........................................................................................130 numerical value ........................................................................................130 array value ................................................................................................130 named value .............................................................................................130 function value ...........................................................................................130 Value-holding element ..................................................................................131 single-value element .................................................................................131 array-value element ..................................................................................131 Syntactic element..........................................................................................131 name.........................................................................................................131 numerical value ........................................................................................131 logical value ..............................................................................................132 text value ..................................................................................................132 in-line comment ........................................................................................132 block comment .........................................................................................132 separator ..................................................................................................132 USERS GUIDE TO MODELS IN ATP

ix Appendix B – Keywords of the MODELS language ........................................133 Keywords of the MODELS section of ATP ....................................................133 start/end....................................................................................................133 element declarations ................................................................................133 model declarations ...................................................................................133 use directives ............................................................................................133 record directives .......................................................................................133 Keywords of the Model description ...............................................................134 start/end....................................................................................................134 element declarations ................................................................................134 function declarations.................................................................................134 submodel declarations ..............................................................................134 simulation directives .................................................................................134 procedures................................................................................................135 Keywords of the Statements .........................................................................135 assignment statements .............................................................................135 algorithm control statements ....................................................................135 Keywords of the Directives in a USE statement............................................136 Keywords of the Expressions ........................................................................136 Keywords of the Regular expression ............................................................137 Keywords of the Comments ..........................................................................137 Appendix C – Pre-defined constants and variables ........................................138 Pre-defined constants ...................................................................................138 Pre-defined global variables .........................................................................138 Pre-defined local variables............................................................................139 Appendix D – Pre-defined functions................................................................141 Numerical functions ......................................................................................141 1-to-1 functions returning one value for each argument ...........................141 2-argument functions returning a single value ..........................................142 n-argument functions returning a single value ..........................................143 Logical functions ...........................................................................................143 1-to-1 functions returning one value for each argument ...........................143 n-argument functions returning a single value ..........................................144 Random value functions ...............................................................................144 Simulation functions ......................................................................................146 deriv(x)......................................................................................................147 deriv2(x)....................................................................................................147 prevval(x) ..................................................................................................148 delay(x, dval, pol) .....................................................................................148 predval(x, tval, pol) ...................................................................................149 predtime(x, xval, pol) ................................................................................149 backval(x, tval, pol) ...................................................................................149 backtime(x, xval, pol) ................................................................................150 histval(x, tval) ............................................................................................150 histdef(x) ...................................................................................................150 Bibliography ......................................................................................................152 Index .................................................................................................................157 USERS GUIDE TO MODELS IN ATP

x In closing ... .......................................................................................................162

USERS GUIDE TO MODELS IN ATP

1

INTRODUCTION This manual starts with a discussion of the basic aspects of the MODELS language, providing a general presentation of what the language does, what is special about the language, and the nuts and bolts of its rules and conventions. This is followed by a more in-depth look at the process of writing a model, writing expressions, and specifying simulation directives in a model. Various aspects of using a model are discussed next. This is then followed by a detailed presentation about using MODELS in ATP. It includes an explanation of the different declarations that can be included in the MODELS section. It also describes the different ways in which MODELS is interfaced with ATP, and how each approach can be used in the simulation of a circuit. The text concludes with a discussion and examples of building libraries of models and functions that can be assembled as a toolkit to be used in present and future simulation projects. Four sections are added as appendices to this manual. They are built for use as a quick reference to the MODELS language. The first is a summary reference to the syntax of the MODELS language. It condenses the contents of the Language Manual, presenting only the structure and the diagrams, without the text. Next comes a summary of that summary, providing a structured overview of only the keywords of the MODELS language, without the details of the full syntax rules. The other two appendices show the pre-defined constants and variables, and the pre-defined functions of MODELS, with discussions and examples.

1. Basic aspects of the MODELS language MODELS is a general technical description language supported by a simulation solver. It is a programming language targeted to time-domain simulation, and is used as a tool for describing the dynamic behavior of complex physical systems. In ATP, it can be used for describing the operation of circuit components and of control components. It can also be used for generating signals or for analyzing measurements from the circuit. Finally, it can be used as the interface between ATP and outside programs.

USERS GUIDE TO MODELS IN ATP

2

1.1. Why use MODELS 1.1.1. MODELS in ATP The purpose of having MODELS available in ATP is four-fold: 1) to have a tool for developing models of circuit and control components which cannot be built easily with the set of existing components available in ATP and TACS; 2) to have the flexibility of a full programming language without having to interact with ATP at the programming level; 3) to be able to describe not only how a component operates, but also how the initial state (initial values and initial history) of the component is established, at any required detail level; 4) to have a standard program interface to ATP defined at the modeling level in terms of voltages, currents, and control signals, as opposed to an interface which would be defined at the programming level in terms of the variables, common blocks, and subroutines of ATP; this makes it possible to connect external programs to ATP for modeling of components, access to measurements, or interaction with equipment, without requiring a programming knowledge of the internal operation of ATP, and without requiring any modification to be made to the source code of ATP. 1.1.2. Starting to use MODELS Looking at the MODELS language for the first time can feel like a large task. With some guidance at the beginning, it can be easily divided into simple parts. Starting with examples provides an easy exposure to the main aspects of the language as well as, later on, to the finer details of its syntax. Many examples are provided with this guide, and can be used as a base from which modifications can be made to describe more complex operations. 1.1.3. Overall form The structure of the language is simple, and is similar to the structure of other programming languages, for example, Pascal or Modula-2. It has a small number of keywords that can be remembered easily. There are no formatting rules to complicate its use, and every construct is introduced by a descriptive keyword. The basic module is called a model. A model consists of procedures describing how the model operates, value-holding elements to carry the state and the history of its operation and to exchange information with the outside, and directives influencing the operation of the model in a simulation.

USERS GUIDE TO MODELS IN ATP

3 Value-holding elements can be constant or variable, and can be assigned values from inside the model (types CONST and VAR) or from outside the model where the model is used (types DATA and INPUT). Two standard procedures can be defined for each model. The initialization procedure (INIT) describes the initial point of operation of the model before the simulation is started. The execution procedure (EXEC) describes how the operation of the model is updated at each successive instant of the simulation. Additional procedures can be defined for describing other actions of the model and to access the value of specific variables of the model. The simulation directives include control of the size of the time step used in the model, choice of interpolation method for determining input values at internal substeps, assignment of history expressions describing the pre-simulation values of some of the variables of the model, and allocation of special storage required for the past values of variables referenced in the model using a delay() function. A model is defined independently from the directives and location of where it will be used. Multiple instances of the same model can be used, each maintaining its individual operating point and history. 1.1.4. Similar to a programming language Users who apply the language to develop models of components and to possibly build library of components need sufficient power and flexibility from the description language. Users who more occasionally apply the language to represent a component or a numerical process, for example, need the language to be simple, so that it may be used and read with familiarity. Using a programming language approach seemed to fill both types of needs. In this regard, MODELS includes the following capabilities: - a regular syntax for the use of variables, arrays, expressions, and functions; - the use of various types of variables, holding values modified by the procedures of the model; variables can be numerical and logical, in either scalar or array form; - a set of pre-defined numerical and logical functions; additional functions can be defined by the user, in the form of parametrized expressions, point lists, and externally-programmed functions; - the use of conditions and loops (if, while, for, etc.) for structuring the execution flow of a procedure; - the use of comments within a description, as an aid to producing models and procedures that are self-documenting; - the use of arbitrarily-long names to facilitate self-documentation;

USERS GUIDE TO MODELS IN ATP

4 - an individual naming scope for each model, to allow the user to assign meaningful names to the variables used in a description, without the risk of conflicting with names chosen in other parts of the simulation; - separation of the description of a model, from its use in a simulation; - the use of multiple instances of the same component, each possibly supplied with different parameters, different inputs, or different simulation directives; - a mechanism for dividing a large component description into smaller units, for reduced model complexity, explicit identification of interfaces and operation, easier testing, and use of prototyping during model development; - the possibility to specify operations that are executed only when some conditions are met, for example for initialization, or when simulation difficulties or errors are detected. 1.1.5. What's particular to MODELS Two aspects differentiate MODELS from a regular programming language. One aspect is the set of operations and functions needed for the representation of systems that vary in time: - time automatically increases during a simulation; - individual instances of the models of a system automatically update their operation according to the increasing value of the simulation time; - the values of the variables are persistent over successive instants of time, and maintain their value during the simulation until assigned a different value; - expressions can be described as generic functions of the time "t", allowing a clear symbolic representation; an example would be referring to the time value of an oscillating signal by simply using A*sin(omega*t), with A and omega being defined elsewhere in the model; this expression automatically takes on the appropriate value at different times of the simulation; - a number of pre-defined time-based functions are available, including time integrals, time derivatives, time differential equations, Laplace and z transfer functions, and references to past and predicted values of a variable. The other aspect is that MODELS automatically manages the storage and retrieval of the history values of the variables of a model, as needed during the execution of the simulation. The time-based functions of the language all have direct access to the past values of a variable, as needed for the calculations, without imposing on the user the task of specifying how that information is stored and accessed.

USERS GUIDE TO MODELS IN ATP

5

1.1.6. What about TACS? TACS had been designed to represent mostly-linear control systems described in the form of a block diagram. TACS allows the user to assemble a description of a control system using a set of pre-defined function blocks and devices. However, it was not designed to accommodate operations represented by algorithms, although we can achieve some measure of conditional assignments by using type-60 and type-61 devices. TACS doesn't provide a mechanism to solve sets of nonlinear simultaneous equations. Any feedback loop involving a nonlinear device is automatically cut open so it can fit in the linear matrix solution of TACS, effectively inserting delays of one timestep on the outputs of such nonlinear devices. Depending on the size of the time step and on the nature of the simulated system, the consequences of this approach can range from satisfactory to numerically unstable. The interface between TACS and the simulated circuit is a unidirectional information-type interface, passing measured values from the circuit to TACS, and control variables from TACS to the circuit. No iteration mechanism is provided. At each time step, the circuit is first solved completely, measured values are passed to TACS, then TACS is solved and its outputs applied to the circuit at the next time step of the simulation. Again, depending on the size of the time step and on the nature of the simulated system, this arrangement ranges from satisfactory to numerically unstable. When TACS is used for representing control system components, this delay provides satisfactory results, as control devices always involve an element of delay in their operation in the real systems. Similarly, it is possible to control the value of an impedance in the circuit without adverse effects due to the delay (for example, representing an arc by controlling the value of a resistance). However, using a control signals to inject currents or voltages intended to represent the true power connection of a circuit component is typically not a stable proposition, unless the injected currents or voltages are strictly history values calculated from a past state of the simulation, as in the case of using a Norton equivalent to represent an inductance using bilinear transformation. Finally, in contrast with TACS, the user is not limited to a pre-defined set of components, but can build libraries of components and submodels as required by different applications. 1.1.7. Reasons for using MODELS in a project Here are some of the reasons why it may be beneficial to use MODELS in a project: - when we need to do incremental development of the various parts of the simulated system, prototyping individual elements as we go;

USERS GUIDE TO MODELS IN ATP

6 - when we need to include multiple or detailed aspect of the operation of some of the elements of the system, for example representing the thermodynamic behavior in conjunction with the electrical behavior; - when we want to include the representation of elements of the system that are already developed and available as separate subroutines written in a different program; an example might be using a model supplied by the manufacturer of a particular element; - when we have to develop from scratch the modeling of some of the components of the system, in the case that they could not be easily represented by using what's already available in ATP; we can do some of this in TACS, but MODELS provides a full algorithmic description language that can simplify the work; - when we need a component to be solved simultaneously with the rest of the circuit, avoiding the one-step delay otherwise imposed by TACS.

1.2. Value-holding elements, and values 1.2.1. Kinds of value-holding elements If we sort the types of value-holding elements according to the value held by each named element, we have: - for values global to a simulation (i.e. to all model instances of all models): - global variables: t, starttime, stoptime, startstep - global numerical constants: pi, inf, undefined - global logical constants: false, no, open, off true, yes, closed, on - for values global to all instances of one model: - constants - for values local to each instance of a model: - data, inputs, variables, resident variables If we look at the value-holding elements in terms of where we specify the expressions used for calculating their value, we can note the difference between model definition and model use: - in expressions global to all instances of a model, specified in the model definition: -

value expression of constants default expression of data default expression of inputs all value assignment expressions of variables

USERS GUIDE TO MODELS IN ATP

7 - in expressions local to each instance of a model, specified in the USE statement: - use expression of data - use expression of inputs If we look at the value-holding elements in terms of where they are visible, we can see the difference between names that are private to a model, and names that are visible outside the model where they are declared: Type

Access

Where value is specified

constant

private

model definition

data

public

default value in model definition local value in use instance

variable

private

model definition

input

public

default value in model definition local value in use instance

output

public

local value in use instance

The naming of the types is not perfect, in the sense that data are as constant as the constants, and inputs are certainly as variable as the variables. They are identified by separate type names to underline their difference of being public or private with respect to the model where they are defined. 1.2.2. Scalars and arrays Value-holding elements in a model can be declared as individually-named scalar elements: DATA d1, d2, d3 VAR y10, y11, y12

or as elements grouped in array form: DATA d[1..3] VAR y[10..12]

The elements of an array can be declared using an index range: DATA d[1..3]

or individually (useful for inserting separate comments for each): DATA d[1] d[2] d[2]

-- some descriptive comment -- ... -- ...

USERS GUIDE TO MODELS IN ATP

8 After being declared, array elements can be used separately: y[10] := d[1] + k[5] y[11] := d[2] + k[6] y[12] := d[3] + k[7]

or they can be used in a group defined by range, inside array-value expressions: y[10..12] := d[1..3] + k[5..7]

1.2.3. Use of arrays Array elements can be grouped by range inside numerical and logical equations: vbr[1..3] := vk[1..3] -vm[1..3] gate[1..6] := fire[1..6] AND flag>0

as well as when specifying function arguments: wabs[1..6] := abs(w[1..6])

In the few circumstances where a group of array elements cannot be used as a range, for example on the left side of a Laplace assignment, it is still possible to use an indexed array notation inside a FOR structure, as in the following: FOR i=1 TO 3 DO laplace(y[i]/x[i]) := (s_polynomial)/(s_polynomial) ENDFOR

The use of an array notation can simplify the description of a model, and also contributes to reducing the execution time of the simulation. 1.2.4. Representation of numbers All quantities inside a MODELS simulation are represented as double-precision floating point numbers. Some observations follow: - the value of a Boolean operation or conversion is 0.0 or 1.0 in doubleprecision (note that in MODELS, numerical operators can be applied to Boolean values and vice versa); - when used as index to an array, the result of an expression is internally rounded to the nearest integer; - both rounding and truncation can be forced inside an expression using the functions round() and trunc(); - all operations involving some kind of value comparison automatically include a round-off multiplier of 10-8, which means that the granularity of any point value

USERS GUIDE TO MODELS IN ATP

9 is 10-8 times its value, to the left and to the right, anywhere on the number line. Examples, where margin = b times 10-8 : a>b

is calculated as

a > b+margin

a=b

is calculated as

a >= b-margin AND a = 0

is calculated as

a >= 0 (because margin=0)

1.2.5. Limits Values are specified in expressions. In addition, each expression can be qualified by a minimum value and a maximum value. These limits are themselves described using an expression which may vary in value during a simulation. Limits are discussed in more detail below, in the sections on COMBINE, differential equations and transfer functions, integrals, and expressions. a := 3*b -c {min: amin, max: amax} y := integral(x) {dmax: 3*a} laplace(y/x) := (s_numerator)/(s_denominator) {dmin: ymin*cos(omega*t)}

1.3. Notation, format, and conventions 1.3.1. Model, MODELS, and MODEL When referring to the MODELS language, we use all upper case characters for the word. When referring to a model description written in the MODELS language, we use the word model written in regular lower case. The upper case singular form MODEL is the keyword that starts a model description. 1.3.2. Equal sign and assignment sign A distinction is made in the MODELS language between value assignment and value equality. Value assignment is identified by the assignment operator ":=". Value assignment is an action. When a value is assigned to a named value-holding element, the assignment operation is expressed using ":=", for example: w[2] := expression

or laplace(y/x) := (s_numerator)/(s_denominator)

USERS GUIDE TO MODELS IN ATP

10 Value equality is identified by the equality operator "=". Value equality is a condition that can be true or false. It is used as a logical relation in a logical expression, for example: IF a = b THEN ... ENDIF

1.3.3. Parentheses, brackets, and braces The left and right parenthesis characters "(" and ")" are used to enclose the arguments of a function. In this case, the left parenthesis must immediately follow the function name, without any space. For example: y := delay(x1, delay_value) integral(w) := expression laplace(x1/x2) := (1|s0) / (1|s0 + tau|s1) histdef(integral(y2)) := 2*histdef(y1)

The parentheses can also be used by themselves inside an expression to designate a sub-expression: y := a -(2*b -c)

The left and right square bracket characters "[" and "]" are used to identify an element or a range of elements of an array. In this case, the left bracket must immediately follow the function name, without any space. They can be used with an array name to identify elements of that array: wabs[1..n] := abs(w[1..n])

The brackets can also be used by themselves inside an expression to indicate a grouping of values into an array value: vpp[1..3] := [va-vb, vb-vc, vc-va]

The left and right brace characters "{" and "}" are used to identify some attribute, like default value, limit value, type, argument count, etc. For example: INPUT va { v(NODEA) } CONST twopi { val: 2*pi } DATA freq { dflt: 50 } FUNCTION windspeed FOREIGN { ixarg: 2 }

1.3.4. Blank lines MODELS has its own syntax rules, separate from ATP. Among other things, it allows the insertion of white space anywhere in the MODELS section, including blank lines and tabs. So, for example, there is no need to start blank lines in the

USERS GUIDE TO MODELS IN ATP

11 MODELS section with "C ", necessary for indicating comment lines in the rest of ATP. 1.3.5. Names Names can be composed using any combination of letters, digits, and the underscore character "_", with the restriction that a name must start with a letter. Names are not case-sensitive. Upper and lower case can be used for readability, but not for distinguishing two names of the same spelling. Keywords of the language are typically written in capitals for readability, but this is not necessary for interpretation by the parser. Hyphens are not permitted inside a name, and will be interpreted as a minus sign. 1.3.6. Delimiters From a parsing point-of-view, all constructs of the language are self-delimiting. This means that some kind of end delimiter indicates where a construct ends, whether implicitly or explicitly. An implicit delimiter is what is used for indicating the end of a name, keyword, operator, or value. For example, names terminate at the first character that is not a recognized name character, and values terminate at the first character that is not a legal value character. Explicit end delimiters are keywords that indicate the end of a construct, for example, ENDMODEL or ENDIF. 1.3.7. Comments Two aspects contribute to making a model understandable. The first is to choose names that are appropriately descriptive of the value or function they are representing. The other is the liberal use of in-line comments and block comments. An in-line comment starts with a string of two or more hyphens, and automatically terminates at the end of the line. A block comment is a block of text starting with the keyword COMMENT and ending with the keyword ENDCOMMENT. This can be used to annotate a model, or to temporarily block out a part during model development or testing. MODEL m1 comment --------------------------------------------------| This is a block comment describing this model | | (the vertical bars and the hyphens are only decorative) | ------------------------------------------------ endcomment VAR a

-- this is an in-line comment describing this variable

USERS GUIDE TO MODELS IN ATP

12

1.3.8. Line indentation Line indentation in the form of tab or space characters can be used to increase the readability of a model description. There are no pre-defined formatting rules imposed by the language. Indentation rules are therefore a matter of arbitrary style. However, the use of tabs is often counter-productive if a model description is to be viewed on different text editors treating tabs in different ways.

USERS GUIDE TO MODELS IN ATP

13

2. WRITING A MODEL This section introduces the elements used when building a model description of something. The dynamic operation of a model is represented by the named elements that hold the values used in and created by the model (constants, data, inputs, variables, and outputs), and by a description of how these values are calculated and used. Procedures contain the statements where these values are used and assigned. Various types of statements are available for representing how a value is calculated and assigned. Submodels and functions can also be defined to carry out some of the calculation of these values. The use of each model and submodel can be customized for each use instance, by means of simulation directives specified in the model definition and in the USE statements introducing each instance.

2.1. Defining the value-holding elements Each model can contain any number of value-holding elements, identified by type, name, and, if an array, range of array indices. The type, name, and range of these elements must first be declared in a model before they can be used. These declarations are grouped in a model by type: constant, data, input, output, variables. In summary, the names of data and inputs are public (although they can be assigned private default expression). The names of constants and variables are private (can't be referenced in the USE statement). The value of a constant or data is constant in time. The value of a variable or input can vary in time. 2.1.1. Defining constant elements Constants are used for holding values that are defined inside the model, and that do not vary during the simulation. The names of the CONST elements are only visible inside the model where they are declared. Their value is assigned inside the model, in the declaration. The same value is used in all use instances of the model. CONST twopi {val: 2*pi} CONST power_of_2[0..8] {val: [1,2,4,8,16,32,64,128,256]}

There is a set of constants that have pre-defined names and values. They can be used without needing to be declared:

USERS GUIDE TO MODELS IN ATP

14 - pre-defined numerical constants: - pi - inf - undefined

3.14159... a large value, typically 1020 the special value 88888.88888

- pre-defined logical constants - false, no, open, off true, yes, closed, on

the value 0 the value 1

2.1.2. Defining data elements Data are used for holding values that are defined outside the model, and that do not vary during the simulation. The names of the DATA elements are visible inside the model where they are declared, and also in the USE statements defining instances of the model. Their value is assigned in the USE statements. A default value can also be optionally assigned inside the model, in the declaration. When a default value exists for a data element, assigning that element a value in the USE statement is optional. Different values can be used in different use instances of the model. DATA n DATA freq {dflt: 50}

-- an array dimension used in the model -- providing a default value

Data elements are typically used for parameters and dimensions that can be assigned a different value in different use instances of the model. Once assigned, DATA values do not vary in time. Their value is constant over the full length of a simulation. Data values are automatically calculated in the USE statement the first time the use instance is called. 2.1.2.1. Using a data value as an array dimension A data value can be used in the expressions defining the range of indices of an array. This can be useful for dimensioning an array to just the size needed in an application. DATA n INPUT vterm[1..n] VAR vtmax[1..n]

-- a dimension assigned differently in each use instance -- a variably-dimensioned input -- a variably-dimensioned variable

2.1.2.2. Dependent data values If we declare what should be a dependent data value (one that depends on the value of another data) as DATA in order to assign it a default value, we risk that it be reassigned an erroneous value in a USE statement. For example: DATA n DATA n2 {dflt: n*n}

-- an array dimension -- another array dimension

USERS GUIDE TO MODELS IN ATP

15 This is because it's inadvertently making public a name that is really private to the model. For array dimensions, this is unavoidable, and at best could be checked for consistency in the INIT procedure of the model. DATA n -- an array dimension DATA n2 {dflt: n*n} -- another array dimension ... INIT IF n2n*n THEN ERROR write('Some error message...') STOP ENDIF ...

When the data is not needed as the dimension of an array, it's better practice to hide it to the outside by declaring it as a variable, and then assign its value in the INIT procedure in function of the data value it depends on. For example, instead of doing: DATA freq {dflt: 50} DATA omega {dflt: 2*pi*freq}

-- a frequency in Hz -- the equivalent frequency in rad/sec

it would be safer to use: DATA freq {dflt: 50} VAR omega ... INIT omega := 2*pi*freq ...

-- a frequency in Hz -- the equivalent frequency in rad/sec

2.1.3. Defining input elements Inputs are used for holding values that are defined outside the model, and that vary during the simulation. The names of the INPUT elements are visible inside the model where they are declared, and also in the USE statements defining instances of the model. Their value is assigned in the USE statements. A default value can also be optionally assigned inside the model, in the declaration. When a default value exists for an input element, assigning that element a value in the USE statement is optional. Input values are automatically re-calculated in the USE statement each time the use instance is called. INPUT vterm[1..3] vref {dflt: 0}

-- value of measured terminal voltages -- value of a reference voltage, =0 if not used

Arrays of inputs can be variably dimensioned. The above example of a 3-terminal model can be replaced with a model designed for n terminals, with the value of n determined at simulation time as a data in the USE statement:

USERS GUIDE TO MODELS IN ATP

16 DATA n INPUT vterm[1..n] vref {dflt: 0}

-- number of terminals -- value of measured terminal voltages -- value of a reference voltage, =0 if not used

2.1.4. Defining variable elements Variables are used for holding values that are defined inside the model, and that vary during the simulation. The names of the VAR elements are only visible inside the model where they are declared, except when they are declared as OUTPUT (see section below). Their value can be assigned in any statement inside the model. Once assigned a value, a variable maintains that value during the simulation, until it is assigned a new value. To continue the previous example, one could track the input voltages for maximum amplitude for each terminal, let's say, and the maximum for all terminals. Let's define the variables vtmax[ ] and vmax: DATA n INPUT vterm[1..n] vref {dflt: 0} VAR vtmax[1..n] voltage vmax voltages

-----

number of terminals value of measured terminal voltages value of a reference voltage, =0 if not used tracked maximum absolute value of each terminal

-- tracked maximum absolute value of all terminal

To update the value of these variables during the simulation, statements describing how to do that can be included in the EXEC procedure of the model, with initialization in the INIT procedure, for example: INIT ... vtmax[1..n]:=0 -- initialize tracked maximum values vmax:=0 -- initialize overall tracked maximum value ... ENDINIT EXEC ... FOR i:=1 TO n DO -- for each terminal vtmax[i]:= max(vtmax[i], abs(vterm[i])) -- update tracked maximum ENDFOR vmax:= max(vmax, vtmax[1..n]) -- update overall tracked maximum ... ENDEXEC

Various other ways of assigning values to variables are described in more detail in this manual, in the section on "Writing the statements of a procedure". 2.1.5. Defining output elements Variables can be declared as OUTPUT of a model. The names of variables declared as output are made visible to the USE statements defining instances of the model. No other variable is visible outside the model. USERS GUIDE TO MODELS IN ATP

17 Continuing the above example, the values of vtmax[ ] and vmax can be specified as output of the model, as shown here: DATA n -INPUT vterm[1..n] -vref {dflt: 0} -VAR vtmax[1..n] -voltage vmax -voltages OUTPUT vtmax[1..n], vmax

number of terminals value of measured terminal voltages value of a reference voltage, =0 if not used tracked maximum absolute value of each terminal tracked maximum absolute value of all terminal -- can be used as outputs of the model

2.2. Defining the submodels As mentioned before, the dynamic operation of a model is represented by the named elements that hold the values used in and created by the model, and by a description of how these values are calculated and used. This representation can be decomposed into a hierarchy of models, each holding the description of a specific aspect of what is being modeled. How do we select to represent something as a model rather than defining it as a procedure or a function? A function has the characteristic of an expression. For a given set of arguments, it calculates and returns a set of values, without maintaining any trace of previous calls to the function, without holding any state to be used by future calls to the function, and without modifying the state of the model in which it is defined. A procedure expresses how something is done, modifying and making reference to values held in the model. A model has both value holders, to represent the state of operation of what is modeled, and procedures, to act on that state. A model maintains its own memory storage of values for each instance in which it's used. Functions don't need that kind of storage, as there is nothing to store between calls. Procedures use the existing storage of the model where they are defined. When used as a submodel inside another model, a model can be written in the MODELS language, with its description inserted locally in the declarations of the calling model. This is the locally-defined submodel. A model can also be a separate program, written in any language, and accessed through the programming interface of MODELS. This is a foreign submodel. A local or foreign model can possibly be described outside the calling model where it is used. This is declared in the calling model as an external submodel. 2.2.1. Locally-defined submodels This is the standard way of introducing a submodel. A submodel is a full model of its own, except for the fact that it is declared and used inside another model. USERS GUIDE TO MODELS IN ATP

18 Once it is declared, it can be used in that model in as many use instances as required, each one maintaining its own separate state of operation. MODEL component -- defining a model CONST ... DATA ... INPUT ... VAR ... OUTPUT ... MODEL controller -- defining a local submodel CONST ... DATA ... ... ENDMODEL ... EXEC ... USE controller AS control_1 -- using the submodel ... ENDUSE ... ENDEXEC ENDMODEL

An alternate way, that is still a locally-defined submodel, is to replace the actual description of the submodel by a reference to the file containing that description. The above example could be rewritten as: MODEL component -- defining a model CONST ... DATA ... ... $INCLUDE filename { inserting a local submodel (notice the ATP formatting) ... EXEC ... USE controller AS control_1 -- using the submodel ... ENDUSE ... ENDEXEC ENDMODEL

The $INCLUDE directive is an ATP command used for accessing the contents of other files. It's a formatted command, and must start in column 1 of a new line. 2.2.2. Foreign submodels MODELS has a simple interface for accessing other programs that can be used as submodels or functions inside a model. A program accessed as a model has to meet the following requirements: - its call arguments are pointers to four arrays - it has two separate entry points, one for initialization, and one for execution

USERS GUIDE TO MODELS IN ATP

19 The four arrays hold values of data, inputs, outputs, and stored variables. The data, inputs, and outputs correspond to the regular data, inputs, and outputs of a model. The array of stored variables is a service of MODELS, to hold internal values of the program between calls, allowing the called program to be used for more than one use instance without requiring the called program to manage separate storage for individual instances. The two entry points correspond to the INIT and EXEC procedures of a model. The initialization routine is called only when an instance of the model is used for the first time. The execution routine is called when the state of the model is to be updated according to new conditions. The declaration of the foreign model indicates the local name identifying that submodel in the calling model, the foreign name of the model, and the length of each of the four arrays. MODEL component -- defining a model CONST ... DATA ... ... MODEL controller FOREIGN control_program {ixdata:3, ixin:2*n+4, ixout:n, ixvar:5} ... EXEC ... USE controller AS control_1 -- using the submodel ... ENDUSE ... ENDEXEC ENDMODEL

In the above example, the local name is "controller", and the foreign name is "control_program". That foreign name is not necessarily the name of the foreign program itself. It is a unique identifier used in the subroutine "fgnmod" of MODELS, to recognize which foreign model is being called. It is inside that subroutine that the actual call to the foreign program is made. That subroutine needs to be edited when installing calls to new foreign programs. That subroutine is fully documented with comments, and should present no difficulty when used. Part of that subroutine is shown below, showing how the identifier "controller" of the previous example would be used:

USERS GUIDE TO MODELS IN ATP

20

C C

SUBROUTINE FGNMOD ( name, namlen, xdata, xin, xout, xvar, iniflg, ierflg) IMPLICIT REAL*8 (A-H, O-Z), INTEGER*4 (I-N) DIMENSION xdata(*), xin(*), xout(*), xvar(*) ... In the following lines, register the foreign model names as declared in the models:

C C C C C

DATA refnam(1) / 'SAMPLE_MODEL' / ! Example "ftnmodel.dat" DATA refnam(2) / 'SAMPLE_C_MODEL' / ! Example "cmodel.dat" DATA refnam(3) / 'CONTROLLER' / ! Added for this example DATA refnam(4) / ' ' / ... The following lines call the actual foreign subroutines/procedures: - actual names may be different from the foreign names used in the models - notice how each one uses both an initialization routine and an execution routine

1

IF ( iname.EQ.1 ) THEN ! "sample_model" IF (iniflg.EQ.1) THEN CALL sampli(xdata, xin, xout, xvar) ELSE CALL samplm(xdata, xin, xout, xvar) ENDIF CONTINUE ! ------------------------------------------ELSE IF ( iname.EQ.2 ) THEN ! "sample_c_model" IF (iniflg.EQ.1) THEN CALL c_sample_i(xdata, xin, xout, xvar) ELSE CALL c_sample_m(xdata, xin, xout, xvar) ENDIF CONTINUE ! ------------------------------------------ELSE IF ( iname.EQ.3 ) THEN ! "controller" IF (iniflg.EQ.1) THEN CALL contri(xdata, xin, xout, xvar) ELSE CALL contrm(xdata, xin, xout, xvar) ENDIF CONTINUE ! ------------------------------------------ELSE IF ( iname.EQ.4 ) THEN ...

It is when actually using the foreign model that the contents of the data, input, and output arrays is identified. Just like when using a local model, it is possible to specify how data, input, and history values are calculated. One difference is that the value of the local simulation time must be explicitly passed to the foreign program as one of the inputs. It's not done "magically" in the background. Outputs of the foreign model are used just like those of a local model. The contents of the array of variables is specified and managed inside the called program, not in the USE statement. However, it is possible to assign initial values to these variables using HISTORY directives, just like in a regular USE statement. Note that only initial values are passed to the foreign program, not full history expressions available only for regular models. The following example illustrates the definition and the use of a simple foreign model. Note that the four arrays have the pre-defined names "xdata", "xin", "xout", and "xvar":

USERS GUIDE TO MODELS IN ATP

21 DATA n VAR a[1..n] ... MODEL ftnmodel FOREIGN sample_model {ixdata:1, ixin:n, ixout:n, ixvar:n} ... EXEC ... USE ftnmodel AS ftnmodel DATA xdata[1]:=n -- set value of xdata[1] INPUT xin[1..n]:= ... -- load inputs xin[1..n] HISTORY xvar[1..n]:=0 -- set history of xvar[1..n] OUTPUT a[1..n]:=xout[1..n] -- use outputs xout[1..n] ENDUSE ...

The foreign program, in this case, is a Fortran subroutine that writes some text and updates the values of the outputs, without using the value of time (which is thus not passed as an input): SUBROUTINE samplm(xdata, xin, xout, xvar) DIMENSION xdata(*), xin(*), xout(*), xvar(*) CHARACTER*80 text80 ! Buffer used to assemble messages for output text80 = 'Executing model "sample_model".' CALL OUTSIX( text80, 80 ) ! Send text80 (arg 1) to ATP listing DO 1000 i=1,xdata(1) xvar(i)=(2*xvar(i)+xin(i))/2 xout(i)=xvar(i)+100.0 1000 CONTINUE RETURN ENTRY sampli(xdata, xin, xout, xvar) text80 = 'Initializing model "sample_model".' CALL OUTSIX( text80, 80 ) RETURN END

In the example, "xdata[1]" holds the dimension of the other three arrays, "xin" holds input values received from the calling model, "xout" holds output values sent back to the calling model, "xvar" holds state values stored in memory by MODELS between calls. Note how xvar is referenced before a new value is assigned to it, requiring a reference to the initial value of xvar at the first execution of the subroutine. 2.2.3. External submodels If a submodel is used in a model, but defined somewhere else, it can be introduced in the calling model as "external". It needs to be declared in the calling model, but the declaration can be as simple as mentioning the model's name and saying it's external, like this:

USERS GUIDE TO MODELS IN ATP

22 MODEL component -- defining a model CONST ... DATA ... ... MODEL controller EXTERNAL ... EXEC ... USE controller AS control_1 -- using the submodel ... ENDUSE ... ENDEXEC ENDMODEL

The full definition of the external model can be placed anywhere at the same level of the calling model or above. For the previous example, it could be found either at the same level of the "component" model as a locally-defined model: MODEL component -- defining a model ... MODEL controller EXTERNAL ... ENDMODEL MODEL controller CONST ... DATA ... ... ENDMODEL

or at the same level as a foreign model: MODEL component -- defining a model ... MODEL controller EXTERNAL ... ENDMODEL MODEL controller FOREIGN control_program {ixdata:3, ixin:2*n+4, ixout:n, ixvar:5} ...

or at a higher level: MODEL system MODEL sub_system_1 MODEL component -- defining a model ... MODEL controller EXTERNAL ... ENDMODEL ... ENDMODEL MODEL sub_system_2 ... ENDMODEL MODEL controller ... ... ENDMODEL

USERS GUIDE TO MODELS IN ATP

23 or at the same level or above, as part of a library of models: MODEL component -- defining a model ... MODEL controller EXTERNAL ... ENDMODEL $INCLUDE filename { a file holding a library of models ...

2.3. Defining the functions A function operates like an expression. When it is called, it uses the existing values of all the named references used in the function, to calculate and return a result to the expression from where it was called. A function has access to the value of its arguments and to the values of all valueholding elements of a model. However, as compared to a procedure, a function cannot modify any value other than the result it is returning. As compared to a model, a function does not have internal variables that can retain values between calls, that is, a function doesn't carry a state. A function can return a single value, or a list of values in the form of an array. Array-returning functions can be used inside expressions that use array arithmetic. In addition to the pre-defined functions supplied by MODELS, three types of custom functions can be defined in a model. Statements functions are simply re-usable named expressions. Point list functions express a relation between input and output in terms of (x, y) coordinates. Foreign functions are functions that are defined in a separate program and accessed through the programming interface of MODELS. 2.3.1.Statement functions Statement functions are defined inside a model in the form: FUNCTION somename(argname1, argname2, ... ) := expression

These functions are macro-expressions that can be used in other expressions of a model. The function's expression can be a single-value expression or an expression returning an array of values. That expression can contain references to the named arguments of the function, as well as to any value-holding element of the model. The function is used by indicating the name of the function, and by providing a list of values used by the arguments of the function:

USERS GUIDE TO MODELS IN ATP

24 somename(value1, value2, ... )

The form under which the list of values is provided is flexible, and can be a mixture of single values and of ranges of array elements, using expressions and array expressions, for example: somename(expr, array_expr, ... )

An example of this would be a two-argument function used for calculating the amplitude of a complex number, given its real and imaginary part. The arguments can be supplied as a list of two separate values, like this: FUNCTION c_ampl(real, imag) := sqrt(real*real +imag*imag) ... ym := c_ampl(xr, xi)

or can be supplied as an array of two values, with the array, in this case, being a representation of the real and imaginary part of a complex number: VAR cx[1..2] -- a complex variable as real and imaginary FUNCTION c_ampl(real, imag) := sqrt(real*real +imag*imag) ... ym := c_ampl(cx[1..2])

Refer to the section on "Using a function" for more examples. 2.3.2. Pointlist functions Pointlist functions are useful when data about a function is available in the form of a table. Pointlist functions are single-valued functions expressed as a list of coordinates in a 2-dimension plane, sorted in increasing value of the input coordinate. For example, a curve of resistance in function of temperature could be expressed as: FUNCTION temp_dep POINTLIST (-273, 1.e-6), (-60, 1.e-4), (0, 1.e2), etc...

The first coordinate of each pair corresponds to the input value, and the second coordinate corresponds to the output value of the function. What gets interesting is that the values of the coordinates can be expressed using regular expressions making reference to other variables or functions of the model. Very complex functions can be assembled using this possiblilty. An interesting example is the description of a parametrized family of curves. A pointlist function specifies what curve the function will use for different values of a parameter "k". Each curve can in turn be described using an expression that contains a reference to another function of any type. The following example illustrates a simple 1-parameter family of curves.

USERS GUIDE TO MODELS IN ATP

25 VAR a, k FUNCTION curve2(x) ... -- a statement function or a point list for k=2 FUNCTION curve4(x) ... -- a statement function or a point list for k=4 FUNCTION curve6(x) ... -- a statement function or a point list for k=6 FUNCTION f POINTLIST (2, curve1(a)) (4, curve2(a)) (6, curve3(a)) ... a:= some value -- used inside the function f(k) k:= 2.5 -- any value between 2 and 6 y:=f(k)

In the above example, the family is reduced to a set of three representative curves. The pointlist function simply specifies which of these curves (themselves functions) will be used for the three representative parameter values 2, 4, and 6. Interpolation is provided automatically. When the interpolation order is not specified, as in y:=f(2.5) in the above example, the interpolation is linear, that is, the function calculates the values of f(a) for k=2 and for k=4, and interpolates linearly between the two values to return a value for k=2.5 . The interpolation order can be specified as a second argument when using the function, and can be either 0, 1, or 2, (none, linear, quadratic), as shown in the section on "Using a function". 2.3.2.1. External point list It is possible to use the $INCLUDE function of ATP for gaining access to a list of points stored in a separate file, possibly generated by another program. The formatting requirements are that each pair be enclosed in parentheses, with the enclosed coordinates separated by a comma. The pairs must be sorted in increasing value of the first coordinate, for example: (0,0) (1,2) (2,4) (3,6) etc...

Using separate lines is not required, although a maximum line length of 80 characters is imposed by ATP. As everywhere else in a model, spacing characters are ignored. (0,0) (1,2) (2,4) (3,6) etc...

Supposing that these coordinates are available in a file named "xy.lst", they could be included in a model as follows: FUNCTION xyfun POINTLIST $INCLUDE xy.lst

-- with data points located in the following file:

USERS GUIDE TO MODELS IN ATP

26

2.3.3. Foreign functions Foreign functions are functions written in any language and linked to ATP before execution. The function call is handled by the programming interface of MODELS. A foreign procedure accessed as a function must meet the following requirements: - it has one function argument that is a pointer to an array - it returns the number of output values placed by the function in the argument array The values returned by the function in the argument array must be placed at the beginning of that array. The declaration of the foreign function in a model indicates the local name identifying that function in the calling model, the foreign name of the function, and the length of the argument array. MODEL component VAR speed[1..2] -- velocity [m/s] and direction [deg] ... FUNCTION windspeed FOREIGN wind_speed {ixarg: 2} ... EXEC ... speed[1..2] := windspeed(t) ... ENDEXEC ENDMODEL

In the above example, the local name is "windspeed", and the foreign name is "wind_speed". The dimension of the argument array is indicated as "2", because even if there is only one input argument when the function is used, the function returns two values that it places in that array. The indicated foreign name is not necessarily the name of the foreign procedure itself. It is a unique identifier used in the subroutine "fgnfun" of MODELS, to recognize which foreign function is being called. It is inside that subroutine that the actual call to the foreign procedure is made. That subroutine needs to be edited when installing calls to new foreign procedures. That subroutine is fully documented with comments, and should present no difficulty when used. Part of that subroutine is shown below, showing how the identifier "wind_speed" of the previous example would be used:

USERS GUIDE TO MODELS IN ATP

27

C C

SUBROUTINE fgnfun ( name, namlen, xarg, nval, ierflg) IMPLICIT REAL*8 (A-H, O-Z), INTEGER*4 (I-N) DIMENSION xarg(*) ... In the following lines, register the foreign function names as declared in the models:

C C C

DATA refnam(1) / 'SAMPLE_FUNCTION' / ! Example "ftnfun.dat" DATA refnam(2) / 'SAMPLE_C_FUNCTION' / ! Example "cfun.dat" DATA refnam(3) / 'WIND_SPEED' / ! Added for this example DATA refnam(4) / ' ' / ... The following lines call the actual foreign procedures: - actual names may be different from the foreign names used in the models IF (iname.EQ.1) THEN nval= samplf(xarg) ELSE IF (iname.EQ.2) THEN nval= cfun(xarg) ELSE IF (iname.EQ.3) THEN nval= wind(xarg) ...

It is when actually using the foreign function that the values of the input arguments are identified. Just as when using a local function, it is possible to specify how the function arguments are calculated. If the operation of the function varies in function of time, the value of time must be explicitly passed to the function as one of its input arguments. In the example of the wind speed function shown above, the only input argument used by the function is the value of the simulation time "t". The function returns two values, the wind velocity and direction, placed in the argument array of the function. Internally, MODELS uses the value returned by the function, which in this case will be "2", to find out how many values the function has placed in the argument array. The following example illustrates the definition and the use of another simple foreign function: VAR y[1..2], k FUNCTION f1 FOREIGN sample_function {ixarg:2} ... EXEC ... y[1..2]:=f1(k+t, -k) -- each argument can be an arbitrary expression ...

The foreign procedure, in this case, is a Fortran function that uses two input values, and returns two output values placed in the argument array: FUNCTION samplf(arg) DIMENSION arg(2) arg(1)=arg(1) +arg(2) arg(2)=arg(1)*10 samplf=2 RETURN END

USERS GUIDE TO MODELS IN ATP

28 The same function could be written in C, for example: int CFUN(double arg[]) { arg[0] = arg[0] + arg[1]; arg[1] = 10 * arg[0]; return 2; }

2.4. Writing the procedures The procedures describe the methods used by the model for accessing and modifying the values of the value-holding elements of the model during the simulation. Two procedures have pre-defined names: EXEC and INIT. The EXEC procedure is the procedure that is called when it is time to update an instance of the model to a new simulation time. It is called automatically each time a USE statement is executed. It describes how the model operates as time increases. The INIT procedure describes how to initialize the values of the variables before the simulation begins. It is called automatically when a USE statement introduces a new instance of a model. Additional named procedures can be defined, identified by arbitrary names and performing arbitrary operations on the variables of the model. 2.4.1. The EXEC procedure The EXEC procedure is the main operating procedure of the model. It is called each time a USE statement calling that model is executed. The EXEC procedure describes how the state of a model, as expressed by the value of its variables, evolves over the time of the simulation. This evolution is described by means of an arbitrary arrangement of assignment statements (value assignment, integral assignment, Laplace and z transfer functions, differential equations, and combined simultaneous equations), algorithm control statements (for conditions and repetitions using IF, WHILE, FOR, ERROR), calls to other models (USE), and procedure calls. 2.4.2. The INIT procedure The first time that a model instance is called during a simulation, the INIT procedure of the model is executed, followed by the EXEC procedure. At subsequent time steps, only the EXEC procedure is executed. The EXEC procedure can be prevented to execute at the initial use by placing its contents inside an IF statement, but see the following discussion on the subject of executing both INIT and EXEC. The initial call to a model instance can be at a

USERS GUIDE TO MODELS IN ATP

29 time different than time zero if, for example, the corresponding USE statement is written inside an IF statement in the EXEC procedure of the calling model. 2.4.2.1. Executing both INIT and EXEC at time zero Here is the reasoning at the base of the approach of having both the INIT and EXEC procedures execute at the initial time t0. If only the INIT procedure ran at t0, then it would have to contain value assignments for all the variables in the model, which means that much of the INIT procedure would duplicate what's in the EXEC procedure. Similarly, we would need to somehow call all the submodels used in the EXEC procedure, so that they be initialized too, again a duplication of the contents of the EXEC procedure. Let's turn the thing on its head and consider instead what would prevent us from having only the EXEC procedure run at t0 without an INIT procedure. The problem would be that any past value that needs to be referenced in the model during the first execution would be undefined. This can happen either explicitly, as in a_increase := a - a_old

where "a_old" has of course not been defined yet. It can also happen in implicit references to past values, as in: slope_v := deriv(v)

where the function deriv() needs to access, behind the scene, the value of v at the previous time step, which of course has not yet been stored in the model's running history, and is therefore undefined. By having both the INIT and EXEC procedures executing at the initial time, we minimize the size of INIT, and avoid code duplication which would easily create maintenance problems in the development life of the model. All we need to do in the INIT procedure is define any past values which will be referenced in the EXEC procedure before the model has had the opportunity to store these past values itself in its running history. 2.4.2.2. INIT procedure and HISTORY assignment Rather than forcing one to define all initial values and history expressions in the INIT procedure of a model, a more flexible three-level mechanism is available in MODELS. This mechanism owes its existence to the need of being able to assign history and initial values differently for different uses of the same model. If the definition of history and initial values had to be hard-coded in the INIT procedure of the model, then the contents of the model would have to be modified from one use to another, which runs counter to the approach of separating the definition from the use of the models.

USERS GUIDE TO MODELS IN ATP

30 This is why MODELS has been built so that it be possible to assign HISTORY expressions in the USE statement calling a model -- this is level one. In addition, default history expressions can be specified for any of a model's inputs and variables which require a history to be defined. The default history expression will be used only if no history is specified for that element in the USE statement. This is level two. Note that if an element is declared in a model as requiring a history, and that no default history is defined for it, then its history expression must be specified in the USE. What's left for the INIT procedure is assigning history and initial values which are private to the model, that is, which the user of the model doesn't need to know about (see the section on history expression assignment). This is level three. Of course, it's desirable to build the INIT procedure so that it takes care of as much of the history and initial value assignments as possible, leaving a minimum of concern to the user of the model. Notice that the expression defining the history of an element can make reference to the history expression of another element, which can be very useful in the INIT procedure. 2.4.3. Named procedures Although not yet available at the time this text is being written, it will soon be possible to define named procedures in a model. This is to provide the possibility of performing operations on a model other than what is done in the EXEC procedure. The implicit message guiding the operation of the EXEC procedure is "updating to a new simulation time". Using additional procedures, other operations can be executed, for example asking a model instance to reset a group of variables or to perform a write operation, or accessing the value of a specific variable of the model. This also makes it possible to connect to the operation of a model from more than one locations in the calling model, otherwise reserved to one USE statement for each instance. The final format for defining a procedure is not yet definitive, but would be in the line of this example: MODEL proc_example DATA inival {dflt:0} INPUT x VAR y INIT -- this is executed when the instance is created or first USEd integral(x) := inival ENDINIT EXEC

-- this is the default operation procedure, -- executed when the instance is used from a USE statement y := integral(x) -- assigns value of integral to y self.write_y -- calls the procedure 'write_y' ENDEXEC

USERS GUIDE TO MODELS IN ATP

31 PROC write_y write('In model proc_example, y=', y) ENDPROC PROC reset_integral(resetval) integral(x) := resetval ENDPROC PROC integral_value integral_value := integral(x) ENDPROC

-- uses one input argument -- resets the value of the integral

-- returns the value of the integral

ENDMODEL

As shown in the above example, a procedure can have zero or more input arguments, and can return zero or more output values. A procedure can be called from inside the model where it is defined, using the instance identifier "self". As shown in the next example, a procedure can also be called from another model that uses an instance of the model where the procedure is defined: MODEL test_proc MODEL proc_example EXTERNAL -- identifies a model description VAR k -- counter INIT k:=0 ENDINIT EXEC k:=k+1 USE proc_example AS example -- creates and updates an instance named -- "example" of the model "proc_example" DATA inival := -4 INPUT x := 2*t +3 ENDUSE IF k=4 THEN example.reset_integral(0) -- calls a proc of "example" ENDIF write('In test_proc at t=', t, ', integral value=', example.integral_value) -- calls another proc ENDEXEC ENDMODEL

In the above example, a procedure is called by identifying the name of the model instance to which it belongs, the name of the procedure, and the value of its input arguments, if any. The procedure "reset_integral" expects one input value, and returns no value. The procedure "integral_value" expects no input value, and returns one output value. A procedure can be used as a function inside an expression, returning one or more values to the expression. A procedure returning no values can be used as a statement inside another procedure. A procedure can be recursive.

2.5. Writing the statements of a procedure Various types of statements can be used in a procedure for assigning values to the variables of the model, for controlling the algorithmic flow of a procedure, for USERS GUIDE TO MODELS IN ATP

32 defining and using instances of other models, and for calling the procedures of a model. They are: - assigning values element := expression diffeq(d-polynomial)|y := x laplace(y/x) := (s-polynomial)/(s-polynomial) zfun(y/x) := (z-polynomial)/(z-polynomial) integral(element) := expression histdef(element) := expression - controlling the algorithm IF ... WHILE ... FOR ... DO ... REDO COMBINE ... ERROR ... - using and updating an instance of a model USE ... - using a procedure of a model instance.procname(argument values) write( ... ) 2.5.1. Value assignment statement There are two types of equations available for assigning a value to a variable: explicit and implicit. The explicit value assignment has the simple form: element := expression

The element can be a single variable y, a single element of an array variable y[expr], or a range of elements of an array variable y[expr..expr]. The types of expressions available are regular expression, sum expression, derivative polynomial expression, and integral (see the section about Expressions). A regular expression can be written to return either a single value or a list of values. Single elements, of course, can only be assigned a single value. But a range of elements can be assigned either a single value applied to all the elements of the range, or individual values taken from the list of values returned by the expression.

USERS GUIDE TO MODELS IN ATP

33 Minimum and maximum limits can be placed on the value or values returned by the expression (see Expressions). It is also possible to assign a value explicitly to the integral of a variable, as discussed in the section on integral value assignment. Finally, it is possible to associate a value expression to the history of an element (see History expression assignment). The available implicit forms of value assignment are differential equation, Laplace transfer function, and z transfer function, discussed below. 2.5.2. Differential equation, Laplace and z transfer functions These three types of assignments can each describe how the value of a variable changes with respect to the value of another variable over time. They are discussed together because their representation and their solution are similar, and are based on the same approach. The built-in form of the differential equation is a first-degree (the exponent applied to the derivatives) nth-order (the highest order of the derivative) ordinary differential equation (of one variable), as follows: or, using the operator D to replace d/dt : (a0 D 0 + a1D1 + a2 D 2 +... ) ⋅ y = x

expressed using the keyword DIFFEQ, and the vertical bar as an operator meaning "applies to": DIFFEQ(polynomial)|y := x

where the polynomial in D is expressed as follows, with the value of each coefficient described by an expression: expr|D0

expr|D1

expr|D2

...

The Laplace-transform transfer function describes the variation of a variable y with respect to a variable x, expressed as a ratio of two linear polynomials in s: Y (s) b0 + b1s + b2s2 +... = X (s) a0 + a1s + a2s2 +...

This is expressed using the following notation, again using the vertical bar as the operator "applies to": LAPLACE(y/x) := (numerator)/(denominator)

where the numerator and the denominator are each expressed as (expr|s0

expr|s1

expr|s2

... )

USERS GUIDE TO MODELS IN ATP

34 The z-transform transfer function describes the variation of a variable y with respect to a variable x, expressed as a ratio of two linear polynomials in z-1: Y (z) b0 + b1z −1 + b2 z −2 +... = X (z) a0 + a1z −1 + a2 z −2 +...

This is expressed using the following notation, again using the vertical bar as the operator "applies to": ZFUN(y/x) := (numerator)/(denominator)

where the numerator and the denominator are each expressed as (expr|z0

expr|z-1

expr|z-2

... )

In each of the above types of representations, the polynomials are linear in D, s, or z-1. However the coefficients of the polynomials can be arbitrary time-variant nonlinear expressions. When the coefficients are known to be constant, the use of the keyword CDIFFEQ, CLAPLACE, and CZFUN will reduce execution time by avoiding the recalculation of the coefficients at each time step. The elements y and x are single-value elements, whether single variables or single elements of a variable array, and cannot be a range of multiple array elements. 2.5.2.1. Numerical solution Using the differential equation is equivalent to using the Laplace transfer function with N(s)=1, as the variable s translates to the time derivative d/dt when converted from the frequency domain to the time domain. As seen below, (a0 D 0 + a1D1 + a2 D 2 +... ) ⋅ y = x

is equivalent to Y (s) 1 = X (s) a0 + a1s + a2 s2 +...

Conversely, the Laplace representation can be solved in the time-domain by converting the numerator and the denominator to polynomials of derivatives of the variables y and x, where Y (s) b0 + b1s + b2 s2 +... = X (s) a0 + a1s + a2 s2 +...

becomes (a0 + a1D + a2 D 2 +... ) ⋅ y (t ) = (b0 + b1D + b2 D 2 +... ) ⋅ x (t )

where D is the operator d/dt. To avoid having to calculate derivatives, we can integrate symbolically this equation with respect to time on both sides, as many times as required to eliminate all derivatives, each time using the bilinear transformation. This process USERS GUIDE TO MODELS IN ATP

35 produces an equation expressed in terms of the present and past values of y and x: y(t0) = f( x(t0), x(t1), x(t2), ..., y(t1), y(t2), ... ) where x(t0) = x(t), x(t1) = x(t-t), x(t2) = x(t-2t), .. or, using the z-domain notation, x(t0) = t, x(t1) = z-1 x, x(t2) = z-2 x, ... to produce an equivalent z-transform transfer function Y (z) B0 + B1z −1 + B2 z −2 +... = X (z) A0 + A1z −1 + A2 z −2 +...

The equation now shows a new set of coefficients, each a function of the original coefficients of the respective polynomials. To summarize, differential equations and Laplace transfer functions are converted to z-transform transfer functions. This is done in the solver by applying a numerical transformation to the coefficients of each polynomial. Instead of using values of derivatives, the equation is solved numerically by making simple references to as many past values of y and x as needed in each case. 2.5.2.2. Initialization Because of the transformation discussed above, we can initialize the solution of any of these equations without having to provide initial conditions for the derivatives of a differential equation or Laplace transfer function. It is sufficient to describe the value of the variable at past times before time zero, simply using a history expression f(t) written in function of time. The solver will continue the calculation from time zero onward just as if all the initial conditions on the derivatives had been provided. Some textbook examples of differential equations set t=0 at a time when the system is in a transient condition, not a steady-state condition, and need initial conditions on the derivatives in order to solve the equations analytically. This situation is not representative of typical simulations, where we start a simulation from a known simple state, and then let the transient behavior start only at or after the beginning of the simulation. In any case, even if one needs to start a simulation from a transient condition, it can be argued that if one has enough information to know analytically the initial conditions of all the derivatives, one certainly has enough information to also know the shape of the variables in the form of a history expression f(t). Let's look at an example where we have to find the time domain solution for the following differential equation using Laplace transforms (from Kuo): d2x/dt2 + 3 dx/dt + 2 x(t) = 5 u(t) with initial conditions USERS GUIDE TO MODELS IN ATP

36 x(0) = -1 dx/dt = 2 This problem is not a simulation problem. In a simulation situation, if we have enough information to know not only the instantaneous value of an output but also the instantaneous value of its derivative(s) at initial time t0, we also certainly have enough information to have a very good idea of the shape of that signal around time t0. That is what we can then provide to MODELS as history of the signal at time t0 in the form of a function f(t). To use this example in MODELS, we could go around the problem and provide the analytical form of the signal as history expression f(t). But then, if we know the analytical expression of y, we don't need a differential equation to simulate it, we can just use the analytical expression directly as y = f(t) MODELS is not meant to serve as a symbolic or analytical equation solver. It is a simulation solver. The solution of differential equations in MODELS is not based on the calculated values of the inner derivatives of the signals (the analytical approach), but instead uses the measured values of the signals at one or more past simulation times (the empirical approach, implemented using z-transforms). For doing mathematical exercises not requiring simulation, it may be more appropriate to use a symbolic or analytical mathematical solver. 2.5.2.3. Values of y at t0 At the first execution of a model-use (that is, at the initial time at which each instance of that model is called), the above equations don't need to be recalculated, because the value of the variable to which they apply is already defined by its history expression. The same reasoning applies to the value of the integrals. 2.5.2.4. Using CDIFFEQ, CLAPLACE, and CZFUN Using CDIFFEQ, CLAPLACE, or CZFUN, the coefficients of the polynomials are considered to be constant, and are evaluated only once at the start of the simulation of each instance of a model, instead of at every time step. The equation itself, of course, is evaluated at each time step, whether the coefficients are constant or variable. 2.5.2.5. Limits The only limit that can be applied directly to the value of a variable calculated using a differential equation and a Laplace or z transfer function, is a dynamic limit. This is because when a limit is reached, all the derivatives of that variable become zero, therefore changing the internal state of the "component" used to produce the output represented by that variable. If we need to apply a limit (minimum and/or maximum) which does not modify the internal state of the

USERS GUIDE TO MODELS IN ATP

37 represented component, we apply a static limit to that variable in a separate equation. For a Laplace function, for example, a dynamic minimum limit can be specified along with the equation: LAPLACE(y/x) {dmin: expr} := (...)/(...)

and a static limit, outside the Laplace equation: LAPLACE(y/x) := (...)/(...) z := y {min: expr}

An example of a component that reaches a limit is an op amp used with a resistor and a capacitor in the feedback branch. If the output of the component is clipped by a limiter placed past the component, the voltage across the capacitor in the feedback branch will show the same values as if there was no limiter. The external limit is a static limit as seen from the component. But if a Zener diode is placed in parallel with the feedback branch to limit the output voltage, the voltage across the capacitor will also be limited. This is a limit operating internally to the component, as it dynamically affects the internal operating behavior of the component. This is a dynamic limit. A mechanical example is the indicating arm of a meter reaching a stop peg at the upper end of the scale. If the arm is mounted on a spiral spring, the spring will compress while the driving torque attempts to push the arm past its allowed range. When the torque decreases, the spring needs to unwind to its resting position before the arm will start moving away from the peg. This is a static limit, also called "windup" limit, for the spring winding up. If instead the arm is mounted on a slip bushing, when the torque attempts to push the arm past its maximum position, the arm will simply slip on its shaft, ready to come off the peg as soon as the torque starts decreasing, without any unwinding delay. This is a dynamic limit, also called "no windup". This is shown in the figure below, comparing the effect of a static and a dynamic limiter on a the output value of a simple integrator:

USERS GUIDE TO MODELS IN ATP

38

2.5.3. Integral value assignment At any time t0 of a simulation, the time integral is defined as: t0

∫ x ⋅ dt −∞

the integral of x with respect to time, from -infinity to the present time. This can be decomposed, using t1 = t0 - t, as: t0

t1

∫ x ⋅ dt =

∫ x ⋅ dt + ∫ x ⋅ dt

−∞

−∞

t0 t1

or I (x, t 0 ) = I (x, t1) + ∆I (x, t1 → t 0 )

The running value of an integral is calculated during a simulation by using the value of the integral at the previous time, and adding to it the value of the incremental integral over the past step. This increment, in MODELS, is calculated using the trapezoidal approximation, as the average of x(t1) and x(t0), multiplied by the time interval t0-t1: ∆I =

x(t1) + x(t 0 ) ⋅ (t 0 − t1) 2

However, it is possible to bypass this process and assign a value to the integral directly, in effect resetting the value of the integral, to zero or some other value, by using an integral value assignment of the form: integral(x) := expression

This new value becomes the starting point to which the next incremental integral will be added at the next time step. One detail to notice is the following. At a given simulation time inside the EXEC of a model, we may assign a value to x, then use the value of its time integral (which will use the present value of x to calculate the integral increment). Then further on in the EXEC at the same time step, we may assign a different value to x, then again use the value of the integral (which will use the new x to recalculate its increment), and so on. But from the point in the EXEC where a value is directly assigned to the integral, the value of the integral is not dependent on the present value of x anymore for the rest of that EXEC at that simulation time. No matter how often one changes the value of x after the reset inside the same time step, any reference to the value of the integral will always return the same value, the reset value that was assigned directly to the integral by the integral value assignment. 2.5.4. History expression assignment To associate a history expression with a variable in the INIT procedure, we use a history expression assignment:

USERS GUIDE TO MODELS IN ATP

39 histdef(y) := expression written as a function of the variable "t"

This is the third form of history assignment, as discussed in the section on the INIT procedure. The expression can itself make reference to the history expression associated with other variables. For example, to make the history expression of y dependent on the history expression associated with another variable x, we can use the histdef() function in the expression: histdef(y) := 2 * histdef(x)

Notice the difference between the equation above, and the following: histdef(y) := 2 * x

which would not achieve the intended purpose, but instead only use the most recent value of x whenever the history expression of y needs to be evaluated. 2.5.5. IF statement IF statements are used for grouping statements that are executed only when certain conditions are met. 2.5.5.1. Explicit IF statement The simple form of the IF statement consists of a single conditional clause: IF condition_is_true THEN statement list ENDIF

Multiple clauses can be chained inside the same IF statement. Only the first clause found with a true condition is executed: IF condition_is_true THEN statement list ELSIF another_condition_is_true THEN another statement list ELSIF ... ... ENDIF

A default clause, the ELSE clause, can also be defined. It is executed only when no other clause of the IF statement is found with a true condition:

USERS GUIDE TO MODELS IN ATP

40 IF condition_is_true THEN statement list ELSIF another_condition_is_true THEN another statement list ... ELSE another statement list ENDIF

An IF statement can be enclosed inside another IF statement, in any of its clauses: IF condition_is_true THEN statement 1 statement 2 IF condition THEN another statement list ... ENDIF ... ENDIF

There is no "CASE" statement in MODELS at this time, although it may be added later. A case statement can be described using an IF statement with multiple clauses, as shown in the following example: MODEL if_example -- illustrates the IF structure in MODELS VAR k INIT k:=0 ENDINIT EXEC IF k=0 THEN k:=1 ELSIF k=1 THEN write("In first 'elsif' with k=1") k:=2 ELSIF k=2 THEN write("In second 'elsif' with k=2") k:=3 ELSE write("In 'else' with k=3") ENDIF ENDEXEC ENDMODEL

2.5.5.2. Implicit IF statement When we need to determine the value taken by a variable under a variety of conditions, we can use an explicit IF statement, for example:

USERS GUIDE TO MODELS IN ATP

41 IF onswa=2 THEN IF ia

true if left greater than right

>=

true if left greater than or equal to right


1 THEN x:= -1 ENDIF y:= x dlim :=integral(x) {dmax: 0.7} nolim :=integral(y) slim :=nolim {max:0.7} ENDEXEC ENDMODEL

The values of the variables x, nolim, slim, and dlim are shown in the following figure:

USERS GUIDE TO MODELS IN ATP

64

USERS GUIDE TO MODELS IN ATP

65

4. SPECIFYING SIMULATION DIRECTIVES The simulation directives affecting the operation of a model are: - the constraints placed on the size of the time step used by the model - the interpolation method to be used on the external input values at intermediate internal time steps - the number of delay cells to be reserved for storing the past values of variables and inputs affected by the delay() function - and the history expressions describing analytically the value of some of the inputs and variables of the model prior to its simulation. It is possible to specify default characteristics for these directives in each model description. This is what is covered in this section. It is also possible to specify or modify simulation directives in the USE statement of individual instances of a model. That is covered in the section on "Using a model".

4.1. Specifying the time step range It is possible to define local limits, minimum and maximum, local time step to be used for the step-by-step solution implications of updating a model at a smaller or larger time used outside the model, are discussed in the section on variables", in Appendix C.

on the size of the of a model. The step than the one "Pre-defined local

When a model is called from outside for updating its internal state to a new simulation time, the interval of time since the last call for update determines the step that the model could take to carry on its operation. But this outside step may not be properly scaled to the fineness of representation needed to follow the internal dynamic operation of the model, being either too large or too small. By specifying a minimum and/or a maximum limit on the size of the time step, we can maintain it within an appropriate range. If the outside time step is too large for the model, that is, larger than the specified maximum, the model will subdivide the outside step into finer internal steps. If the outside time step is too small for the model, that is, smaller than the specified minimum, the model will ignore the request for update, which would provide no significant change in the state of the model. The expressions used for describing these limits can make reference to the value of any variable in the model, providing the possibility to dynamically adjust these limits, and consequently the size of the time step, to changing conditions monitored in the operation of the model.

USERS GUIDE TO MODELS IN ATP

66 Typically, the size of the time step would be maintained between 1/100 and 1/10 times the size of the smallest time constant of the model. A finer step would be a waste of execution time. A larger step would affect accuracy. TIMESTEP MAX: 0.1 * min(tau1, tau2, tau3) TIMESTEP MIN: 0.01 * min(tau1, tau2, tau3)

4.2. Specifying the input interpolation method When the time step size is limited to a maximum value, and the outside step exceeds that value, the model will select a local time step that is a sub-multiple of the outer time step, and that fits inside the allowed limit. But when this happens, we don't have values for the external inputs to the model at those intermediate time steps. We use the input interpolation directive to specify what method of interpolation will be used for estimating the value of the inputs at the sub-steps. The directives are flexible. We can select different methods for different inputs. A default method can also be specified. Also, the method specified in the model definition can be modified later in the USE statement of individual instances of the model. The degree of the fitting polynomial can be specified as 0, 1, or 2, for step, linear, and quadratic interpolation, respectively. When not specified, linear interpolation is used. Step interpolation is no interpolation, that is, for all times ti between t-¡Error! Marcador no definido.t and t0, y(ti) keeps the value y(t- t). Linear interpolation uses a straight line between the values y(t- t) and y(t). Quadratic interpolation uses the values y(t-2t), y(t-t), and y(t) to fit a parabola used for finding the values of y(ti) between t-t and t. The following notation is used: INTERPOLATION DEGREE DFLT: 0 DEGREE(y1, y2): 1 DEGREE(y3): 2

and the INTERPOLATION keyword can also be repeated: INTERPOLATION DEGREE DFLT: 0 INTERPOLATION DEGREE(y1, y2): 1 INTERPOLATION DEGREE(y3): 2

USERS GUIDE TO MODELS IN ATP

67

4.3. Specifying the size of the delay storage Many functions of MODELS require past values of a variable for calculating the value of the function, for example, derivatives and integrals. The storage needed for recording these past values is taken care of automatically by the solver. This can be easily determined by the solver, because the storage window is never much longer than two or three cells back depending on the level of interpolation needed. Such is not the case for the delay() function. The size of the storage needed for recording the past values of a variable to be accessed by a delay() function depends on what size of delay will be used, and on the size of the time step at which the samples are recorded. For example, a delay value of 500 ms, in a simulation using a time step of 1 ms, would require 500 cells of storage for that variable. And this estimation is not necessarily so simple, considering that both the size of the delay used and the size of the time step can be described in the form of symbolic expressions, the value of which may vary dynamically during a simulation. Choosing to store all past values in order to avoid having to specify any storage dimensions is not a practical alternative either. This has been tried in earlier versions of MODELS, for use with the function pastval(). The storage needs can be considerable, and require paging from memory to external storage, a process that consumes more execution time, especially when considering the fact that most of those past values are never used. The present approach is to provide a simulation directive, in the model definition and/or in the USE statement, indicating how many cells must be reserved for storing a moving window of past values for each variable accessed by a delay() function. Typically, the expression specifying the number of cells will include a reference to the size of the time step used in the model. It must be understood, however, that this expression is evaluated only once when each instance of the model is created, and that the size cannot be adjusted later. A reference to the variable timestep would be using the value of that variable at the time when it is used, that is, at the time when the instance of the model is created and initialized. As a footnote, specifying the number of cells is also the approach that was used in TACS, although in a different form. For each delay device (type 53), we have to specify the maximum delay time for which the device will be used. Specifying the maximum time delay in MODELS would not suffice, because the timestep can also vary. The following notation is used: DELAY CELLS DFLT: max(delay1, delay2)/timestep +1 CELLS(y1, y2): 50 CELLS(y3): 10

USERS GUIDE TO MODELS IN ATP

68 and the DELAY keyword can also be repeated. When a default value is not specified, a default value of 100 cells will be used.

4.4. Specifying history expressions To summarize what has been discussed in other sections, two types of references to the history expression of a variable or input are possible. One is hidden and is made internally by the solver whenever it needs to access a nonexisting past value from a time t preceding the simulation of the model, for example when needing a delay value from a time before the simulation was started, or when needing pre-simulation values for the first few evaluations of a laplace(), diffeq(), deriv(), etc. The other type of reference is one that can be written explicitly in the model description in any expression. Two functions are available for this. One is histval(y,t1) which will use the history expression of variable y to evaluate y(t1). The other is histdef(y), which is equivalent to writing histval(y,t) for the generic value of time t. To understand the need to specify history functions, consider, for example, using a delay function which would make reference to the past value of a variable for a time preceding the time of the first execution of that model instance, as in y := delay(x, delaysize)

which corresponds to asking for the value of x at time t-delaysize. If t-delaysize >= t0, then the value of x at that time has been stored in the delay storage cells of the model. But ift-delaysize < t0, then that value is undefined unless the model has access to an analytical expression describing how to calculate the value of x at times t=1.5e8*t +1e5 THEN grid:=1 ELSE grid:=0 ENDIF ENDEXEC ENDMODEL USE dc30 AS dc30 INPUT dv:=deltav OUTPUT grid:=grid ENDUSE RECORD dc30.dv AS dv ENDMODELS C ============================================================================== GEN BUS1 15. BUS1 2.9 BUS1 BUS2 0.1 BUS2 0.1 BUS3 .017 BUS3 490. BUS2 BUS2R 24.34 BUS3 BUS3R BUS2 BUS2R BLANK card terminates electric network branches BUS2 BUS3 -1. 1.E9 NAME: Valve ! { Request "NAME: " of cols. 3-8 precedes A6 valve name in 914

USERS GUIDE TO MODELS IN ATP

81 11BUS2R BUS3R 20. 12 BLANK card ends all switches 14GEN 66500. 50. -2.0508 BLANK card terminates electric network sources { No node voltages printout/plotting BLANK card ending node voltage request BLANK card ending plot cards BEGIN NEW DATA CASE BLANK

GRID

-1.

6.1.1.4. Inputs from ATP program variables Any numerical non-array variables from the ATP program that are accessible to ATP's SPY can also be used as inputs to MODELS. A local name can be specified, along with an indication of the name of the ATP program variable used as input: INPUT atp_t { ATP(t) } tmax { ATP(tmax) }

-- value of ATP variable 't' -- value of ATP variable 'tmax'

Another way to have access to internal variable values of the ATP program is to use the special function atp() in an expression inside a model description. This provides the added advantage of being able to also access elements or array variables used in the ATP program, which is not possible in the INPUT declarations of the MODELS section. MODEL example ... EXEC ... step := atp(istep) estimated_voltage := atp(voltk[2*index]) 'voltk' ...

-- value of ATP variable 'istep' -- value of element of array

ENDEXEC ENDMODEL

It is also possible to modify the value of internal program variables of ATP, by using the special procedure deposit(). This is discussed in the following section on Outputs to ATP. Following is an example combining illustrations of the atp() input that can be used in the MODELS section, of the special function atp() that can be used in a model, and of the procedure deposit() that can also be used in a model. BEGIN NEW DATA CASE } C deltat tmax xopt 0.001 0.005 C print points connec 1 1 0

{ ATPVAR.DAT copt

epsiln

tolmat

tstart

s-s 0

minmax 0

vary 0

again 0

plot 0

USERS GUIDE TO MODELS IN ATP

82 C ============================================================================== MODELS INPUT atp_t {atp(t)} tmax {atp(tmax)} MODEL atpvar VAR step EXEC write('*** e(2) = ', atp(e[2])) write(' e(3) = ', atp(e[3])) step := atp(istep) IF step=4 THEN deposit(tmax, 0.0095) ENDIF ENDEXEC ENDMODEL

-- get value of ATP variable 't' -- get value of ATP variable 'tmax'

-- write value of ATP variable e(2) -- write value of ATP variable e(3) -- get value of ATP variable 'istep' -- modify value of

ATP variable 'tmax'

USE atpvar AS example ENDUSE RECORD atp_t AS t example.step AS istep tmax AS tmax ENDMODELS C ============================================================================== A1 A2 1. A2 1. BLANK card ending electric network branches BLANK card ending switches 14A1 100. 50. -1. BLANK card ending electric network source cards BLANK card ending voltage printout requests BLANK card ending plot requests BEGIN NEW DATA CASE BLANK

6.1.2. Outputs to ATP Any variable declared as output in the MODELS section becomes visible in the circuit, and can be used as control variable to the components of the circuit, everywhere a TACS variable can be used. Applications include controlling the operation of switches, controlling the value of a type-91 resistance and other nonlinear components, controlling the value of voltage and control sources, and controlling the value of internal variables in the machine components The output names are declared using the following notation: OUTPUT name1 name2 ...

-- comment describing the value -- comment describing the value

The names of these outputs are stored and used by ATP, and are therefore limited to the 6-character naming convention of ATP. Also, no arrays can be used, only single outputs. USERS GUIDE TO MODELS IN ATP

83 There is a difference between declaring a MODELS variable as output to the circuit, and specifying a variable to be recorded for printout and plotting during the simulation. The latter is done using a RECORD directive, discussed in a separate section below. Variables declared as outputs of the MODELS section are not automatically recorded for printout or plotting, unless they are also included in the RECORD directives of the MODELS section. No modifications have been made to the format rules of ATP branches, switches, sources, and machines regarding the use of control variables from TACS or MODELS. In either case, the keyword TACS used on these cards indicates control variables coming from a "control system" described outside the circuit, using either TACS or MODELS, without distinguishing between the two. Another type of output to ATP can be made directly from inside a model. The deposit() procedure allows a model to modify the value of any numerical program variable of ATP that can be changed using ATP's SPY command DEPOSIT. The ATP documentation of the SPY commands describes what variables can be modified. Thedeposit() procedure can be used to modify the value of single variables and of single or multiple elements of array variables of the ATP program, using the following notation: DEPOSIT( name, value ) DEPOSIT( name[ expr ] , value ) DEPOSIT( name[ expr .. expr ] , value ) where name is the name of a program variable accessible from SPY, and where the index of the array elements can be specified using regular expressions. An illustration is included in the example used in the previous section. 6.1.3. Variables in the MODELS section In addition to the input and output variables that can be declared in the MODELS section, it is possible to define internal variables that can be used for passing values between the models used in the MODELS section. They are named and declared as variables using the following notation: VAR name1 name2 ...

-- comment describing the variable -- comment describing the variable

The names of these variables are stored and used by ATP, and are therefore limited to the 6-character naming convention of ATP. Also, no array variables can be used, only single variables. Values are assigned to these variables in the USE statements of the MODELS section, on the left-hand side of the output assignments, receiving values from the outputs of the used models. Note that the outputs of the MODELS section can also be used for the same purpose as the variables.

USERS GUIDE TO MODELS IN ATP

84

6.1.4. RECORD for printout/plotting Any value-holding element existing in MODELS can be added to the printout/plotting list of ATP, by using a RECORD directive. Each RECORD identifies an element by specifying its path-name in MODELS, and by specifying a 1- to 6-character label to be used by ATP in the printout heading, for example: RECORD controller_A.control AS ctrl RECORD top.subuse.field AS field1 RECORD source1 AS src1 RECORD SRCE__CT1___LIMR__.r AS rs

The first example adds to the printout list, identified in the list as "MODELS CTRL", the value of an element named control, from a model used at the top level of the MODELS section with the instance name controller_A. The second example adds to the printout list, identified as "MODELS - FIELD1", the variable field from a model used as subuse in a model with instance name top. The third example adds to the printout list, idendified as "MODELS - SRC1", the element named source1 defined as a variable or input or output of the MODELS section. Note that no instance name is needed in the path, because the element source1 exists at the top level of the MODELS section, outside of any model instance. The fourth example adds to the printout list, with the label "MODELS - RS", the element named r from the model named limr used by a type-94 component connected to the circuit between nodes SRCE and CT1. Non-existing instance names found in a record path don't trigger an error, because an instance name starts its existence only at the instant of the simulation when the associated instance of the model is first used, which is not necessarily at the initial time of the simulation. It is therefore not an error for the program to not find a given instance name, as it may simply not have been yet created in the simulation. The only way to provide a clear indication that the record has an undefined value would be to be able to assign it the value "undefined", something like minus zero. And of course we cannot use the undefined value from MODELS (=88888.88888) because it would affect the scale limits of a plot if we used that value until the time an actual value starts being assigned to the variable. 6.1.5. Model descriptions All models used in a simulation must be described in the MODELS section of a data case. This includes models used from a USE statement in the MODELS section, as well as models used from a type-94 circuit component.

USERS GUIDE TO MODELS IN ATP

85 The $INCLUDE command of ATP can also be used to refer to a file containing a model description, instead of including the full text of the model in the data case. The example illustrating variables of the MODELS section, above, could be rewritten in a more simple way using an $INCLUDE command: MODELS INPUT atp_t {atp(t)} tmax {atp(tmax)} $INCLUDE atpvar.m

-- get value of ATP variable 't' -- get value of ATP variable 'tmax'

{ insert file containing the model 'atpvar'

USE atpvar AS example ENDUSE RECORD atp_t AS t example.step AS istep tmax AS tmax ENDMODELS

Just as foreign models can be declared inside a model (see Foreign submodels), they can also be declared at the top level of the MODELS section. The notation is identical to when a foreign model is declared inside a regular model. Here is an example: BEGIN NEW DATA CASE C deltat tmax xopt copt epsiln tolmat tstart 1. 10. C print points connec s-s minmax vary again plot 1 1 0 0 0 0 0 0 C ============================================================================== MODELS STAND ALONE VAR a1, a2, a3 MODEL ftnmodel FOREIGN sample_model {ixdata:1, ixin:3, ixout:3, ixvar:3} USE ftnmodel AS example DATA xdata[1]:=3 -- set value of xdata[1] INPUT xin[1..3]:=[t, t+1, t+2] -- load inputs xin[1], xin[2], xin[3] HISTORY xvar[1..3]:=0 -- set history of xvar[..] OUTPUT a1:=xout[1], a2:=xout[2], a3:=xout[3] ENDUSE RECORD example.xdata[1] AS xdata1 example.xin[1] AS xin1 example.xvar[1] AS xvar1 -- its value after each execution a1 AS xout1 ENDMODELS C ============================================================================== BLANK card ending plot requests BEGIN NEW DATA CASE BLANK

In this example, three variables are defined, a1, a2, a3. The foreign model is declared. One instance of that model is used, identified with the instance name USERS GUIDE TO MODELS IN ATP

86 example. Various values are then recorded during the simulation in the printout/plotting list of ATP. To use our own Fortran or C code with ATP, we must link our program with ATP. The details of this process are dependent on the platform on which we are running ATP. Typically, we must use the same compiler that the rest of our version of ATP was compiled on. Then we have to link our compiled file with the compiled files of ATP using a linker compatible with the compiler(s) that we have used. For example, for the Salford version of ATP, we can use the Salford Fortran, C, or Pascal compilers for our routines, and the Salford linker. It also means that we need all the compiled files of ATP in order to be able to relink them with the additional files that we create. 6.1.6. MODELS formatting vs. ATP formatting MODELS has syntax rules separate from the formatting rules of ATP. Among other things, it allows the insertion of white space (space characters, tabs, carriage returns, blank lines) anywhere in the text of a model and in the MODELS section of a data case. There is no need to start blank lines in the MODELS section with the C-in-column-one format used for indicating comment lines in the rest of ATP. Even if the "C "-formatted ATP comments can be used in the MODELS section without producing a syntax error, their use is not encouraged for two reasons. One is simply style, as they really don't belong to the MODELS language. The other reason is that a model written with this type of comment lines would not be compatible with other versions of MODELS used outside of ATP.

6.2. Using a model in the MODELS section When we access a model with a USE statement in the MODELS section, the model instance that we create interacts with the circuit as a control component. This is to be compared to the circuit approach available when using a model with the type-94 circuit element (see a separate section below). The control-type component receives measurements from the circuit (the inputs), and sends back control signals (the outputs) to be used in the circuit. In this mode, ATP performs no iteration. The control signals are simply applied to the operation of the circuit at the next time step of the simulation. This is the mode of operation that was also available between the circuit and TACS. When used for representing true control components, this decoupling, and its one-step delay, are not a limitation, as any physical control component will include transmission delays in its operation. This approach can also be used without problem for representing passive circuit elements in the form of a Norton equivalent, where the value of the equivalent current source, if present, is calculated using values of voltages and currents already delayed by one or more USERS GUIDE TO MODELS IN ATP

87 time steps (see the representation of inductance, capacitance, and transmission lines in ATP). This forced decoupling will create numerical stability problems when used for representing circuit components that should be solved simultaneously with the rest of the circuit. This includes any component for which a Norton equivalent would use concurrent (as opposed to delayed) values of voltages or currents to calculate the value of the equivalent source (for example, any type of voltage- or current-driven voltage source or current source). In this case, it is necessary to use a type-94 Thevenin or iterated circuit element to connect the model representing the operation of the component. The USE statement available in the MODELS section lets us use all features of the USE statement available inside a regular model (see the section on the Use statement). This includes assigning data and input values, retrieving output values, and specifying history expressions, range of time step, input interpolation methods, and delay cells storage size. Here is an example where models are used from USE statements in the MODELS section. The complete data case represents a circuit that uses three models to describe the operation of a variable source, a variable current-limiting resistance, and a variable load.

Here is the corresponding data case: BEGIN NEW DATA CASE { LIMR-USE.DAT } C deltat tmax xopt copt epsiln tolmat tstart 5.E-5 0.16 C print points connec s-s minmax vary again plot 100 1 0 0 0 0 0 1 C ============================================================================== MODELS INPUT vmeas {v(CT1)} -- load voltage measured at node CT1 OUTPUT srce -- source driving voltage rs -- limiting resistance rl -- load resistance

USERS GUIDE TO MODELS IN ATP

88

$INCLUDE vs.m { inserts model source_voltage $INCLUDE limr-use.m { inserts model limr $INCLUDE resist.m { inserts model variable_resistance USE source_voltage AS source DATA vrms := 100 -- [ V ] freq := 60 -- [ Hz] OUTPUT srce := vs -- [ V ] ENDUSE USE limr AS rs DATA rsmin := 1.0 -- [ohm] ilim := 20 -- [ A ] INPUT v := srce - vmeas OUTPUT rs := r ENDUSE USE variable_resistance AS res OUTPUT rl := r -- [ohm] ENDUSE

source rms voltage source frequency source driving voltage

source min resistance source max current

load resistance control

RECORD rl AS rl rs.r AS rs ENDMODELS C ============================================================================== 91SRCE CT1 TACS RS { Variable limiting resistance CT2 LOAD 0.1 0.2 { Fixed load R-L 91LOAD TACS RL { Variable load resistance BLANK card ending branches ---------------------------------------------------CT1 CT2 MEASURING 1 BLANK card ending switches ---------------------------------------------------60SRCE { Source driving voltage BLANK card ending sources ----------------------------------------------------SRCE CT1 BLANK card ending voltage printout request -----------------------------------BLANK card ending plot -------------------------------------------------------BEGIN NEW DATA CASE BLANK

The included file LIMR-USE.M contains the description of the limiting resistance model, as follows: MODEL limr -- limiting resistance DATA rsmin -- [ohm] min resistance ilim -- [ A ] max current INPUT v -- [ V ] voltage across terminals VAR r -- [ohm] resistance OUTPUT r EXEC r := abs(v)/ilim {min: rsmin} ENDEXEC ENDMODEL

USERS GUIDE TO MODELS IN ATP

89 The operation of that model is described in its one-line EXEC procedure, where the resistance is first calculated to create a current equal to ilim, and is then limited to be no less than the value specified by rsmin. For comparison, a version of this circuit is shown using a type-94 component, in the section below.

6.3. Using a model with the type-94 component In ATP, the type-94 nonlinear component is a user-defined multi-branch circuit component. The operation of the component is completely described by the user in a model, placed in the MODELS section of the data case, and used not by a USE statement, but by a type-94 component in the circuit. This model can be written as a native model using the MODELS language, or it can call a foreign model using other programming languages. The type-94 component can be used in three different modes: Thevenin, iterated, and Norton. In each case, the interface with the circuit is a true electrical connection defined in terms of the voltages and currents of the data case. Each one can be used for representing multi-branch nonlinear circuit elements, with or without associated controls. The solution of the Thevenin and the iterated modes is simultaneous with the solution of the rest of the circuit, without any time delay. The solution of the Norton uses the control-type approach, with a one-step delay. The following example is the same data case as shown in the previous section, except that the limiting resistance model is used as a circuit component (type-94) instead of being used as a control component called from a USE statement. BEGIN NEW DATA CASE { LIMR-94.DAT } C deltat tmax xopt copt epsiln tolmat tstart 5.E-5 0.16 C print points connec s-s minmax vary again plot 100 1 0 0 0 0 0 1 C ============================================================================== MODELS OUTPUT srce -- source driving voltage rl -- load resistance $INCLUDE vs.m { inserts model source_voltage $INCLUDE limr-94.m { inserts type-94 model limr $INCLUDE resist.m { inserts model variable_resistance USE source_voltage AS source DATA vrms := 100 -- [ V ] freq := 60 -- [ Hz] OUTPUT srce := vs -- [ V ] ENDUSE

source rms voltage source frequency source driving voltage

USE variable_resistance AS res

USERS GUIDE TO MODELS IN ATP

90 OUTPUT rl := r ENDUSE

-- [ohm]

load resistance control

RECORD rl AS rl SRCE__CT1___LIMR__.r AS rs ENDMODELS C ============================= Electrical circuit ============================= 94SRCE CT1 LIMR ITER { Variable limiting resistance >DATA RSMIN 1. >DATA ILIM 20. >END CT2 LOAD 0.1 0.2 { Fixed load R-L 91LOAD TACS RL { Variable load resistance BLANK card ending branches ---------------------------------------------------CT1 CT2 MEASURING 1 BLANK card ending switches ---------------------------------------------------60SRCE { Source driving voltage BLANK card ending sources ----------------------------------------------------SRCE CT1 BLANK card ending voltage printout request -----------------------------------BLANK card ending plot -------------------------------------------------------BEGIN NEW DATA CASE BLANK

The included file LIMR-94.M contains the description of the limiting resistance model, as follows: MODEL limr -- limiting resistance -- Fixed declarations for a type-94 iterated model --------------------------DATA n -- number of node pairs n2 {dflt: n*n} -- number of matrix elements INPUT v -- guessed voltage across terminals 1-2 v0 -- steady-state voltage across terminals 1-2 i0 -- steady-state current into terminal 1 VAR i -- calculated current into terminal 1 didv -- calculated conductance 1-2 OUTPUT i, didv -- Local declarations -------------------------------------------------------DATA rsmin -- [ohm] min resistance ilim -- [ A ] max current VAR r -- [ohm] resistance EXEC r := abs(v)/ilim {min: rsmin} IF r>rsmin -- if the current is at the limit THEN didv := 0 ELSE didv := 1/r ENDIF i := v/r ENDEXEC ENDMODEL

USERS GUIDE TO MODELS IN ATP

91

6.3.1. Thevenin, iterated, and Norton What follows is a comparison between the three different modes of the type-94 circuit component: Thevenin type-94 input

Thevenin voltage source behind Thevenin equivalent resistance or admittance of the network seen from the component; if multi-branch, Thevenin source is a vector, Thevenin resistance is a matrix;

output

value of branch current from the component; if multibranch, current is a vector;

implementation uses the compensation interface of ATP usage

restricted to one nonlinear component per subnetwork

solution assurance

numerical solution is assured (no iteration between ATP and the type-94 component)

speed

faster than iterated, because no iteration is needed; slower than Norton, because a Thevenin equivalent must be calculated

Iterated type-94 input

most-recent branch voltage value calculated by ATP; if multi-branch, uses a vector of voltages;

output

branch current and branch di/dv calculated by the model; if multi-branch, current is a vector, [ i/v] is a matrix;

implementation uses the iteration mechanism of ATP usage

no restriction on how many are used

solution assurance

the ATP iterated solution is not guaranteed to converge (especially if any of the iterated components are allowed to have oscillating step discontinuities in their operating point during an iteration - but this could be restricted by the model's logic)

speed

possibly slower overall execution than Thevenin if many iterations are required at each time step due either to the interaction between many iterated nonlinear components, or to discontinuities in any of the nonlinear components; may be possible to use larger step size to compensate;

Norton type-94 non-transmission

USERS GUIDE TO MODELS IN ATP

92 input

left node voltage at time t; vector if multi-node; right node is not used;

output

Norton equivalent of the component, as seen from the electrical circuit, in the form of a current source in parallel with the equivalent admittance of the component; if multinode, current source is a vector, admittance is a matrix; values of current source and admittance are predicted for next time step

implementation - is not treated as a nonlinear element by ATP - is similar to presently using a combination of a type-60 controlled current source in parallel with a type-51 controlled resistance, except that it is extended to a matrix form; - the solution of this component is not simultaneous with that of the circuit (a delay of one time step is introduced between input and output) usage

- where the operating point of the component can be easily predicted with sufficient accuracy from one time step to the next (for example when the operating point of the component changes more slowly than the operating point of the rest of the circuit) - where the exact timing of the operating point of the component is not critical to the operation of the rest of the circuit (for example when representing something with an element of randomness, like the state of an arc) - where the component is not a current-controlled or voltage-controlled voltage source or current source that would need to be solved simultaneously with the circuit

solution assurance

the ATP solution is always assured (the equivalent circuit of the component is linear); numerical instability can be expected when the represented element is not a passive circuit element;

speed

faster execution than both Thevenin and iterated, because the component is represented directly in the nodal admittance matrix of the circuit (it's not treated as an exception to the circuit); slower execution when admittance varies often during the simulation, requiring a retriangularization of the full admittance matrix of the ATP circuit at each change

Norton type-94 with transmission

USERS GUIDE TO MODELS IN ATP

93 input

left node voltage and right node voltage at time t; vectors if multi-node; the two sides are decoupled by the component; the component represents a transmission element (cable or line);

output

two Norton equivalents of the component, as seen from the electrical circuit on each side, in the form of a current source in parallel with the equivalent admittance of the component; if multi-node, current source is a vector, admittance is a matrix; values of current source and admittance are predicted for next time step

implementation same as for the non-transmission type; allows to separate each side into a different subnetwork, just like a regular transmission line component usage

used where the component operates as a transmission device;

6.3.2. Initializing the type-94 component The type-94 component is not included in the steady-state initialization of the ATP circuit at t=0. As for other nonlinear elements used in a circuit, a temporary equivalent linear circuit can be used for representing the component in the steady-state circuit solution. This provides us with representative values of voltages and currents at the component, values that we can use to initialize the operating point of the corresponding model when it is first called for execution. In the case of the Thevenin and the iterated types, the model is not called until the circuit solution is already under way at the first time step of the simulation. The pre-defined inputs v0[1..n] and i0[1..n] carry the values of voltages and currents measured at the end of the steady-state solution, which can be used to initialize the model. In the case of the Norton type, the model is called for the first time at time t=0 immediately after the steady-state solution, but before the circuit solution at the first time step. This gives us a chance to initialize not only the model, but also the values of the Norton equivalent that will be used in the circuit at the next time step, which in this case will be the first time step. Here again, the pre-defined inputs v0[1..n] and i0[1..n] carry the values of voltages and currents measured at the end of the steady-state solution, and can be used in a special section of the EXEC procedure, executed only at time t=0, to properly operate the model. To illustrate this last point, compare below the INIT and EXEC procedures of a simple model representing a constant inductance, built first as a type-94 Thevenin, and next at a type-94 Norton. Notice where the steady-state measured values of v0 and i0 are used:

USERS GUIDE TO MODELS IN ATP

94 Thevenin: INIT L := L1 -- initialize variable inductance value histdef(v) := v0 histdef(i) := i0 ENDINIT EXEC COMBINE AS group1 CLAPLACE(i/v) := (1|s0)/(L|s1) v := sum(vth| -rth|i) ENDCOMBINE ENDEXEC

-- i/v=1/sL -- sum(a0| +a1|x1)

Norton: INIT st:= 2/timestep L := L1 g := 1/(st*L) ENDINIT

-- trapezoidal rule conversion from Laplace -- initialize variable inductance value -- conductance converted from Laplace 1/sL

EXEC IF t=0 THEN flag := 1 -- conductance values have been changed i := i0 -- t=0 current through L is := -i0 -g*v0 -- history term for next step ELSE flag := 0 -- reset flag, no more change in g i := g*v -is -- applying trapezoidal rule, calculate from v(t) is := -i -g*v -- history term from trapezoidal rule, for next step ENDIF ENDEXEC

6.3.3. Foreign models with a type-94 The type-94 component automatically calls the specified model at each time step of the simulation. That model describes how the component operates during the simulation. This operation can be described locally in the model itself, or can be programmed in a foreign model called by that model. This provides a way to represent the operation of a circuit component in ATP using a set of subroutines or procedures written as a separate program. They can be written in any programming language that can be linked with ATP on the used platform. The foreign programs are connected to ATP using the simple foreign interface of MODELS, in terms of data, input, output, and initial conditions. (See the section on Foreign submodels).

USERS GUIDE TO MODELS IN ATP

95

6.4. Using MODELS with ATP's FREQUENCY SCAN It is possible to include a MODELS section to be used with the FREQUENCY SCAN operation of ATP. At each frequency step, the value of the frequency is passed to MODELS, carried using the variable t. This may seem odd at first look, until one considers that this trick provides built-in access to derivatives and integrals of values with respect to frequency, instead of with respect to time. This is illustrated in the example below. For instance: - timestep holds the step in frequency between the previous frequency (now prevtime) and the present frequency (now t); - deriv(y) calculates the derivative of y with respect to frequency - integral(y) calculates the integral of y with respect to frequency - prevval(y) returns the value of y at the previous frequency step - predval(y, f1) returns the predicted value of y at frequency f1 - diffeq(a0|D0 +a1|D1 +...) | y := x calculates the value of y from a differential equation expressed in terms of the frequency, i.e. a0*y + a1*(dy/df) + a2*(d2y/df2) + ... = x - laplace(y/x) doesn't make any sense in this context BEGIN NEW DATA CASE C BENCHMARK DC-52 with addition of a model and its use FREQUENCY SCAN, 1.0, 0.0, 15., 2, 1.0 0.0 1 1 1 1 { Note request for phasor branch flows C ============================================================================== MODELS INPUT v_Re_swit v_Im_swit v_Re_load v_Im_load i_Re_swit i_Im_swit state_swit

{v(swit)} {imssv(swit)} {v(load)} {imssv(load)} {i(swit)} {imssi(swit)} {switch(swit)}

--------

real part of voltage imag part of voltage real part of voltage imag part of voltage real part of current imag part of current state of switch SWIT

at node SWIT at node SWIT at node LOAD at node LOAD at switch SWIT at switch SWIT (0=open, 1=closed)

MODEL m1 ---------------------------------------------------------------------VAR pass INPUT v_Re_1 v_Im_1 v_Re_2 v_Im_2 i_Re_1 i_Im_1

-- to verify that its value is kept between passes {dflt: {dflt: {dflt: {dflt: {dflt: {dflt:

0} 0} 0} 0} 0} 0}

-- to verify that all types of inputs are -accessed correctly -(machine quantities are not tested here)

USERS GUIDE TO MODELS IN ATP

96 state_1 {dflt: 0} INIT

pass:=0

ENDINIT

EXEC pass:=pass+1 write('************** In models, pass= ', pass) write(' freq= ', t) write(' Re{v1}, Im{v1} = ', v_Re_1, ', ', v_Im_1 write(' Re{v2}, Im{v2} = ', v_Re_2, ', ', v_Im_2 write(' Re{i1}, Im{i1} = ', i_Re_1, ', ', i_Im_1 write(' state_1 = ', state_1 ) ENDEXEC ENDMODEL

-) ) )

maxstep timestep