Principles of Object-Oriented Modeling and Simulation with Modelica 2.1
IEEE Press 445 Hoes Lane, ~O. Box 1331 Piscataway, NJ 08855-1331 IEEE Press Editorial Board StamatiosV. Kartalopoulos, Editor in Chief
M.Akay J. B. Anderson
R.1. Baker J. E. Brewer
R.1. Herrick R. F. Hoyt D. Kirk R. Leonardi
M. E. El-Hawary
M. S. Newman M. Padgett W. D. Reeve S. Tewksbury G. Zobrist
Kenneth Moore, DirectorofIEEE Press Catherine Faduska, SeniorAcquisitionsEditor Christina Kuhnen, AssociateAcquisitionsEditor Technical Reviewers
John R. Clymer, California State University, Fullerton, CA Vedula V. Sastry, UnitedTechnologies Research Center, Hartford, CT Harold (Bud) Lawson, Lawson KonsultAB, Stockholm, Sweden Roger Germundsson, Wolfram Research, Champaign, IL
Principles of Object-Oriented Modeling and Simulation with Modelica 2.1
Peter Fritzson
+IEEE IEEE PRESS
ffiWILEY-
~INTERSCIENCE A JOHN WILEY & SONS, INC., PUBLICATION
For further information visit: the book.web page http://www.DrModelica.org, the Modelica Association web page http://www.modelica.org, the authors research page http://www.ida.liu.se/labs/pelab/modelica, or email
[email protected] Copyright © 2004 by the Institute of Electrical and Electronics Engineers, Inc. All rights reserved. AII right reserved. Reproductionor use of editorial or pictorial content in any manner is prohibited without express permission, No patent liability is assumed with respect to the use of information contained herein. While every precaution has been taken in the preparation of this book the publisher assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of information contained herein. Certain material from the Modelica Tutorial and the Modelica Language Specificationavailable at http://www.modelica.org has been reproduced in this book with permission from the Modelica Association. Documentation from the commercial libraries HyLib and PneuLib has been reproduced with permission from the author. Documentation and code from the Modelica libraries available at http://www.modelica.orghas been reproduced with permission in this book according to the following license: The Modelica License (Version 1.1 of June 30,2000) Redistribution and use in source and binary forms, with or without modification are permitted, provided that the following conditions are met: I. The author and copyright notices in the source files, these license conditions and the disclaimer below are (a) retained and (b) reproduced in the documentation provided with the distribution. 2. Modifications of the original source files are allowed. provided that a prominent notice is inserted in each changed file and the accompanyingdocumentation, stating how and when the file was modified, and provided that the conditions under ( I) are met. 3. It is not allowed to charge a fee for the original version or a modified version of the software, besides a reasonable fee for distribution and support. Distribution in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution is permitted, provided that it is not advertised as a product of your own. Modelica License Disclaimer
The software (sources. binaries. etc.) in its original or in a modified fonn are provided "as is" and the copyright holders assume no responsibility for its contents what so ever. Any express or implied warranties. including. but not limited to, the implied warranties of merchantabilityand fitness for a particular purpose are disclaimed. In no event shall the copyright holders. or any party who modify and/or redistribute the package, be liable for any direct, indirect, incidental, special, exemplary, or consequential damages. arising in any way out of the use of this software, even if advised of the possibility of such damage. Trademarks Modelica® is a registered trademark of the Modelica Association. MathModelica®and MathCode® are registered trademarks of MathCore Engineering AB. Dymola® is a registered trademark of Dynasim AB. MATLAB® and Simulink® are registered trademarks of MathWorks Inc. Java" is a trademark of Sun MicroSystems AB. Mathematica® is a registered trademark of Wolfram Research Inc. Library ofCongress Cataloging-in-Publication Data is available. ISBN 0-471-47163-1
Printed in the United States of America. 10 9 8 7 6 5 4
v
Many thanks to Hilding Elmqvist for sharing the vision about a declarative modeling language, for starting off the Modelica design effort by inviting people to form a design group, for serving as the first chairman of Modelica Assocation, and for enthusiasm and many design contributions including pushing for a unified class concept. Also thanks for inspiration regarding presentation material including finding historical examples of equations. Many thanks to Martin Otter for serving as the second chairman of the Modelica Association, for enthusiasm and energy, design and Modelica library contributions, as well as inspiration regarding presentation material. Many thanks to Eva-Lena Lengquist Sandelin and Susanna Monemar for help with the exercises, for help with preparing certain appendices, and for preparing the DrModelica interactive notebook teaching material which makes the examples in this book more accessible for interactive learning and experimentation. Thanks to Peter Aronsson, Bernhard Bachmann, Peter Beater, Jan Brugard, Dag Brock, Brian Elmegaard, Hilding Elmqvist, Vadim Engelson, Rudiger Franke, Dag Fritzson, Torkel Glad, Pavel Grozman, Daniel Hedberg, Andreas Idebrant, Mats Jirstrand, Olof Johansson, David Landen, Emma Larsdotter Nilsson, Hakan Lundvall, Sven-Erik Mattsson, Iakov Nakhimovski, Hans Olsson, Adrian Pop, Per Sahlin, Levon Saldamli, Hubertus Tummescheit, and Hans-Jurg Wiesmann for constructive comments, and in some cases other help, on parts of the book, and to Peter Bunus and Dan Costello for help in making MicroSoft Word more cooperative. Thanks to Hans Olsson and Dag Bruck, who edited several versions of the Modelica Specification, and to Michael Tiller for sharing my interest in programming tools and demonstrating that it is indeed possible to write a Modelica book. Thanks to Bodil Mattsson-Kihlstrom for handling many administrative chores at the Programming Environment Laboratory while I have been focusing on book writing, to Ulf Nassen for inspiration and encouragement, and to Uwe Assmann for encouragement and sharing common experiences on the hard task of writing books. Thanks to all members of PELAB and employees of MathCore Engineering, who have given comments and feedback. Finally, thanks to the staff at Vardnas Stiftgard, who have provided a pleasant atmosphere for important parts of this writing effort. Approximately 95 per cent of the running text in this book has been entered by voice using Dragon Naturally Speaking. This is usually slower than typing, but still quite useful for a person like me, who has acquired RSI (Repetitive Strain Injury) due to too much typing. Fortunately, I can still do limited typing and drawing, e.g., for corrections, examples, and figures. All Modelica examples are hand-typed, but often with the help of others. All figures except the curve diagrams are, of course, hand drawn. The first version of this book was finalized in September 2003. All known errata have been inserted and some minor corrections have been made for this second printing.
Linkoping, October 2006
Peter Fritzson
vi
Preface
physical modeling in a number of application areas. The book can be read sequentially from the beginning to the end, but this will probably not be the typical reading pattern. Here are some suggestions: •
Very quick introduction to modeling and simulation - an object-oriented approach: Chapters 1 and
• • •
Basic introduction to the Modelica language: Chapter 2 and first part of Chapter 13. Full Modelica language course: Chapters 1-13. Application-oriented course: Chapter 1, and 2, most of Chapter 5, Chapters 12-15. Use Chapters 3-11 as a language reference, and Chapter 16 and appendices as a library reference. Teaching object orientation in modeling: Chapters 2-4, first part of Chapter 12. Introduction to mathematical equation representations, as well as numeric and symbolic techniques, Chapter 17-18. Modelica environments, with three example tools, Chapter 19.
2.
• • •
An interactive computer-based self-teaching course material called DrModelica is available as electronic live notebooks. This material includes all the examples and exercises with solutions from the book, and is designed to be used in parallel when reading the book, with page references, etc. The diagram below is yet another reading guideline, giving a combination of important language concepts together with modeling methodology and application examples of your choice. The selection is of necessity somewhat arbitrary - you should also take a look at the table of contents of other chapters and part of chapters so that you do not miss something important according to your own interest.
Acknowledgements The members of the Modelica Association created the Modelica language, and contributed have many examples of Modelica code in the Modelica Language Rationale and Modelica Language Specification (see http://www.modelica.org), some of which are used in this book. The members who contributed to various versions of Modelica are mentioned further below. First, thanks to my wife, Anita, who has supported and endured me during this writing effort. Very special thanks to Peter Bunus for help with model examples, some figures, MicroSoft Word formatting, and for many inspiring discussions. Without your help this project might have been too hard, especially considering the damage to my hands from too much typing on computer keyboards.
Preface
vii
Many thanks to Hilding Elmqvist for sharing the vision about a. declarative modeling language, for starting off the Modelica design effort by inviting people to form a design group, for serving as the first chairman of Modelica Assocation, and for enthusiasm and many design contributions including pushing for a unified class concept. Also thanks for inspiration regarding presentation material including finding historical examples of equations. Many thanks to Martin Otter for serving as the second chairman of the Modelica Association, for enthusiasm and energy, design and Modelica library contributions, as well as inspiration regarding presentation material. Many thanks to Eva-Lena Lengquist Sandelin and Susanna Monemar for help with the exercises, for help with preparing certain appendices, and for preparing the DrModelica interactive notebook teaching material which makes the examples in this book more accessible for interactive learning and experimentation. Thanks to Peter Aronsson, Bernhard Bachmann, Peter Beater, Jan Brugard, Dag Briick, Brian Elmegaard, Hilding Elmqvist, Vadim Engelson, Rudiger Franke, Dag Fritzson, Torkel Glad, Pavel Grozman, Daniel Hedberg, Andreas Idebrant, Mats Jirstrand, Olof Johansson, David Landen, Emma Larsdotter Nilsson, Hakan Lundvall, Sven-Enk Mattsson, Iakov Nakhimovski, Hans Olsson, Adrian Pop, Per Sahlin, Levon Saldamli, Hubertus Tummescheit, and Hans-Jtlrg Wiesmann for constructive comments, and in some cases other help, on parts of the book, and to Peter Bunus and Dan Costello for help in making MicroSoft Word more cooperative. Thanks to Hans Olsson and Dag Bruck, who edited several versions of the Modelica Specification, and to Michael Tiller for sharing my interest in programming tools and demonstrating that it is indeed possible to write a Modelica book. Thanks to Bodil Mattsson-Kihlstrorn for handling many administrative chores at the Programming Environment Laboratory while I have been focusing on book writing, to Ulf Nassen for inspiration and encouragement, and to Uwe Assmann for encouragement and sharing common experiences on the hard task of writing books. Thanks to all members of PELAB and employees of MathCore Engineering, who have given comments and feedback. Finally, thanks to the staff at Vardnas Stiftgard, who have provided a pleasant atmosphere for irnportant parts of this writing effort. A final note: approximately 95 per cent of the running text in this book has been entered by voice using Dragon Naturally Speaking. This is usually slower than typing, but still quite useful for a person like me, who has acquired RSI (Repetitive Strain Injury) due to too much typing. Fortunately, I can still do limited typing and drawing, e.g., for corrections, examples, and figures. All Modelica examples are hand-typed, but often with the help of others. All figures except the curve diagrams are, of course, hand drawn.
Linkoping, September 2003
Peter Fritzson
viii
Contributors
Contributions to Examples Many people contributed to the original versions of some of the Modelica examples presented in this book. Most examples have been significantly revised compared to the originals. A number of individuals are acknowledged below with the risk of accidental omission due to oversight. If the original version of an example is from the Modelica Tutorial or the Modelica Specification on the Modelica Association web sites, the contributors are the members of the Modelica Association. In addition to the examples mentioned in this table, there are also numerous small example fragments from the Modelica Tutorial and Specification used in original or modified form in the text, which is indicated to some extent in the refererence section of each chapter.
Classes VanDerPol in Section 2.1.1 SimpleCircuit in Section 2.7.1 PolynomialEvaluator in Section 2.14.3 LeastSquares in Section 2.14.4 Diode and BouncingBall in Section 2.15 SimpleCircuit expansion in Section 2.20.1 Rocket in Section 3.5 MoonLanding in Section 3.5 BoardExample in Section 3.13.3 LowPassFilter in Section 4.2.9 FrictionFunction, KindOfController Sec 4.3.7 Tank in Section 4.4.5 oscillator, Mass, Rigid in Section 5.4.4 RealInput, RealoutPut, MISO in Section 5.5.2 MatrixGain, CrossProduct in Section 5.7.4 Environment in Section 5.8.1 circuitBoard in Section 5.8.2 uniformGravity, pointGravity in Section 5.8.3 ParticleSystem in Section 5.8.3 pendulumImplicitL,readParameterDatain Section 8.4.1.4 ProcessControll,ProcessContro12, ProcessContro13, ProcessContro14 in Section 8.4.2 HeatRectangle2D in Section 8.5.1.4 Material to Figure 8-9 on 2D heat flow using FEM. FieldDomainOperatorslD in Section 8.5.4. DifferentialOperatorslD in Section 8.5.4. HeadDiffusionlD in Section 8.5.4. niff22D in Section 8.5.4.1 FourBarl example in Section 8.6.1. orientation in Section 8.6.1. FixedT:r;-anslation in Section 8.6.2 Material to Figure 8-14 on cutting branches in virtual connection graph.
Individuals Andreas Karstrom Members of the Modelica Association. Members of the Modelica Association. Mikael Adlers Members of the Modelica Association. Martin Otter Peter Bunus Peter Bunus Members of the Modelica Association. Members of the Modelica Association. Members of the Modelica Association. Peter Bunus Martin Otter Martin Otter Members of the Modelica Association. Members of the Modelica Association. Members of the Modelica Association. Members of the Modelica Association. Members of the Modelica Association. Sven-Erik Mattsson, HUrling Elmqvist, Martin Otter, Hans Olsson Sven-Erik Mattsson, Hilding Elmqvist, Martin Otter, Hans Olsson Levon Saldamli Levon Saldamli Hilding Elmqvist, Jonas Jonasson Jonas Jonasson, Hilding Elmqvist Jonas Jonasson, Hilding Elmqvist Hilding Elmqvist Martin Otter Martin Otter, HiJding Elmqvist, SvenErik Mattsson. Martin Otter, Hilding Elmqvist, SvenErik Mattsson. Martin Otter, Hilding Elmqvist, SvenErik Mattsson.
Contributors
findElement in Section 9.2.7 FilterBlockl in. Section 9.2.10.1 realToString in Section 9.3.2.1 eigen in Section 9.3.2.3 findMatrixElement in Section 9.3.2.5 Record2 in Section9.3.2.6 bilinearSampling in Section 9.4.3 MyTable, intcrpolateMyTable in Section 9.4.6 Mechanics in Section 10.3.2.2 Placement, Transformation in Section 11.3.4 Line, Polygon, etc. in Section 11.3.5 Resistor, FrictionFunction in Section 11.3.6.2 hO, hl, h2 in Section 11.5.1 FlatTank in Section 12.2.1.1 TankPI, Tank, LiquidSource in Section 12.2.3 PIContinuousController in Section 12.2.3 TankPID, PIContinuousController Section 12.2.4 DC-Motor Servo in Section 12.3 WatchDogSystem in Section 13.3.2.2 CustomerGeneration in Section 13.3.4.2 ServerWithQueue in Section 13.3.4.2 BasicDEVSTwoPort in Section 13.3.5 SimpleDEVSServer in Section 13.3.5 Place, Transition in Section 13.3.6.5 GameOfLife, nextGeneration in Section 13.3.3.1 PldiscreteController in Section 13.4.1 TankHybridPI in Section 13.4.1 SimpleElastoBacklash in Section 13.4.2 DCMotorCircuitBacklash in Section 13.4.2 ElastoBacklash in Section 13.4.2 Philosophers, DiningTable in Section 13.5.1 Basicvolume in Section 15.2.2 BasicVolume in Section 15.2.3 BasicVolume in Section 15.2.4 BasicVolume in Section 15.2.4.2 IdealGas in Section 15.2.5.2 PressureEnthalpySource in Section 15.2.5.3 SimpleValveFlow in Section 15.2.5.4 ValveFlow in Section 15.2.5.5 ControlledValveFlow in Section 15.2.5.6 CtrlFlowSystem in Section 15.2.5.6 PneumaticCylinderVolume in Section 15.2.5.7 PneumaticCylinderVolume in Section 15.2.5.8 RoomWithFan in Section 15.2.6 RoomlnEnvironment in Section 15.2.6 Hydrogenlodide in Section 15.3.1 LotkaVolterra in Section 15.4.1 WillowForest in Section 15.4.2
Peter Aronsson Members of the Modelica Association. Members of the Modelica Association. Martin Otter Peter Aronsson Membersof the Modelica Association. Membersof the Modelica Association. Membersof the Modelica Association. Membersof the Modelica Association. Membersof the Modelica Association. Membersof the Modeliea Association. Membersof the ModelicaAssociation. Membersof the Modelica Association. Peter Bunus Peter Bunus Peter Bunus Peter Bunus Mats Jirstrand Peter Bunus Peter Bunus Peter Bunus Peter Bunus Peter Bunus Hilding Elmqvist, Peter Bunus Peter Bunus Peter Bunus Peter Bunus Peter Bunus Peter Bunus Martin Otter Hakan Lundvall Mats Jirstrand Mats Jirstrand Mats Jirstrand Johan Gunnarsson Mats Jirstrand, HubertusTummescheit Mats Jirstrand Mats Jirstrand Mats Jirstrand Mats Jirstrand Mats Jirstrand HubertusTummescheit HubertusTummescheit HubertusTummescheit HubertusTummescheit Emma LarsdotterNilsson Emma Larsdotter Nilsson Emma Larsdotter Nilsson
IX
x
Contributors TCPSender, Loss_link_queue in Section 15.6.3 Router21, TCPSackvsTCPWestWood in Section 15.6 LinearActuator in Section 15.7 WeakAxis in Section 15.8 WaveEquationSample in Section 15.9 FreeFlyingBody in Section 15.10.2 doublePendulumNoGeometry in Section 15.10.6 doublePendulumCylinders in Section 15.10.5.2 PendulumLoop2D in Section 15.10.6 Ext Force Pendulum in Section 15.10.8.1 PendulumRotationalSteering in Section 15.10.8.3 PendulumWithPDController in Section 15.10.8.4 TripleSprings in Section TripleSprings 5.4.3.2 EngineV6 in Section 15.10.10 Generator in Section 17.1.6
Material to Figure 17-4, Figure 17-5, and Figure 17-6 EntertainmentUnit in Section 18.3.1.1 LayerConstraints in Section 18.3.1.1 CdChangerBase, CdChanger in Section 18.3.1.2
Daniel Farnquist et. al., Peter Bunus Daniel Farnquist et. al., Peter Bunus Mats Jirstrand, Jan Brugard Mats Jirstrand, Jan Brugard Jan Brugard, Mats Jirstrand Vadim Engelson Vadim Engelson Vadim Engelson Vadim Engelson Vadim Engelson Vadim Engelson Vadim Engelson Martin Otter Martin Otter Peter Bunus Bernhard Bachmann Karin Lunde Members of Modelica Association Hans Olsson
Contributors to the Modelica Standard Library, Versions 1.0 to 2.1 Person
Affiliation
Peter Beater Christoph Clauf Martin Otter Andre Schneider Nikolaus Schilrrnann Christian Schweiger Michael Tiller Hubertus Tummescheit
University of Paderbom, Germany Fraunhofer Institute for Integrated Circuits, Dresden, Germany German Aerospace Center, Oberpfaffenhofen, Germanyr Fraunhofer Institute for Integrated Circuits, Dresden, Germany German Aerospace Center, Oberpfaffenhofen, Germany German Aerospace Center, Oberpfaffenhofen, Germany Ford Motor Company, Dearborn, MI, U.S.A. Lund Institute of Technology, Sweden
Contributors to the Modelica Language, Version 2.1 Person
Affiliation
Mikael Adlers Peter Aronsson Bernhard Bachmann Peter Bunus Jonas Ebom Hilding Elmqvist RUdiger Franke Peter Fritzson Anton Haumer Dlof Johansson Karin Lunde Sven Erik Mattsson Hans Olsson
MathCore, Linkoping, Sweden Linkoping University, Sweden University of Applied Sciences, Bielefeld, Germany Linkoping University, Sweden United Technologies Research Center, Hartford, U.S.A. Dynasim, Lund, Sweden ABB Corporate Research, Ladenburg, Germany Linkoping University, Sweden Tech. Consult. & Electrical Eng., St.Andrae-Woerdem, Austria Linkoping University, Sweden R.O.S.E. Informatik GmbH, Heidenheim, Germany Dynasim, Lund, Sweden Dynasim, Lund, Sweden
Contributors Martin Otter Levon Saldamli Christian Schweiger Michael Tiller Hubertus Tummescheit Hans-Jurg Wiesmann
German Aerospace Center, Oberpfaffenhofen, Germany Linkoping University, Sweden German Aerospace Center, Oberpfaffenhofen, Germany Ford Motor Company, Dearborn, MI, U.S.A. United Technologies Research Center, Hartford, U.S.A ABB Switzerland Ltd.,Corporate Research, Baden, Switzerland
Contributors to the Modelica Language, Version 2.0 Person Peter Aronsson Bernhard Bachmann Peter Beater Dag Bruck Peter Bunus Hilding Elmqvist Vadim Engelson RUdiger Franke Peter Fritzson Pavel Grozman Johan Gunnarsson Mats Jirstrand Sven Erik Mattsson Hans Olsson Martin Otter Levon Saldamli Michael Tiller Hubertus Tummescheit Hans-JUrg Wiesmann
Affiliation Linkoping University, Sweden University of Applied Sciences, Bielefeld, Germany University of Paderborn, Germany Dynasim, Lund, Sweden Linkoping University, Sweden Dynasim, Lund, Sweden Linkoping University, Sweden ABB Corporate Research, Ladenburg Linkoping University, Sweden Equa, Stockholm, Sweden MathCore, Linkoping, Sweden MathCore, Linkoping, Sweden Dynasim, Lund, Sweden Dynasim, Lund, Sweden German Aerospace Center, Oberpfaffenhofen, Germany Linkoping University, Sweden Ford Motor Company, Dearborn, MI, U.S.A. Lund Institute of Technology, Sweden ABB Switzerland Ltd.,Corporate Research, Baden, Switzerland
Contributors to the Modelica Language, Version 1.4 Person Bernhard Bachmann Dag Bruck Peter Bunus Hilding Elmqvist Vadim Engelson Jorge Ferreira Peter Fritzson Pavel Grozman Johan Gunnarsson Mats Jirstrand Clemens Klein-Robbenhaar Pontus Lidman Sven Erik Mattsson Hans Olsson Martin Otter
Affiliation University of Applied Sciences, Bielefeld, Germany Dynasim, Lund, Sweden Linkoping University, Sweden Dynasim, Lund, Sweden Linkoping University, Sweden University of Aveiro, Portugal Linkoping University, Sweden Equa, Stockholm, Sweden MathCore, Linkoping, Sweden MathCore, Linkoping, Sweden Gennany MathCore, Linkoping, Sweden Dynasim, Lund, Sweden Dynasim, Lund, Sweden German Aerospace Center, Oberpfaffenhofen, Germany
xi
xii
Contributors
Tommy Persson Levon Saldamli Andre Schneider MichaelTiller HubertusTummescheit Hans-Jiirg Wiesmann
Linkoping University,Sweden LinkopingUniversity,Sweden FraunhoferInstitute for IntegratedCircuits, Dresden, Germany Ford Motor Company, Dearborn, MI, U.S.A. Lund Institute of Technology, Sweden ABD SwitzerlandLtd.,Corporate Research,Baden, Switzerland
Contributors to the Modelica Language, up to Version 1.3
Person BernhardBachmann FrancoisBoudaud Jan Broenink Dag Bruck Thilo Ernst Hilding Elrnqvist' RiidigerFranke Peter Fritzson Pavel Grozman Kaj Juslin David Kagedal Mattias Klose N. Loubere Sven Erik Mattsson P. J. Mosterman HenrikNilsson Hans Olsson
Affiliation University of Applied Sciences,Bielefeld,Germany Gaz de France, Paris, France University of Twente, Enschede,the Netherlands Dynasim, Lund, Sweden GMD FIRST, Berlin, Germany Dynasim, Lund, Sweden ABB NetworkPartner Ltd. Baden, Switzerland Linkoping University, Sweden Equa, Stockholm,Sweden VIT, Espoo, Finland Linkoping University, Sweden TechnicalUniversityof Berlin, Germany Gaz de France, Paris, France Dynasim, Lund, Sweden GermanAerospaceCenter,Oberpfaffenhofen, Germany Linkoping University, Sweden Dynasim, Lund, Sweden
Martin Otter
German Aerospace Center, Oberpfaffenhofen, Germany
Per Sahlin Andre Schneider Michael Tiller Hubertus Tummescheit Hans Vangheluwe
Bris Data AB, Stockholm, Sweden FraunhoferInstitute for IntegratedCircuits, Dresden, Germany Ford Motor Company,Dearborn, MI, U.S.A. Lund Institute of Technology, Sweden University of Gent, Belgium
Modelica Association Member Companies and Organizations
Companyor Organization DynasimAB, Lund, Sweden Equa AB, Stockholm, Sweden German Aerospace Center,Oberpfaffenhofen, Germany Linkoping University, the Programming Environment Laboratory, Linkoping, Sweden MathCoreEngineering AB, Linkoping,Sweden
1
The Modelica 1.0design documentwas edited by HildingElmqvist.
Contributors
xiii
Funding Contributions Linkoping University, the Swedish Strategic Research Foundation (SSF) in the ECSEL graduate school, and MathCore AB have supported me for part of this work. Additionally, results in the form of reports and papers produced in a number of research projects at my research group PELAB, the Programming Environment Laboratory, Department of Computer and Information Science, Linkoping University, have been used as raw material in writing parts of this book. Support for these research projects have been given by: the Swedish Business Development Agency (NUTEK) in the Modelica Tools project, the Wallenberg foundation in the WITAS project, the Swedish Agency for Innovation Systems (VINNOV A) in the VISP (Virtuell Integrerad Simuleringsstodd Produktframtagning) project, the European Union in the REALSIM (Real-Time Simulation for Design of Multi-physics Systems) project, SSF in the VISIMOD (Visualization, Identification, Simulation, and Modeling) project, and SKF AB.
Contents
xv
Table of Contents
Part I
Introduction ••••..•.......•.....•.•................••...••..•.....•.•.........••••....•...•....••.•••.••.•••••..•..•.•..•.•..••••...•.•...• 1
Chapter 1
Introduction to Modeling and Simulation
3
1.1 Systems and Experiments 1.1.1 Natural and Artificial Systems 1.1.2 Experiments 1.2 The Model Concept 1.3 Simulation 1.3.1 Reasons for Simulation 1.3.2 Dangers of Simulation 1.4 Building Models 1.5 AnalyzingModels 1.5.1 Sensitivity Analysis 1.5.2 Model-Based Diagnosis 1.5.3 Model Verification and Validation 1.6 Kinds of Mathematical Models 1.6.1 Kinds of Equations 1.6.2 Dynamic vs. Static Models 1.6.3 Continuous-Titne vs. Discrete-Time Dynamic Models 1.6.4 Quantitative vs. Qualitative Models ).7 Using Modeling and Simulation in Product Design . 1.8 Examples of System Models 1.9 Summary t.IO Literature Chapter 2
3 4 5 6 7
7 8 8 9 9 10 10
10 11 11 12 13 14 15 18 18
A Quick Tour of M.odelica ••.••...•..••••••••••••.•••••••••••••••.•..•.•••.•••••.••.••••••••••.•.•••••••••.••••••••••... 1.9
2.1 Getting Started with Modelica 2.1.1 Variables 2.] .2 Comments 2.1.3 Constants 2.1.4 Default start Values 2.2 Object-Oriented Mathematical Modeling 2.3 Classes and Instances Creating Instances 2.3.1 2.3.2 Initialization 2.3.3 Restricted Classes 2.3.4 Reuse ofM.odified Classes 2.3.5 Built-in Classes 2.4 Inheritance 2.5 Generic Classes 2.5.1 Class Parameters Being Instances 2.5.2 Class Parameters being Types 2.6 Equations 2.6.1 Repetitive Equation Structures 2.6.2 Partial Differential Equations 2.7 Acausal Physical Modeling 2.7.1 Physical Modeling vs. BJock-Oriented Modeling
0
•••••••••••••••••••••••••••
19 22 24 24 25 25 26 26 27 28 28 29 29 30 30 31 32 33 34 34 35
xvi
Contents
2.8 The ModelicaSoftware Component Model 36 2.8.1 Components 37 2.8.2 ConnectionDiagrams 37 2.8.3 Connectorsand ConnectorClasses 38 2.8.4 Connections 38 2.9 Partial Classes 39 2.9.1 Reuse of'Partial Classes 40 2.10 ComponentLibrary Design and Use 41 2.11 Example: Electrical ComponentLibrary 41 2'.11.1 Resistor 41 2.11.2 Capacitor 41 2.11.3 Inductor 42 2.11.4 VoltageSource 42 2.11.5 Ground 43 2.12 The Simple Circuit Model....................................•................................................................ 43 2.13 Arrays 44 2.14 Algorithmic Constructs 46 2.]4.1 Algorithms 46 2.14.2 Statements 46 2.14.3 Functions 47 48 2.14.4 Function and Operator Overloading 2.14.5 External Functions 49 2.14.6 Algorithms Viewed as Functions 49 2.15 Discrete Event and HybridModeling 50 2.16 Packages 53 2.17 Annotations 54 2.18 Nanling Conventions 55 2.19 Modelica StandardLibraries 55 2.20 Implementation and Execution of Model.ica 57 2.20.1 Hand Translation of the SimpleCircuit Model. 58 2.20.2 Transformation to State SpaceForm 60 2.20.3 Solution Method , 61 2.21 History 63 2.22 Summary ·65 2.23 Literature 65 2.24 Exercises 67 eo •••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Part II
The Modelica Language •..•.••••...•.•..••••••....•...•..•......•..••....••...••..••.....•....•.•••••.•••••.••...•••••••..•••• 71
Chapter 3
Classes, Types, and Declarations
3.1 Contract BetweenClass Designerand User 3.2 A Class Example 3.3 Variables 3.3.1 DuplicateVariableNames 3.3.2 Identical VariableNames and Type Names 3.3.3 Initialization of Variables 3.4 Behavior as Equations 3.5 Access Control 3.6 Simulatingthe ~100n LandingExample 3.6.1 Object CreationRevisited 3.7 Short Classesand Nested Classes 3.7.1 Short Class Definitions 3.7.2 'Local Class Definitions-Nested Classes 3.8 Restricted Classes 3.8.1 RestrictedClass: model
73 73 74 74 75 75 75
76 77 78 80 80 80 80 81 81
Contents 3.8.2 3.8.3 3.8.4
Restricted Class: record Restricted Class: type Restricted Class: connector 3.8.5 Restricted Class: block 3.8.6 function 3.8.7 package 3.9 Predefined Types/Classes 3.9.1 Real Type 3.9.2 Integer, Boolean, and String Types 3.9.3 Enumeration Types 3.9.4 Other Predefined Types 3.10 Structure of Variable Declarations 3.1.1 Declaration Prefixes 3.11.1 Access Control by Prefixes: public and protected 3.11.2 Variability Prefixes: constant, parameter and discrete 3.11.3 Causality Prefixes: input and output. 3.11:4 Flow Prefix: flow 3.11.5 Modification Prefixes: replaceable, redeclare, and final 3.11.6 Class Prefix: partial 3.11.7 Class Encapsulation Prefix: encapsulated 3.11.8 Instance Hierarchy Lookup Prefixes: inner and outer 3.11.9 Ordering of Prefixes 3.11.10 Variable Specifiers 3.11.11 Initial 'Values of Variables 3.12 Declaration Order and Use Before Declaration 3.13 Scoping and Name Lookup 3.13.1 Nested Name Lookup 3.13.2 Nested Lookup Procedure in Detail 3.13.3 Instance Hierarchy Lookup Using inner and outer 3.14 The Concepts of Type and Subtype 3.14.1 Conceptual Subtyping of Subranges and Enumeration Types 3.14.2 Tentative Record/Class Type Concept 3.14.3 Array Type 3.14.4 Function Type 3.14.5 General Class Type 3.14.6 Types of Classes That Contain Local Classes 3.14.7 Subtyping and Type Equivalence 3.14.8 Use of Type Equivalence 3.14.9 Definition of Type Equivalence 3.14.10 Use of Subtyping 3.14.11 Definition of Subtyping 3.15 Summary 3.16 Literature 3.17 Exercises Chapter 4
Inheritance, l\lodifications, and Generics
4.1 Inheritance 4.1.1 Inheritance of Equations 4.1.2 Multiple Inheritance 4.1.3 Processing Declaration Elements and Use Before Declare 4.1.4 Declaration Order of extends Clauses 4.1.5 The MoonLanding Example Using Inheritance 4.1.6 Inheritance and Subtyping 4.1.7 Inheritance of Protected Elements
xvii 82 82 82 82 83 83 84 85 86 86 87 88 88 88 89 91 91
91 93 93 93 93 94 94 95 96 96 97 99 100 102 102 103 104 104 105 106 106 107 107 108 108 109 109 11 t 112 112 113 114 115 115 116 117
xviii
Contents
4.1.8 Short Class Definition as Inheritance 4.1.9 ExtendingPredefined Types/Classes 4.1. to Redefining Declared Elementsat Inheritance 4.2 Inheritance Through Modification 4.2.1 Modifiers in VariableDeclarations 4.2.2 Modifiers for Constant Declarations 4.2.3 M.odifiers for Array Variables 4.2.3.] Iterative Array ElementModification Using each 4.2.3.2 Modificationof Arrays with NonconstantExtent. 4.2.4 Modifiers in Short Class Definitions 4.2.5 Modifiers in extends Clauses 4.2.6 Modification of Nested extends Clauses 4.2.7 Priority of Modifications Modificationof ProtectedElements 4.2.8 4.2.9 Hierarchical Modification 4.2.10 Single ModificationRule 4.3 Redeclaration 4.3.t R.edeclaration of Elements not Declared replaceable 4.3.2 ModificationPrefix: replaceable 4.3.3 ModificationPrefix: redeclare 4.3.4 ModificationPreventionPrefix: final 4.3..5 Constraining Type of ReplaceableElements 4.3.6 Summaryof Restrictionson Redeclarations 4.3.7 Redeclarations of AnnotationChoices 4.4 ParameterizedGeneric Classes 4.4.1 Class Parameterization Using Replaceable and Redeclare 4.4.2 Class Parameters Being Components 4.4.3 GeneralizingConstrainingTypes of Class Parameters 4.4.4 Class ParametersBeing Types 4.4.5 Parameterization and Extensionof Interfaces 4.5 Designing a Class to Be Extended 4.5.1 4.5.2
4.6 4.7 4.8
Chapter 5
Reuse ofYariable Declarations from Partial Base Classes
Extendi.ng and RedefiningBehavior Summary Literature Exercises Components, Connectors, and Connections
5.1 Software Component Models 5.1.1 Components 5.1.2 ConnectionDiagrams 5.2 Connectors and Connector Classes 5.3 Connections................. 5.3.1 The flow Prefix and Kirchhoff's Current Law....... 5.3.2 connect Equations 5.3.3 Electrical Connections 5.3.4 MechanicalConnections 5.3.5 Acausal, Causal, and CompositeConnections 5.4 Connectors, Components,and Coordinate Systems 5.4.1 Coordinate Direction for Basic Electrical Components 5.4.2 Mechanical Translational Coordinate Systems and Components 5.4.3 Multiple Connectionsto a Single Connector 5.4.3.1 ResistorCircuit 5.4.3.2 TripleSprings
117 118
119
119 ) 19 120 120 120 121 122
122 123 123 124 124
]25 125 126 127 127 128 129 131 132 133
133 134 135 135 136
137 138 139
140 140
140 145
145 t 46
146 146 148
148 ]49 149 150 151 15] 152 153
155 155 156
Contents
5.4.4 An Oscillating Mass Connectedto a Spring 5.5 Design Guidelines for ConnectorClasses 5.5.1 Physical Connector Classes Based on Energy Flow -. 5.5.2 Signal-basedConnectorClasses 5.5.3 CompositeConnectorClasses 5.6 ConnectingComponentsfrom Multiple Domains 5.7 Detailed Connection Semantics 5.7.1 Hierarchically StructuredComponents with Inside and Outside Connectors 5.7.2 Connection Restrictionson Input and Output Connectors 5.7.3 ConnectionConstraintsregarding Arrays, Subscripts, and Constants 5.7.3.1 Array Dimensionality Matching 5.7.3.2 Constant or Parameter SubscriptConstraint 5.7.4 Connecting Arrays of Connectors 5.7.5 Generationof Connection Equations 5.7.5.1 Connection Sets 5.7.5.2 ConnectionEquations for Nonflow Variables 5.7.5".3 ConnectionEquations for Flow Variables 5.7.5.4 ConnectionEquations for Constants and Parameters 5.7.5.5 inner/outerConnectorMatching 5.7.6 Cardinality-dependent ConnectionEquations 5.7.7 The Directionof a Connection 5.8 ItnplicitConnectionswith the inneriouterConstruct 5.8.1 Accessof Shared EnvironmentVariables 5.8.2 Implicit versus Explicit ConnectionStructures 5.8.3 ImplicitInteraction within a Gravitational Force Field 5.9 Overconstrained ConnectionGraphs 5.10 Summary 5.11 Literature 5.12 Exercise
xix
v ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
00
Chapter 6
6.1 6.2 6.3
Character Set Comments Identifiers, Names, and Keywords
4
6.5.2
•••••••
173 173
173 J74 175 177 t 81 181 1.81 181
Literals, Operators, and Expressions •................•..........•..••..•.....•.•.."
6.3.1 Identifiers Nam.es 6.3.2 6.3.3 ModelicaKeywords PredefinedTypes 6.4 Literal Constants 6.5 6.5.1 Floating Point Numbers 6.5.3 , 6.5.4
u
183
183 183 184 184 185 ,.185 185
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Integers Booleans
Strings 6.5.5 Enumeration Literals 6.5.6 Array Literals 6.5.7 Record Literals 6.6 Operator Precedenceand Associativity 6.7 Order of 'Evaluation 6.7.1 Guarding Expressions Against Incorrect Evaluation 6.7.1.t Guards with Discrete-Time Conditions 6.7.1.2 Guards with Continuous-Time Conditions 6.8 Expression Type and Conversions 6.8.1 Type Conversions 6.8.1.1 Implicit Type Conversions
156 158 159 161 162 162 162 163 164 166 166 167 167 169 169 171 171 172 172
186 186 186 J86 186
187 187 187 187 188 t 89 189 189 190 190 191
xx
Contents 6.8.1.2 Explicit Type Conversions 6.9 Variability of Expressions 6.9.1 Constant Expressions 6.9.2 Parameter Expressions 6.9.3 Discrete-Time Expressions 6.9.4 Continuous-Time Expressions 6.9.5 Variability and Subtyping 6.10 Arithmetic Operators 6.10.1 Integer Arithmetic 6. t 0.2 Floating Point Arithmetic 6.11 Equality, Relational, and Logical Operators 6.12 Miscellaneous Operators 6.12. t String Concatenation 6.12.2 The Conditional Operatorif-expressions 6.12.3 Member Access Operator 6.12.4 User-defined Overloaded Operators 6.12.5 Built-in Variable time 6.13 Built-in Intrinsic MathematicalFunctions 6.14 Built-in Special Operators and Functions 6.14.1 Event Iteration and the pre Function 6.15 Summary 6.16 Literature 6.17 Exercises
Chapter 7 1.1
191 192 192 192 1.93 193 194 195 195 195 196 197 197 197 198 t 98 198 199 201 204 204 204 204
Arrays ..••.•.•.••.•..•••••.....•••..•.•...••••••••.•.•.••..•.•.••••••.••••••...•••.....•••.••.••••••••..••...•••.•••••.•••••••••.• 207
Array Declarations and Types 7.1.1.1 Array Dimension Lower and Upper Index .Bounds 7.1.2 Flexible Array Sizes 7.1.3 Array Types and Type Checking 7.2 General Array Construction 7.2.1 Range Vector Construction 7.2.2 Set FormersArray Constructors with Iterators 7.3 Array Concatenation and Construction 7.3.1 Type Rules for Concatenation 7.3.2 More on Concatenation Along the First and Second Dimensions 7.3.2.1 Examples 7.4 Array Indexing 7.4.1 Indexing with Scalar Index Expressions 7.4.1.1 Indexing with Boolean or Enumeration Values 7.4.] .2 Indexing with end 7.4.2 Accessing Array Slices with Index Vectors 7.4.3 Array Record Field Slices of Record Arrays 1.5 Using Array Concatenation and Slices 7.5. t Advise for Users with Matlab Background 7.5.2 Usage Examples 7.5.2.1 Appending an Element to Vectors and Row/Column Matrices 7.5.2.2 Composing a Blocked Matrix from Submatrices 7.5.2.3 Cyclic Permutation of Matrix Rows or Columns 7.6 Array Equality and Assignment 7.6.1 Declaration Equations and Assignments for Arrays Indexed by Enumerations and Booleans 7.7 String Concatenation Array Operator 7.8 Arithmetic Array Operators 7.9 Built-in Array Functions
201 208 209 209 2 to 21·1 212 213 214 215 21.6 216 217
217 217 217 2] 8 219 219 220 220 220 221 221
222 223 223 225
xxi
Contents
7.9.1 Array Dimension and Size Functions 7.9.2 Dimensionality Conversion Functions 7.9.3 Specialized Constructor Functions 7.9.4 Array Reduction Functions and Operators 7.9.4.1 Array Reduction Operators with Iterators 7.9.5 Matrix and Vector Algebra Functions 7.9.6 Array Concatenation Functions Once More 7.10 Application of Scalar Functions to Arrays 7.10.1 General Formulation of Element-wise Function Application 7.11 Empty Arrays 7.11.1 Empty Array Literals 7.12 Summary 7.13 Literature 7.14 Exercises Chapter 8
225 04225 226 227 227 228 229 229 230 231 232 233 233 233
Equations
237
General Equation Properties 8.1.1 Equation Categories and Uses 8.1.2 Expressivity of Equations 8.1.3 Single-assignment Rule for Equations 8.).4 Synchronous Data-flow Principle for Modelica 8.2 Equations in Declarations 8.2.1 Declaration Equations 8.2.2 Modifier Equations 8.3 Equations in Equation Sections 8.3.1 Simple Equality Equations 8.3.2 Repetitive Equation Structures with for-Equations 8.3.2.1 Implicit Iteration Ranges 8.3.2.2 Polynomial Equations Using for-Equations 8.3.2.3 Variable-length Vector Step Signals Using for-Equations 8.3.3 Connect Equations 8.3.3.1 Repetitive Connection Structures 8.3.4 Conditional Equations with if-Equations 8.3.5 Conditional Equations with when-Equations 8.3.5.1 Restrictions on Equations within when-Equations 8.3.5.2 Application of the Single-Assignment Rule on when-Equations 8.3.6 reinit 8.3.7 assert and terminate 8.3.7.1 assert 8.3.7.2 terminate 8.4 Initialization and initial equation 8.4.1.1 Initialization Constraints and Hints Through the start Attribute 8.4.1.2 Initialization Constraints Through initial equation 8.4.1.3 Using when-Equations During Initialization "Explicit and Implicit Specification of Parameter Values for Initialization 8.4.1.4 8.4.1.5 The Number of Equations Needed for Initialization 8.4.2 System Initialization ExamplesDiscrete Controller Models 8.5 Partial Differentia' Equations 8.5.1 Structuring a PDE Problem 8.5.1.1 Basic Definitions of Domain, Field, Boundary, and Interior 8.5.1.2 The Method of Lines Approach to Spatial Discretization 8.5.1.3 Range and Domain Geometry Types and Generalized in Operator 8.5.1.4 Summary of Operators and Types Needed for PDEs in Modelica 8.5.2 Modelica PDE Examples of Domains, Fields, and Models in ID, 2D~ and 3D
8.1
u
237
237 238 238 239 239 239 240 240 240 241. 242 242 244 244 244 245 246 247 248 249 249 250 250 250 251 252 253 253 255 256 258 260 261 262 263 264 264
•••••••••••••••••••••••••••••••••••••••
xxii
Contents
8.5.2.1 Modelica Heat Diffusion Model on a 'Rectangular Domain One-dimensional Domains 8.5.2.2 Two-dimensional Domains 8.5.2.3 Three-dimensional Domains 8.5.2.4 A POE on a 20 Domain with General Shape and FEM Solution 8.5.3 Grid Function Finite Difference Approach to ID Heat Diffusion 8.5.4 8.5.4.1 2D Grid Functions EquationOperatorsfor Overconstrained Connection-Based Equation Systems 8.6 An Exampleof an Overconstrained Connection Loop 8.6.1 8.6.2 Overconstrained Equation Operators for Connection Graphs 8.6.3 Convertingthe Connection Graph into Trees and Generating Connection Equations Summary 8.7 Literature 8.8 Exercises 8.9 Chapter 9
9.1
Algorithms and .Functions
283
Declarative versus Nondeclarative Constructs Algorithms and Statements 9.2.] Algorithm Sections Usage Constraints Relatedto Statements and SpecialOperators 9.2.1.1 Local Initialization and Output Consistency 9.2.1.2 initialalgorithm Sections 9.2.2 9.2.3 Simple Assignment Statements Assignments from CalledFunctionswith Multiple Results 9.2.4 Iteration Using for-statements 9.2.5 Implicit Iteration Ranges 9.2.5.1 9.2.5.2 Nested for-loops with Multiple Iterators Iteration 'Using while-statements 9.2.6 Breaking IterationUsingbreak-statements 9.2.7 if-statements 9.2.8 Assignments within if-statements 9.2.8.] 9.2.9 when-statements
9.2
9.2.9.1 Defining when-statements by if-statements 9.2.9.2 AvoidingMultiple-definition Conflicts for when..statements Restrictions on when-statements 9.2.9.3 9.2.1 0 reinit,assert, and terminate 9.2.1 0.1 reinit 9.2.10.2 assert 9.2.t 0.3 terminate 9.3 Functions .Function .Declaration 9.3.1 Orderingof Formal Parameters 9.3.1.1
9.3.2
Function Call
Mixed Positional and Named FunctionArgumentPassing 9.3.2.1 Returning Singleor Multiple Function Results 9.3.2.2 Optional Function Results 9.3.2.3 9.3.2.4 Empty FunctionCalls 9.3.2.5 Function return-statement 9.3.2.6 .Record Constructor Functions 9.3.3 Additional FunctionProperties and Restrictions Extending'Base Functions 9.3.4 Built-inFunctions 9.3.5 ScalarFunctions Applied to Array Arguments 9.3.6 9.3.7 Viewing Algorithms as Functions
264 266 267 268 270 270 273 274 274 276 278 279 279 279
40 • • • • • • • • • • • • • • • • • • • • • • • • • • • •
283 285 285 285 286 286 287 287 288 289 290 290 291 292 292 293 294 295 296 296 296 298 298 298 299 299 300 301 302 303
304 304 305 308 308 309 309 310
Contents
9.3.8 Comparison of Functions with General Modelica Classes 9.4 ExternalFunctions 9.4.1 Structureof External FunctionDeclarations 9.4.1.1 Default Call Structure Mapping 9.4.1.2 Explicit Call StructureMapping 9.4.2 Argument and Result Type Mapping 9.4.3 A Large Example 9.4.4 Preventing External Functions from Changing Their Inputs 9.4.5 Utility Functions Callable in External Functions 9.4.6 External Data Structureslixternal Objects
xxiii 310
311 311 312 3] 3 315 317
318 319 320 322 323 325 327 329 329 329
9.5 User-defined Overloaded Functions and Operators 9.5.1. Built-in Standard Overloaded Operators 9.5.2 Overloaded DefinitionLookup Mechanism and Complex Number Example 9.5.3 Overloaded Matrix Operators and Functions with LAPACK Interface 9.6 Summary 9.7 Literature 9.8 Exercises
Chapter 10 Packages ............................................................•...........•...•...•...............•.•...•.........•..••....333 10.1 Packages as Abstract Data Types 10.2 Package Access 10.2.1 ImportingDefinitionsfrom a Package 10.2.1.1 Qualified Import 10.2.1.2 Single Definition Import Unqualified Import 10.2.1.3 10.2.1.4 Renaming Import 10.3 Package and Library Structuring 10.3.1 Package Naming and Subpackages 10.3.2 Subpackages and Hierarchical Libraries ]0.3.2.1 Encapsulated Packages and Classes 10.3.2.2 Name Lookup in Hierarchically Structured Packages 10.3.3 Mapping Package Structuresto a Hierarchical File System 10.3.3.1 The within Statement 10.3.3.2 Mapping a PackageHierarchy into a Directory Hierarchy 10.3.3.3 Mapping a Package Hierarchy or Class into a Single File 10.3.4 The Modelica Library Path-MODELICAPATH 10.3.5 Packages versus Classes 10.4 Package Variants and Operations
10.4.1 Generic Packages 10.4.2 Inherited Packages 10.4.3 Local Packages 10.4.4 Nonencapsulated Packages 10.4.4.1 Problems with Nonencapsulated Packages 10.4.5 Moving Packages 10.5 A ComparisonBetween Java and. Modelica Packages 10.5.1 Import 10.5.2 Subpackages 10.5.3 Encapsulation and Independence of Packages 10.5.4 Local Packages 10.5.5 Inheritance of Packages 10.5.6 Lookup 10.5.7 Mapping to the File System 10.5.8 Identification of Packages 10.5.9 Remarks "
_
333 335 335 336 336 337 337 338
338 0
":
Figure 1-3.A resistor is a staticsystem where the voltage is directly proportional to the current, independent of time, whereas a capacitor is a dynamic system where voltage is dependent on the previous timehistory. A resistor is an example of a static model which can be formulated without including time. The resistor voltage is directly proportional to the current through the resistor, e.g. as depicted in Figure 1-3, with no dependenceon time or on the previous history.
1.6.3 Continuous-Time Ys. Discrete-Time Dynamic Models There are two main classes of dynamic models: continuous-time and discrete-time models. The class of continuous-time models can be characterized as follows:
Chapter I Introduction to Modeling and Simulation 13
•
Continuous-time models evolve their variable values continuously over time.
A variable from a continuous-time model A is depicted in Figure 1-4. The mathematical formulation of continuous-time models includes differential equations with time derivatives of some model variables. Many laws of nature, e.g. as expressed in physics, are formulated as differential equations. A -----B
...a-
I--
---'-_ _---'-
~
time
Figure 1-4. A discrete-time system B changes values only at certain points in time, whereas continuoustime systems like A evolve values continuously. The second class of mathematical models is discrete-time models, e.g. as B in Figure 1-4, where variables change value only at certain points in time:
•
Discrete-time models may change their variable values only at discrete points in time.
Discrete-time models are often represented by sets of difference equations, or as computer programs mapping the state of the model at one point in time to the state at the next point in time. Discrete-time models occur frequently in engineering systems, especially computer-controlled systems. A common special case is sampled systems, where a continuous-time system is measured at regular time intervals and is approximated by a discrete-time model. Such sampled models usually interact with other discrete-time systems like computers. Discrete-time models may also occur naturally, e.g. an insect population which breeds during a short period once a year; i.e., the discretization period in that case is one year.
1.6.4 Quantitative vs. Qualitative Models All of the different kinds of mathematical models previously discussed in this section are of a quantitative nature--variable values can be represented numerically according to a quantitatively measurable scale.
Superb Tasty
Good Mediocre time
Figure 1-5. Quality of food in a restaurant according to inspections at irregular points in time. Other models, so-called qualitative models, lack that kind of precision. The best we can hope for is a rough classification into a finite set of values, e.g. as in the food-quality model depicted in Figure 1-5. Qualitative models are by nature discrete-time, and the dependent variables are also discretized. However, even if the discrete values are represented by numbers in the computer (e.g. mediocre--l,
14 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica good-2, tasty -3, superb-4), we have to be aware of the fact that the values of variables in certain qualitative models are not necessarily according to a linear measurable scale, i.e., tasty might not be three times better than mediocre.
1.7 Using Modeling and Simulation in Product Design What role does modeling and simulation have in industrial product design and development? In fact, our previous discussion has already briefly touched this issue. Building mathematical models in the computer, so-called virtualprototypes, and simulating those models, is a way to quickly determine and optimize product properties without building costly physical prototypes. Such an approach can often drastically reduce development time and time-to-market, while increasing the quality of the designed product. ExperienceFeedback Maintenance
System requirements
Product verification and deployment Subsystemlevel integration test calibrationand verification Achitectural designand system functional design
Subsystemlevel integrationand verification
Realization
Level of Abstraction
Documentation, Version and Configuration Management Figure 1-6. The product design-V.
The so-called product design- V, depicted in Figure 1-6, includes all the standard phases of product development: • • • • • • • •
Requirements analysis and specification. System design. Design refinement. Realizationand implementation. Subsystemverificationand validation. Integration. Systemcalibration and model validation. Product deployment.
How does modelingand simulationfit into this design process? In the first phase, requirements analysis, functional and nonfunctionalrequirements are specified. In this phase important design parametersare identified and requirementson their values are specified. For example, when designing a car there might be requirements on acceleration, fuel consumption,
Chapter 1 Introduction to Modeling and Simulation 15 maximum emissions, etc. Those system parameters will also become parameters in our model of the designed product. In the system design phase we specify the architecture of the system, i.e., the main components in the system and their interactions. If we have a simulation model component library at hand, we can use these library components in the design phase, or otherwise create new components that fit the designed product. This design process iteratively increases the level of detail in the design. A modeling tool that supports hierarchical system modeling and decomposition can help in handling system complexity. The implementation phase wiII realize the product as a physical system and/or as a virtual prototype model in the computer. Here a virtual prototype can be realized before the physical prototype is built, usually for a small fraction of the cost. In the subsystem verification and validation phase, the behavior of the subsystems of the product is verified. The subsystem virtual prototypes can be simulated in the computer and the models corrected if there are problems. In the integration phase the subsystems are connected. Regarding a computer-based system model, the models of the subsystems are connected together in an appropriate way. The whole system can then be simulated, and certain design problems corrected based on the simulation results. The system and model calibration and validation phase validates the model against measurements from appropriate physical prototypes. Design parameters are calibrated, and the design is often optimized to a certain extent according to what is specified in the original requirements. During the last phase, product deployment, which usually only applies to the physical version of the product, the product is deployed and sent to the customer for feedback. In certain cases this can also be applied to virtual prototypes, which can be delivered and put in a computer that is interacting with the rest of the customer physical system in real time, i.e., hardware-in-the-loop simulation. In most cases, experience feedback can be used to tune both models and physical products. All phases of the design process continuously interact with the model and design database, e.g. as depicted at the bottom of Figure 1-6.
1.8 Examples of System Models In this section we briefly present examples of mathematical models from three different application areas, in order to illustrate the power of the Modelica mathematical modeling and simulation technology to be described in the rest of this book: • • •
A thermodynamic system-part of an industrial GTX I00 gas turbine model. A 3D mechanical system with a hierarchical decomposition-an industry robot. A bi.ochemical application -part of the citrate cycle (TeA cycle).
A connection diagram of the power cutoff mechanism of the GTXlOO gas turbine is depicted in Figure 1-8 on page 16, whereas the gas turbine itself is shown in Figure 1-7 below.
16 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Figure 1-7. A schematic picture of the gas turbine GTXIOO. Courtesy Alstom Industrial Turbines AB, Finspang, Sweden.
This connection diagram might not appear as a mathematical model, but behind each icon in the diagram is a model component containing the equations that describe the behavior of the respective component.
Figure 1-8. Detail of power cutofTmechanism in 40 MW GTXlOO gas turbine model. Courtesy Alstom Industrial Turbines AB, Finspang, Sweden. In Figure 1-9 we show a few plots from simulations of the gasturbine, which illustrates how a model can be used to investigate the properties of a given system.
Chapter I Introduction to Modeling and Simulation 17
,
.
. ; : ' : " ' ; .. . 1 . . ' ;
•. ; ..• ;
.
•.• • .
;
;
• -
:
Load cutoff
j .•
FuelSrst-
._.•..
~
.
_
.
._._-_.__._
.
.. j . .
~ ...
Genera ted Po....er
-=
=lill i.L.;'. :..:., '.:.:
.. .., . .
.i :
. 1:
.
UE7
I
.
:.
~ .,
; .
.,
•
.. ,
-. . •
.... ..,
... ; :.
.. •
~._ •• ~ ..• • ~ •
" ,
~ "i • . !".
·· 1
'
. .
. ~ . .~ ..
..i
·:··.t. i i'
.- . ". ~ .
~ . .. ;. ..-.....,.....•.. ..._._.:...; ·1··;···· :;: ;: I ~
....
, ~· ;· , ·· : · · ;·.···;· : t·:··· . . ~ .. . _. .. . . ,,~~
... .
Figure 1-9. Simulation of GTXIOO gas turbine power system cutoff mechanism. Courtesy Alstom Industrial Turbines AB, Finspang, Sweden The second example, the industry robot, illustrates the power of hierarchical model decomposition. The three-dimensional robot, shown to the right of Figure 1-10, is repre sented by a 2D connection diagram (in the middle) . Each part in the connection diagram can be a mechanical component such as a motor or joint, a control system for the robot etc. Components may consist of other components which can in turn can be decomposed. At the bottom of the hierarchy we have model classes containing the actual equations .
'r.1 • ""'- " " ""0 11_1 1,.' 11, ."r_,,,., o ,..,.I. "_ ,,,' 0.1,,1., , ., ., .,..
.
:-:.:::~:=."C".II'
... . 1 ' • • · '
. . . . ...1·
''', ' .e,ot h . I.._.,.
... ,,-.o
1. 1 •
. h
0
II •• U · ,...•
n... ,..., ....h
l 1t
II ·U.
Figure 1-10. Hierarchical model of an industrial robot. Courtesy Martin Otter. The third example is from an entirely different domain-biochemical pathways describing the reactions between reactants , in this particular case describing part of the citrate cycle (TCA cycle) as depicted in Figure 1-9.
18 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Figure 1-11. Biochemical pathway model of part of the citrate cycle (TCA cycle).
1.9 Summary We have briefly presented important concepts such as system, model, experiment, and simulation. Systems can be represented by models, which can be subject to experiments, i.e., simulation. Certain models can be represented by mathematics, so-called mathematical models. This book is about objectoriented component-based technology for building and simulating such mathematical models. There are different classes of mathematical models, e.g. static versus dynamic models. continuous-time versus discrete -time models, etc., depending on the properties of the modeled system, the available information about the system, and the approximations made in the model.
1.10 Literature Any book on modeling and simulation need to define fundamental concepts such as system, model, and experiment. The definitions in this chapter are generally available in modeling and simulation literature, including (Ljung and Glad 1994; Cellier 1991). The quote on system definitions , referring to the pendulum, is from (Ashby 1956). The example of different levels of details in mathematical models of gases presented in Section 1.6 is mentioned in (Hyotynierni 2002). The product design-V process mentioned in Section 1.7 is described in (Stevens, Brook., Jackson, and Arnold 1998; Shumate and Keller 1992). The citrate cycle biochemical pathway part in Figure I-II is modeled after the description in (Michael 1999).
19
Chapter 2 A Quick Tour of Modelica
Modelica is primarily a modeling language that allows specification of mathematical models of complex natural or man-made systems, e.g., for the purpose of computer simulation of dynamic systems where behavior evolves as a function of time. Modelica is also an object-oriented equation-based programming language, oriented toward computational applications with high complexity requiring high performance. The four most important features of Modelica are: •
•
•
•
Modelica is primarily based on equations instead of assignment statements. This permits acausal modeling that gives better reuse of classes since equations do not specify a certain data flow direction. Thus a Modelica class can adapt to more than one data flow context. Modelica has multidomain modeling capability, meaning that model components corresponding to physical objects from several different domains such as, e.g., electrical, mechanical, thermodynamic, hydraulic, biological, and control applications can be described and connected. Modelica is an object-oriented language with a genera.l class concept that unifies classes, generics-known as templates in C++ -and general subtyping into a single language construct. This facilitates reuse of components and evolution of models. Modelica has a strong software component model, with constructs for creating and connecting components. Thus the language is ideally suited as an architectural description language for complex physical systems, and to some extent for software systems.
These are the main properties that make Modelica both powerful and easy to use, especially for modeling and simulation. We will start with a gentle introduction to Modelica from the very beginning.
2.1 Getting Started with Modelica Modelica programs are built from classes, also called models. From a class definition, it is possible to create any number of objects that are known as instances of that class. Think of a class as a collection of blueprints and instructions used by a factory to create objects. In this case the Modelica compiler and run-time system is the factory. A Modelica class contains elements, the main kind being variable declarations, and equation sections containing equations. Variables contain data belonging to instances of the class; they make up the data storage of the instance. The equations of a class specify the behavior of instances of that class. There is a long tradition that the first sample program in any computer language is a trivial program printing the string "He 110 Wor Id n. Since Modelica is an equation-based language, printing a string does not make much sense. Instead, our Hello World Modelica program solves a trivial differential equation:
20 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica (2-1)
The variable x in this equation is a dynamic variable (here also a state variable) that can change value over time. The time derivative is the time derivative of x, represented as der (x) in Modelica. Since all Modelica programs, usually called models, consist of class declarations, our HelloWorld program is declared as a class:
x
class HelloWorld Real x(start = 1); parameter Real a = 1; equation der(x) = -a*xi end HelloWorld;
Use your favorite text editor or Modelica programming environment to type in this Modelica code", or open the DrModelica electronic document containing all examples and exercises in this book. Then invoke the simulation command in your Modelica environment. This will compile the Modelica code to some intermediate code, usually C code, which in tum will be compiled to machine code and executed together with a numerical ordinary differential equation (ODE) solver or differential algebraic equation (DAE) solver to produce a solution for x as a function of time. The following command in the MathModelica or OpenModelica environments produces a solution between time 0 and time 2: simulateS (HelloWorld ,stopTime=2) Since the solution for x is a function of time, it can be plotted by a plot command: plot 6 (x) (or the longer form plot (x, xrange= (o 12}) that specifies the x-axis), giving the curve in Figure 2-1: 1.0
0.8 0.6 0.4 0.2
0.5
1.5
2
Figure 2-1. Plot of a simulation of the simple HelloWorld model. Now we have a small Modelica model that does something, but what does it actually mean? The program contains a declaration of a class called HelloWorld with two variables and a single equation. The first attribute of the class is the variable x, which is initialized to a start value of I at the time when the simulation starts. All variables in Modelica have a start attribute with a default value which is normally set to O. Having a different start value is accomplished by providing a so-called modifier
4 There
is a Modelica environment called MathModelica from MathCore (www.mathcore.com). Dymola from Dynasim (www.dynasim.se). and OpenModelica from Linkoping University (www.ida.liu.sellabs/pelab/modelica). S simulate is the MathModelica Modelica-style and OpenModelica command for simulation. The corresponding MathModelica Mathematica-style command for this example, would be Simulate [HelloWorld, {t, O,2}], and in Dymola simulateModel ("HelloWorld", stopTime==2). 6 plot is the MathModelica Modelica-style command for plotting simulation results. The corresponding MathModelica Mathematica-style and Dymola commands would be PlotSimulation [x [t], {t, 0, 2} J, and plot ({ "X"}) respectively.
Chapter 2 A Quick Tour of Modelica 21
within parentheses after the variable name, i.e., a modification equation setting the start attribute to 1 and replacing the original default equation for the attribute. The second attribute is the variable a, which is a constant that is initialized to 1 at the beginning of the simulation. Such a constant is prefixed by the keyword parameter in order to indicate that it is constant during simulation but is a model parameter that can be changed between simulations, e.g., through a command in the simulation environment. For example, we could rerun the simulation for a different value of a. Also note that each variable has a type that precedes its name when the variable is declared. In this case both the variable x and the "variable" a have the type Real. The single equation in this He lloWor ld example specifies that the time derivative of x is equal to the constant - a times x. In Modelica the equal sign = always means equality, i.e., establishes an equation, and not an assignment as in many other languages. Time derivative of a variable is indicated by the pseudofunction der ( ). Our second example is only slightly more complicated,containing five rather simple equations (2-2):
.
Y
mv =-- F -mg Y
L
(2-2)
x=v x y =v y x 2 + y2 = L2 This example is actually a mathematical model of a physical system, a planar pendulum, as depicted in Figure 2-2.
"..
.................
Figure 2-2. A planar pendulum.
The equations are Newton's equations of motion for the pendulum mass under the influence of gravity, together with a geometric constraint, the 5th equation x 2 + y2 = L2 , that specifies that its position (x,y) must be on a circle with radius L. The variables v x and v y are its velocities in the x and y directions respectively. The interesting property of this model, however, is the fact that the 5th equation is of a different kind: a so-called algebraic equation only involving algebraic formulas of variables but no derivatives. The first four equations of this model are differential equations as in the HelloWorld example. Equation systems that contain both differential and algebraic equations are called differential algebraic equation systems (DAEs). A Modelica model of the pendulum appears below: class Pendulum "Planar Pendulum" constant Real PI=3.141592653589793; parameter Real m=l, g=9.81, L=O.S; Real Fj output Real x(start=O.5) ,y(start=O};
22 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
output Real VX,VYi equation m*der(vx)=-(x/L)*Fi m*der(vy)=-(y/L)*F-m*gi der(x)=vxi der(y)=VYi x A2 +y A2 =L A2 ;
end Pendulum; We simulate the Pendulum model and plot the x-coordinate, shown in Figure 2-3:
simulate (Pendulum, stopTime=4) plot(X)i
+--+----o.f----+------+-~I---t
4
-0.2 -0.4
Figure 2-3. Plot of a simulation of the Pendulum DAB (differential algebraic equation) model. You can also write down DAE equation systems without physical significance, with equations containing formulas selected more or less at random, as in the class DAEexample below:
class DAEexample Real x(start=0.9)i Real Yi equation der(y) + (1+0.S*sin(y»*der(x) x-y = exp(-0.9*x)*cos(y); end DAEexample;
sin(time)i
This class contains one differential and one algebraic equation. Try to simulate and plot it yourself, to see if any reasonable curve appears! Finally, an important observation regarding Modelica models: •
The number of variables must be equal to the number of equations!
This statement is true for the three models we have seen so far, and holds for all solvable Modelica models. By variables we mean something that can vary, i.e., not named constants and parameters to be described in Section 2.1.3, page 24.
2.1.1 Variables This example shows a slightly more complicated model, which describes a Van der poe oscillator. Notice that here the keyword model is used instead of class with almost the same meaning.
model Van,DerPol "Van der Pol oscillator model" Real x(start = 1) "Descriptive string for x"; Real y(start = 1) "Descriptive string for y"; parameter Real lambda = 0.3; equation
II x starts at 1 II y starts at 1
7 Balthazar van der Pol was a Dutch electrical engineer who initiated modem experimental dynamics in the laboratory during the 1920's and 1930' s. Vander Pol investigated electrical circuits employing vacuum tubes and found that they have stable oscillations, now called limit cycles. The van der Pol oscillator is a model developed by him to describe the behavior of nonlinear vacuum tube circuits
Chapter 2 A Quick Tour of Modelica
der(x) = Yi der(y) = -x + lambda*(l - x*x)*y; end VanDerPol;
23
II This is the first equation /* The 2nd differential equation */
This example contains declarations of two dynamic variables (here also state variables) x and y, both of type Real and having the start value 1 at the beginning of the simulation, which normally is at time o. Then follows a declaration of the parameter constant lambda, which is a so-called model parameter. The keyword parameter specifies that the variable is constant during a simulation run, but can have its value initialized before a run, or between runs. This means that parameter is a special kind of constant, which is implemented as a static variable that is initialized once and never changes its value during a specific execution. A parameter is a constant variable that makes it simple for a user to modify the behavior of a model, e.g., changing the parameter lambda which strongly influences the behavior of the Van der Pol oscillator. By contrast, a fixed Modelica constant declared with the prefix constant never changes and can be substituted by its value wherever it occurs. Finally we present declarations of three dummy variables just to show variables of data types different from Real: the boolean variable bb, which has a default start value of false if nothing else is specified, the string variable dummy which is always equal to "dummy string", and the integer variable fooint always equal to o. Boolean bb; String dummy = "dummy string"; Integer fooint = Oi
Modelica has built-in "primitive" data types to support floating-point, integer, boolean, and string values. These primitive types contain data that Modelica understands directly, as opposed to class types defined by programmers. The type of each variable must be declared explicitly. The primitive data types of Modelica are: Boolean Integer Real String enumeration( ... )
either true or false corresponding to the C int data type, usually 32-bit two's complement corresponding to the C double data type, usually 64-bit floating-point string of text characters enumeration type of enumeration literals
Finally, there is an equation section starting with the keyword equation, containing two mutually dependent equations that define the dynamics of the model. To illustrate the behavior of the model, we give a command to simulate the Van der Pol oscillator during 25 seconds starting at time 0: simulate (VanDerPol, stopTime=2S)
A phase plane plot of the state variables for the Van der Pol oscillator model (Figure 2-4): plotParametric(x,y, stopTime=2S)
Figure 2-4. Parametric plot of a simulation of the Vander Pol oscillator model.
24 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica The names of variables, functions, classes, etc. are known as identifiers. There are two forms in Modelica. The most common form starts with a letter, followed by letters or digits, e.g. x2. The second form starts with a single-quote, followed by any characters, and terminated by a single-quote, e.g. '2nd*3'.
2.1.2 Comments Arbitrary descriptive text, e.g., in English, inserted throughout a computer program, are comments to that code. Modelica has three styles of comments, all illustrated in the previous VanDerPol example. Comments make it possible to write descriptive text together with the code, which makes a model easier to use for the user, or easier to understand for programmers who may read your code in the future. That programmer may very well be yourself, months or years later. You save yourself future effort by commenting your own code. Also, it is often the case that you find errors in your code when you write comments since when explaining your code you are forced to think about it once more. The first kind of comment is a string within string quotes, e.g., "a comment", optionally appearing after variable declarations, or at the beginning of class declarations. Those are "definition comments" that are processed to be used by the Modelica programming environment, e.g., to appear in menus or as help texts for the user. From a syntactic point of view they are not really comments since they are part of the language syntax. In the previous example such definition comments appear for the VanDerPol class and for the x and y variables. The other two types of comments are ignored by the Modelica compiler, and are just present for the benefit of Modelica programmers. Text following / / up to the end of the line is skipped by the compiler, as is text between / * and the next ../. Hence the last type of comment can be used for large sections of text that occupies several lines. Finally we should mention a construct called annotation, a kind of structured "comment" that can store information together with the code, described in Section 2.17.
2.1.3 Constants Constant literals in Modelica can be integer values such as 4, 75, 3078; floating-point values like 3.14159,0.5, 2.735E-I0, 8.6835e+5; string values such as "hello world", "red"; and enumeration values such as Colors. red, Sizes. xlarge. Named constants are preferred by programmers for two reasons. One reason is that the name of the constant is a kind of documentation that can be used to describe what the particular value is used for. The other, perhaps even more important reason, is that a named constant is defined at a single place in the program. When the constant needs to be changed or corrected, it can be changed in only one place, simplifying program maintenance. Named constants in Modelica are created by using one of the prefixes constant or parameter in declarations, and providing a declaration equation as part of the declaration. For example: constant constant constant parameter
Real String Integer Real
PI = 3.141592653589793; redcolor = "red"; one = 1; mass = 22.5;
Parameter constants can be declared without a declaration equation since their value can be defined, e.g., by reading from a file, before simulation starts. For example: parameter Real mass, gravity, length;
Chapter 2 A Quick Tour of Modelica
25
2.1.4 Default start Values If a numeric variable lacks a specified definition value or start value in its declaration, it is usually initialized to zero at the start of the simulation. Boolean variables have start value false, and string variables the start value empty string vv if nothing else is specified. Exceptions to this rule are function results and local variables in functions, where the default initial value at function call is undefined. See also Section 8.4, page 250.
2.2 Object-Oriented Mathem"atical Modeling Traditional object-oriented programming languages like Simula, C++, Java, and Smalltalk, as well as procedural languages such as Fortran or C, support programming with operations on stored data. The stored data of the program include variable values and object data. The number of objects often changes dynamically. The Smalltalk view of object-orientation emphasizes sending messages between (dynamically) created objects. The Modelica view on object-orientation is different since the Modelica language emphasizes structured mathematical modeling. Object-orientation is viewed as a structuring concept that is used to handle the complexity of large system descriptions. A Modelica model is primarily a declarative mathematical description, which simplifies further analysis. Dynamic system properties are expressed in a declarative way through equations. The concept of declarative programming is inspired by mathematics, where it is common to state or declare what holds, rather than giving a detailed stepwise algorithm on how to achieve the desired goal as is required when using procedural languages. This relieves the programmer from the burden of keeping track of such details. Furthermore, the code becomes m~re concise and easier to change without introducing errors. Thus, the declarative Modelica view of object-orientation, from the point of view of object-oriented mathematical modeling, can be summarized as follows: •
• •
Object-orientation is primarily used as a structuring concept, emphasizing the declarative structure and reuse of mathematical models. Our three ways of structuring are hierarchies, component-connections, and inheritance. Dynamic model properties are expressed in a declarative way through equations". An object is a collection of instance variables and equations that share a set of data.
However: • Object-orientation in mathematical modeling is not viewed as dynamic message passing. The declarative object-oriented way of describing systems and their behavior offered by Modelica is at a higher level of abstraction than the usual object-oriented programming since some implementation details can be omitted. For example, we do not need to write code to explicitly transport data between objects through assignment statements or message passing code. Such code is generated automatically by the Modelica compiler based on the given equations. Just as in ordinary object-oriented languages, classes are blueprints for creating objects. Both variables and equations can be inherited between classes. Function definitions can also be inherited. However, specifying behavior is primarily done through equations instead of via methods. There are also facilities for stating algorithmic code including functions in Modelica, but this is an exception rather than the rule. See alsoChapter 3, page 73 and Chapter 4, page 111 for a discussion regarding object-oriented concepts. Algorithms are also allowed, but in a way that makes it possible to regard an algorithm section as a system of equations.
8
26 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
2.3 Classes and Instances Modelica, like any object-oriented computer language, provides the notions of classes and objects, also called instances, as a tool for solving modeling and programming problems. Every object in Modelica has a class that defines its data and behavior. A class, has three kinds of members: •
• •
Data variables associated with a class and its instances. Variables represent results of computations caused by solving the equations of a class together with equations from other classes. During numeric solution of time-dependent problems, the variables stores results of the solution process at the current time instant. Equations specify the behavior of a class. The way in which the equations interact with equations from other classes determines the solution process, i.e., program execution. Classes can be members of other classes.
Here is the declaration of a simple class that might represent a point in a three-dimensional space: class Point "Point in a three-dimensional space" public Real X; Real y, z; end Point;
The Point class has three variables representing the x, y, and z coordinates of a point and has no equations. A class declaration .like this one is like a blueprint that defines how instances created from that class look like, as well as instructions in the form of equations that define the behavior of those objects. Members of a class may be accessed using dot ( .) notation. For example, regarding an instance myPoint of the Point class, we can access the x variable by writing myPoint . x. Members of a class can have two levels of visibility. The public declaration of x, v, and z, which is default if nothing else is specified, means that any code with access to a Point instance can refer to those values. The other possible level of visibility, specified by the keyword protected, means that only code inside the class as well as code in classes that inherit this class, are allowed access. Note that an occurrence of one of the keywords public or protected means that all member declarations following that keyword assume the corresponding visibility until another occurrence of one of those keywords, or the end of the class containing the member declarations has been reached.
2.3.1 Creating Instances In Modelica, objects are created implicitly just by declaring instances of classes. This is in contrast to object-oriented languages like Java or C++, where object creation is specified using the new keyword. For example, to create three instances of our Point class we just declare three variables of type Point in a class, here Triangle: class Triangle Point point!; Point point2; Point point3; end Triangle;
There is one remaining problem, however. In what context should Triangle be instantiated, and when should it just be interpreted as a library class not to be instantiated until actually used? This problem is solved by regarding the class at the top of the instantiation hierarchy in the Modelica program to be executed as a kind of "main" class that is always implicitly instantiated, implying that its variables are instantiated, and that the variables of those variables are instantiated, etc. Therefore, to instantiate Triangle, either make the class Triangle the "top" class or declare an instance of
Chapter 2 A Quick Tour of Modelica 27
Triangle in the "main" class. In the following example, both the class Triangle and the class Fool are instantiated.
class Fool end Fool; class Foo2 end Foo2; class Triangle Point pointl; Point point2; Point
point3;
end Trianglei class Main Triangle Fool end Main;
pts; fli
The variables of Modelica classes are instantiated per object. This means that a variable in one object is distinct from the variable with the same name in every other object instantiated from that class. Many object-oriented languages allow class variables. Such variables are specific to a class as opposed to instances of the class, and are shared among all objects of that class. The notion of class variables is not yet available in Modelica.
2.3.2 Initialization Another problem is initialization of variables. As mentioned previously in Section 2.1.4, page 25, if nothing else is specified, the default start value of all numerical variables is zero, apart from function results and local variables where the initial value at call time is unspecified. Other start values can be specified by setting the start attribute of instance variables. Note that the start value only gives a suggestion for initial value-the solver may choose a different value unless the £ ixed attribute is true for that variable. Below a start value is specified in the example class Triangle:
class Triangle Point pointl(start={1,2,3}); Point point2; Point point3; end Triangle;
Alternatively, the start value of point 1 can be specified when instantiating Triangle as below:
class Main Triangle Fool end Main;
pts(pointl.start={l,2,3}); £1;
A more general way of initializing a set of variables according to some constraints is to specify an equation system to be solved in order to obtain the initial values of these variables. This method is supported in Modelica through the initial equation construct. An example of a continuous-time controller initialized in steady-state, i.e., when derivatives should be zero, is given below:
model Controller Real Yi equation
28 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica der(y} = a*y + b*u; initial equation der(y)=O; end Controller;
This has the following solution at initialization: der(y) = 0; y = -(b/a)*u;
For more information, see Section 8.4, page 250.
2.3.3 Restricted Classes The class concept is fundamental to Modelica, and is used for a number of different purposes. Almost anything in Modelica is a class. However, in order to make Modelica code easier to read and maintain, special keywords have been introduced for specific uses of the class concept. The keywords model, connector, record, block, and type can be used instead of class under appropriate conditions. For example, a record is a class used to declare a record data structure and may not contain equations. record Person Real age; String name; end Person;
A block is a class with fixed causality, which means that for each member variable of the class it is specified whether it has input or output causality. Thus, each variable in a block class interface must be declared with a causality prefix keyword of either input or output. A connector class is used to declare the structure of "ports" or interface points of a component and may not contain equations. A type is a class that can be an alias or an extension to a predefined type, record, or array. For example: type vector3D
= Real [3]
;
Since restricted classes are just specialized versions of the general class concept, these keywords can be replaced by the class keyword for a valid Modelica model without changing the model behavior. The idea of restricted classes is beneficial since the user does not have to learn several different concepts, except for one: the class concept. The notion of restricted classes gives the user a chance to express more precisely what a class is intended for, and requires the Modelica compiler to check that these usage constraints are actually fulfilled. Fortunately the notion is quite uniform since all basic properties of a class, such as the syntax and semantics of definition, instantiation, inheritance, and generic properties, are identical for all kinds of restricted classes. Furthermore, the construction of Modelica translators is simplified because only the syntax and semantics of the class concept have to be implemented along with some additional checks on restricted classes. The package and function concepts in Modelica have much in common with the class concept but are not really restricted classes since these concepts carry additional special semantics of their own. See also Section 3.8, page 81, regarding restricted classes.
2.3.4 Reuse of Modified Classes The class concept is the key to reuse of modeling knowledge in Modelica. Provisions for expressing adaptations or modifications of classes through so-called modifiers in Modelica make reuse easier. For example, assume that we would like to connect two filter models with different time constants in series.
Chapter2 A QuickTourof Modelica 29
Instead of creating two separate filter classes, it is better to define a common filter class and create two appropriately modified instances of this class, which are connected. An example of connecting two modified low-pass filters is shown after the example low-pass filter class below: model LowPassFilter parameter Real T=l "Time constant of filter"; Real u, y(start=l); equation T*der(y) + y = U; end LowPassFilter;
The model class can be used to create two instances of the filter with different time constants and "connecting" them together by the equation F2 . u = F'1. Y as follows: model FilterslnSeries LowPassFilter Fl(T=2), equation Fl.u = sin(time); F2.u = Fl.Yi end FilterslnSeriesi
F2(T=3)i
Here we have used modifiers, i.e., attribute equations such as T=2 and T=3, to modify the time constant of the low-pass filter when creating the instances Fl and F2. The independent time variable is denoted time. If the FilterslnSeries model is used to declare variables at a higher hierarchical level, e.g., F12, the time constants can still be adapted by using hierarchical modification, as for Fl and F2 below: model ModifiedFilterslnSeries FilterslnSeries F12(Fl(T=6), F2.T=11}; end ModifiedFilterslnSeries;
See also Chapter 4, page 111.
2.3.5 Built-in Classes The built-in type classes of Modelica correspond to the primitive types Real, Integer, Boolean, String, and enumeration(...), and have most of the properties of a class, e.g., can be inherited, modified, etc. Only the value attribute can be changed at run-time, and is accessed through the variable name itself, and not through dot notation, i.e., use x and not x. value to access the value. Other attributes are accessed through dot notation. For example, a Real variable has a set of default attributes such as unit of measure, initial value, minimum and maximum value. These default attributes can be changed when declaring a new class, for example: class Voltage
=
Real(unit= "V", min=-220.0, max=220.0);
See also Section 3.9, page 84.
2.4
Inheritance
One of the major benefits of object-orientation is the ability to extend the behavior and properties of an existing class. The original class, known as the superclass or base class, is extended to create a more specialized version of that.class, known as the subclass or derived class. In this process, the behavior and properties of the original class in the form of variable declarations, equations, and other contents are reused, or inherited, by the subclass. Let us regard an example of extending a simple Modelica class, e.g., the class Point introduced previously. First we introduce two classes named ColorData and Color, where Color inherits the
30 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica data variables to represent the color from class ColorData and adds an equation as a constraint. The new class ColoredPoint inherits from multiple classes, i.e., uses multiple inheritance, to get the position variables from class Point, and the color variables together with the equation from class Color. record ColorData Real red; Real blue; Real green; end ColorData; class Color extends ColorData; equation red + blue + green end Color;
1;
class Point public Real X; Real y, z; end Point; class ColoredPoint extends Point; extends Color; end ColoredPoint;
See also Chapter 4, page Ill, regarding inheritance and reuse.
2.5
Generic Classes
In many situations it is advantageous to be able to express generic patterns for models or programs. Instead of writing many similar pieces of code with essentially the same structure, a substantial amount of coding and software maintenance can be avoided by directly expressing the general structure of the problem and providing the special cases as parameter values. Such generic constructs are available in several programming languages, e.g., templates in C++, generics in Ada, and type parameters in functional languages such as Haskell or Standard ML. In Modelica the class construct is sufficiently general to handle generic modeling and programming in addition to the usual class functionality. There are essentially two cases of generic class parameterization in Modelica: class parameters can either be instance parameters, i.e., have instance declarations (components) as values, or be type parameters, i.e., have types as values. Note that by class parameters in this context we do not usually mean model parameters prefixed by the keyword parameter, even though such "variables" are also a kind of class parameter. Instead we mean formal parameters to the class. Such formal parameters are prefixed by the keyword replaceable. The special case of replaceable local functions is roughly equivalent to virtual methods in some object-oriented programming languages. See also Section 4.4, page 133.
2.5.1 Class Parameters Being Instances First we present the case when class parameters are variables, i.e., declarations of instances, often called components. The class C in the example below has three class parameters marked by the keyword replaceable. These class parameters, which are components (variables) of class C, are declared as
Chapter2 A Quick Tourof Modelica 31
having the (default) types GreenClass, YellowClass, and GreenClass respectively. There is also a red object declaration which is not replaceable and therefore not a class parameter (Figure 2-5). dassC
@] object
pobjt
I
pobj2
pobjJ
obj4
Figure 2-5. Three class parameters pobj 1, pobj 2, and pobj 3 that are instances (variables) of class C. These are essentially slots that can contain objects of different colors.
Here is the class C with its three class parameters pobj 1, pobj2, and pobj3 and a variable obj4 that is not a class parameter: class C replaceable replaceable replaceable RedClass equation
GreenClass pobjl(p1=5) YellowClass pobj2; GreenClass pobj3i obj4;
i
end C;
Now a class C2 is defined by providing two declarations of pobj 1 and pobj 2 as actual arguments to class C, being red and green respectively, instead of the defaults green and yellow. The keyword redeclare must precede an actual argument to a class formal parameter to allow changing its type. The requirement to use a keyword for a redeclaration in Modelica has been introduced in order to avoid accidentally changing the type of an object through a standard modifier. In general. the type of a class component cannot he changed if it is not declared as replaceable and a redeclaration is provided. A variable in a redeclaration can replace the original variable if it has a type that is a subtype of the original type or its type constraint. It is also possible to declare type constraints (not shown here) on the substituted classes. class C2 = C(redeclare RedClass pobjl, redeclare GreenClass pobj2) ;
Such a class C2 obtained through redeclaration of pobj 1 and pobj 2 is of course equivalent to directly defining C2 without reusing class C, as below. class C2 RedClass GreenClass GreenClass RedClass equation
pobjl(pl=5); pobj2; pobj3; obj4;
end C2;
2.5.2 Class Parameters being Types A class parameter can also be a type, which is useful for changing the type of many objects. For example, by providing a type parameter ColoredClass in class C below, it is easy to change the color of all objects of type ColoredClass. class C replaceable class ColoredClass
GreenClass;
32 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica ColoredClass replaceable YellowClass ColoredClass RedClass equation
objl(pl=5); obj2; obj3; obj4;
end C;
Figure 2-6 depicts how the type value of the ColoredClass class parameter is propagated to the memberobject declarations obj 1 and obj 3.
ColoredClass
Colored-
ColoredClass object
Class
object obj1
obj2
obj3
@] object obj4
Figure 2-6.Theclassparameter ColoredClass is a type parameter thatis propagated to the two member instance declarations of objl andobj3. We create a class C2 by giving the type parameter ColoredClass of class c the value BlueClass. class C2
= C(redeclare
class ColoredClass = BlueClass);
This is equivalentto the following definitionof C2: class C2 BlueClass YellowClass BlueClass RedClass equation
objl(pl=5); obj2; obj3; obj4;
end C2i
2.6
Equations
As we already stated, Modelica is primarily an equation-based language in contrast to ordinary programming languages, where assignment statements proliferate. Equations are more flexible than assignments since they do not prescribe a certain data flow direction or executionorder. This is the key to the physical modeling capabilities and increasedreuse potentialof Modelicaclasses. Thinking in equationsis a bit unusual for most programmers. In Modelicathe following holds: • • •
Assignment statements in conventional languages are usually represented as equations in Modelica. Attributeassignments are represented as equations. Connections betweenobjectsgenerateequations.
Equations are more powerful than assignment statements. For example, consider a resistor equation wherethe resistance R multiplied by the current i is equal to the voltage v: R*i =
Vi
Chapter 2 A Quick Tour of Modelica 33
This equation can be used in three ways corresponding to three possible assignment statements: computing the current from the voltage and the resistance, computing the voltage from the resistance and the current, or computing the resistance from the voltage and the current. This is expressed in the following three assignment statements: i
:= :=
viR; R*i; R := vii;
v
Equations in Modelica can be informally classified into four different groups depending on the syntactic context in which they occur: •
Normal equations occurring in equation sections, including the connect equation, which is a
• • •
Declaration equations, which are part of variable or constant declarations. Modification equations, which are commonly used to modify attributes. Initial equations, specified in initial equation sections or as start attribute equations. These
special form of equation.
equations are used to solve the initialization problem at startup time. As we already have seen in several examples, normal equations appear in equation sections started by the keyword equation and terminated by some other allowed keyword: equation <equations> <some other allowed keyword>
The above resistor equation is an example of a normal equation that can be placed in an equation section. Declaration equations are usually given as part of declarations of fixed or parameter constants, for example: constant Integer one = 1; parameter Real mass = 22.5;
An equation always holds, which means that the mass in the above example never changes value during simulation. It is also possible to specify a declaration equation for a normal variable,e.g.: Real speed = 72.4;
However, this does not make much sense since it will constrain the variable to have the same value throughout the computation, effectively behaving as a constant. Therefore a declaration equation is quite different from a variable initializer in other languages. Concerning attribute assignments, these are typically specified using modification equations. For example, if we need to specify an initial value for a variable, meaning its value at the start of the computation, then we give an attribute equation for the start attribute of the variable,e.g.: Real speed(start=72.4);
See also Chapter 8, page 237, for a completeoverview of equations in Modelica.
2.6.1 Repetitive Equation Structures Before reading this section you might want to take a look at Section 2.13 about arrays, page 44, and Section 2.14.2 about statements and algorithmicfor-loops, page 46. Sometimes there is a need to conveniently express sets of equations that have a regular, i.e., repetitive structure. Often this can be expressed as array equations, including references to array
34 Peter Fritzson Principlesof Object-Oriented Modelingand Simulationwith Modelica elements denoted using square bracket notation", However, for the more general case of repetitive equation structures Modelica provides a loop construct. Note that this is not a loop in the algorithmic sense of the word-it is rather a shorthand notation for expressing a set of equations. For example, consider an equation for a polynomial expression: y
= a[1]+a(2]*x + a[3)*x
A2
+ ... + a[n+1)*x An
The polynomial equation can be expressed as a set of equations with regular structure in Modelica, with yequal to the scalar product of the vectors a and xpowers, both of length n-s1: xpowers[1] xpowers[2] xpowers[3]
=
=
1; xpowers[1]*xi xpowers{2]*xi
xpowers[n+1] = xpowers[n]*xi y = a * xpowers;
The regular set of equations involving xpowers can be expressed more conveniently using the for loop notation: for i in 1:n loop xpowers[i+1] = xpowers[ij*xi end for;
In this particular case a vector equation provides an even more compact notation: xpowers[2:n+1] = xpowers[1:n]*x;
Here the vectors x and xpowers have length n+1. The colon notation 2 :n+1 means extracting a vector of length n, starting from element 2 up to and including element n+ 1.
2.6.2 Partial Differential Equations Partial differential equations (abbreviated PDEs) contain derivatives with respect to other variables than time, for example of spatial Cartesian coordinates such as x and y. Models of phenomena such as heat flow or fluid flow typically involve PDEs. At the time of this writing PDE functionality is not part of the official Modelica language, but is in the process of being included. See Section 8.5, page 258, for an overview of the most important current design proposals which to some extent have been evaluated in test implementations.
2.7
Acausal Physical Modeling
Acausal modeling is a declarative modeling style, meaning modeling based on equations instead of assignment statements. Equations do not specify which variables are inputs and which are outputs, whereas in assignment statements variables on the left-hand side are always outputs (results) and variables on the right-hand side are always inputs. Thus, the causality of equation-based models is unspecified and becomes fixed only when the corresponding equation systems are solved. This is called acausal modeling. The term physical modeling reflects the fact that acausal modeling is very well suited for representing the physical structure of modeled systems. The main advantage with acausal modeling is that the solution direction of equations will adapt to the data flow context in which the solution is computed. The data flow context is defined by stating which variables are needed as outputs, and which are external inputs to the simulated system.
9
For more information regardingarrays see Chapter 7, page 207.
Chapter 2 A Quick Tour of Modelica 35
The acausality of Modelica library classes makes these more reusable than traditional classes containing assignment statements where the input-output. causality is fixed.
2.7.1 Physical Modeling vs. Block-Oriented Modeling To illustrate the idea of acausal physical modeling we give an example of a simple electrical circuit (Figure 2-7). The connection diagram'? of the electrical circuit shows how the components are connected. It may be drawn with component placements to roughly correspond to the physical layout of the electrical circuit on a printed circuit board. The physical connections in the real circuit correspond to the logical connections in the diagram. Therefore the term physical modeling is quite appropriate.
R2=100
l=O.1 n
Figure 2-7. Connection diagram of the acausal simple circuit model.
The Modelica SimpleCircuit model below directly corresponds to the circuit depicted in the connection diagram of Figure 2-7. Each graphic object in the diagram corresponds to a declared instance in the simple circuit model. The model is acausal since no signal flow, i.e., cause-and-effect flow, is specified. Connections between objects are specified using the connect equation. construct, which is a special syntactic form of equation that we will examine later. The classes Resistor, Capacitor, Inductor, VsourceAC, and Ground will be presented in more detail on pages 40 to 43. model SimpleCircuit Resistor Rl(R=lO)i Capacitor C(C=O.Ol) ; Resistor R2(R=lOO); Inductor L(L=O.l); VsourceAC AC; Ground G; equation connect (AC.p, Rl.p); connect (Rl.n, C.p); connect (C.n, AC.n); connect (Rl.p, R2.p); connect (R2.n, L.p); connect (L.n, C.n); connect (AC.n, G.p);
II Capacitor circuit II Inductor circuit II Ground
10 A connection diagram emphasizes the connections between components of a model, whereas a composition diagram specifies which components a model is composed of, their subcomponents, etc. A class diagram usually depicts inheritance and composition relations.
36 Peter Fritzson Principlesof Object-Oriented Modelingand Simulationwith Modelica end SimpleCircuiti As a comparison we show the same circuit modeled using causal block-oriented modeling depicted as a diagram in Figure 2-8. Here the physical topology is lost-the structure of the diagram has no simple correspondence to the structure of the physical circuit board. This model is causal since the signal flow has been deduced and is clearly shown in the diagram. Even for this simple example the analysis to convert the intuitive physical model to a causal block-oriented model is nontrivial. Another disadvantage is that the resistor representations are context dependent. For example, the resistors Rl and R2 have different definitions, which makes reuse of model library components hard. Furthermore, such system models are usually hard to maintain since even small changes in the physical structure may result in large changes to the corresponding block-oriented system model.
sum2
Figure 2-8 The simple circuit model using causal block-orientedmodelingwith explicit signal flow.
2.8 The Modelica Software Component Model For a long time, software developers have looked with envy on hardware system builders, regarding the apparent ease with which reusable hardware components are used to construct complicated systems. With software there seems too often to be a need or tendency to develop from scratch instead of reusing components. Early attempts at software components include procedure libraries, which unfortunately have too limited applicability and low flexibility. The advent of object-oriented programming has stimulated the development of software component frameworks such as CORBA, the Microsoft COMIDCOM component object model, and JavaBeans. These component models have considerable success in certain application areas, but there is still a long way to go to reach the level of reuse and component standardization found in hardware industry. The reader might wonder what all this has to do with Modelica. In fact, Modelica offers quite a powerful software component model that is on par with hardware component systems in flexibility and potential for reuse. The key to this increased flexibility is the fact that Modelica classes are based on equations. What is a software component model? It should include the following three items: 1. Components 2. A connection mechanism 3. A component framework Components are connected via the connection mechanism, which can be visualized in connection diagrams. The component framework realizes components and connections, and ensures that communication works and constraints are maintained over the connections. For systems composed of
Chapter2 A QuickTour of Modelica 37
acausal components the direction of data flow, i.e., the causality is automatically deduced by the compiler at composition time. See also Chapter 5, page 145, for a complete overview of components, connectors, and connections.
2.8.1 Components Components are simply instances of Modelica classes. Those classes should have well-defined interfaces, sometimes called ports, in MOOeHca caUed connectors, for communication and coupling between a component and the outside world. A component is modeled independently of the environment where it is used, which is essential for its reusability. This means that in the definition of the component including its equations, only local variables and connector variables can be used. No means of communication between a component and the rest of the system, apart from going via a connector, should be allowed. However, in Modelica access of component data via dot notation is also possible. A component may internally consist of other connected components, i.e., hierarchical modeling.
2.8.2 Connection Diagrams Complex systems usually consist of large numbers of connected components, of which many components can be hierarchically decomposed into other components through several levels. To grasp this complexity, a pictorial representation of components and connections is quite important. Such graphic representation is available as connection diagrams, of which a schematic example is shown in Figure 2-9. We have earlier presented a connection diagram of a simple circuit in Figure 2-7. component2
Figure 2-9. Schematic picture of a connection diagram for components.
Each rectangle in the diagram example represents a physical component, e.g., a resistor, a capacitor, a transistor, a mechanical gear, a valve, etc. The connections represented by lines in the diagram correspond to real, physical connections. For example, connections can be realized by electrical wires, by the mechanical connections, by pipes for fluids, by heat exchange between components, etc. The connectors, i.e., interface points, are shown as small square dots on the rectangle in the diagram. Variables at such interface points define the interaction between the component represented by the rectangle and other components. Front wheels
controller
Figure 2-10. A connection diagram for a simple car model.
38 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica A simple car example of a connection diagram for an application in the mechanical domain is shown in Figure 2-10. The simple car model below includes variables for subcomponents such as wheels, chassis, and control unit. A "comment" string after the class name briefly describes the class. The wheels are connected to both the chassis and the controller. Connect equations are present, but are not shown in this partial example. class Car "A car class to combine car components" Wheel wl,w2,w3,w4 "Wheel one to four"; Chassis chassis "Chassis"; CarController controller "Car controller"; end Car;
2.8.3 Connectors and Connector Classes Modelica connectors are instances of connector classes, which define the variables that are part of the communication interface that is specified by a connector. Thus, connectors specify external interfaces for interaction. For example, Pin is a connector class that can be used to specify the external interfaces for electrical components (Figure 2-11) that have pins. The types Voltage and Current used within Pin are the same as Real, but with different associated units. From the Modelica language point of view the types Voltage and Current are similar to Real, and are regarded as having equivalent types. Checking unit compatibility within equations is optional. type Voltage type Current
Real(unit="V"); Real(unit="A");
Figure 2-11. A component with one electrical Pin connector. The Pin connector class below contains two variables. The flow prefix on the second variable indicates that this variable represents a flow quantity, which has special significance for connections as explained in the next section. connector Pin
Voltage flow Current end Pin;
V;
i;
2.8.4 Connections Connections between components can be established between connectors of equivalent type. Modelica supports equation-based acausal connections, which means that connections are realized as equations. For acausal connections, the direction of data flow in the connection need not be known. Additionally, causal connections can be established by connecting a connector with an output attribute to a connector declared as input. Two types of coupling can be established by connections depending on whether the variables in the connected connectors are nontlow (default), or declared using the f low prefix:
Chapter 2 A Quick Tour of Modelica 39
I. Equality coupling, for nonflow variables, according to Kirchhoff's first law.
2. Sum-to-zero coupling, for flow variables, according to Kirchhoffs current law. For example, the keyword flow for the variable i of type Current in the Pin connector class indicates that all currents in connected pins are summed to zero, according to Kirchhoff's current law.
R1
p
+ R1.p.v
--. R2.p.i
. R1.p.i -
p R2
Figure 2-12. Connecting two components that have electrical pins. Connection equations are used to connect instances of connection classes. A connection equation connect ( Rl. p, R2 . p) , with Rl . P and R2 . P of connector class Pin, connects the two pins (Figure 2-12) so that they form one node. This produces two equations, namely: Rl.p.v = R2.p.v Rl.p.i + R2.p.i
=
0
The first equation says that the voltages of the connected wire ends are the same. The second equation corresponds to Kirchhoff's second law, saying that the currents sum to zero at a node (assuming positive value while flowing into the component). The sum-to-zero equations are generated when the prefix flow is used. Similar laws apply to flows in piping networks and to forces and torques in mechanical systems. See also Section 5.3, page 148, for a complete description of this kind of explicit connections. We should also mention the concept of implicit connections, e.g. useful to model force fields, which is represented by the Modelica inner/outer construct and described in more detail in Section 5.8, page 173.
2.9 Partial Classes A common property of many electrical components is that they have two pins. This means that it is useful to define a "blueprint" model class, e.g., called TwoPin, that captures this common property. This is a partial class since it does not contain enough equations to completely specify its physical behavior, and is therefore prefixed by the keyword partial. Partial classes are usually known as abstract classes in other object-oriented languages. partial class TwoPin 1 1 "Superclass of elements with two electrical pins" Pin P, n; Voltage Vj Current i; equation v p.v - n.v; o = p.i + n.i; i = p.i; end TwOPini
The TwoPin class has two pins, p and n, a quantity v that defines the voltage drop across the component, and a quantity i that defines the current into pin p, through the component, and out from pin n 11 This TwoPin class is referredto by the name Modelica. Electrical.Analog. Interfaces .OnePort in the Modelica standard library since this is the nameused by electrical modeling experts. Here we use the more intuitive name Twopin sincethe class is used for components with two physical ports and not one. The One Port namingis more understandable if it is viewed as denoting composite ports containing two subports.
40 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica (Figure 2-13). It is useful to label the pins differently, e.g., p and n, and using graphics, e.g. filled and unfilled squares respectively, to obtain a well-defined sign for v and i although there is no physical difference between these pins in reality.
v
Figure 2-13.Generic TwoPin class that describes the generalstructure of simpleelectrical components with two pins. The equations define generic relations between quantities of simple electrical components. In order to be useful, a constitutive equation must be added that describes the specific physical characteristics of the component.
2.9.1 Reuse of Partial Classes Given the generic partial class TwoPin, it is now straightforward to create the more specialized Resistor class by adding a constitutive equation: R*i = v;
This equation describes the specific physical characteristics of the relation between voltage and current for a resistor (Figure 2-14).
~~....p
R
v
n-.l~
Figure 2-14. A resistor component. class Resistor "Ideal electrical resistor" extends TwoPini
parameter Real R(unit="Ohm") "Resistance"i equation R*i = Vi end Resistor;
A class for electrical capacitors can also reuse TwoPin in a similar way, adding the constitutive equation for a capacitor (Figure 2-15). C
~~ I
V
Figure 2-15. A capacitorcomponent. class Capacitor "Ideal electrical capacitor" extends TwoPini parameter Real C(Unit="F") "Capacitance"; equation C*der(v) = i; end Capacitor;
Chapter 2 A Quick Tour of Modelica 41
During system simulation the variables i and v specified in the above components evolve as functions of time. The solver of differential equations computes the values of v(t) and i(t) (where t is time) such that C· v(t) = ;(t) for all values of I, fulfilling the constitutive equation for the capacitor.
2.10 Component Library Design and Use In a similar way as we previously created the resistor and capacitor components, additional electrical component classes can be created, forming a simple electrical component library that can be used for application models such as the SimpleCircuit model. Component libraries of reusable components are actually the key to effective modeling of complex systems.
2.11 Example: Electrical Component Library Below we show an example of designing a small library of electrical components needed for the simple circuit example, as well as the equations that can be extracted from these components.
2.11.1 Resistor p.l
+
nJ
P.v~~--..,-~n.v v Figure 2-16. Resistorcomponent. Four equations can be extracted from the resistor model depicted in Figure 2-14 and Figure 2-16. The first three originate from the inherited TwoPin class, whereas the last is the constitutive equation of the resistor. v
=
p.i + n.i p.v - n.v
i v
=
p.i
= R*i
o
=
2.11.2 Capacitor n.i
p.l
--;+I~ p.v
v
•
n.v
Figure 2-17. Capacitorcomponent. The following four equations originate from the capacitor model depicted in Figure 2-15 and Figure 2-17, where the last equation is the constitutive equation for the capacitor.
o = p.i + n.i v = p.v - n.v i p.i i = C * der(v)
42 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
2.11.3 Inductor
Figure 2-18. Inductorcomponent.
The inductor class depicted in Figure 2-18 and shown below gives a model for ideal electrical inductors. class Inductor "Ideal electrical inductor" extends TwoPini parameter Real L(unit="Hn) "Inductance"; equation v = L*der(i); end Inductor; These equations can be extracted from the inductor class, where the first three come from TwoPin as usual and the last is the constitutiveequation for the inductor. 0
v i v
p.i + n.i p.v - n.v p.i L * der(i)
2.11.4 Voltage Source
----.. ..P.i~.i p.v
n.v v
Figure2-19. VoltagesourcecomponentvsourceAC,wherev{t) = VA*sin{2*PI*f*time).
A class VsourceAC for the sin-wave voltage source to be used in our circuit example is depicted in Figure 2-19 and can be defined as below. This model as well as other Modelica models specify behavior that evolves as a function of time. Note that a predefined variable time is used. In order to keep the example simple the constant PI is explicitly declared even though it is usually imported from the Modelica standard library.
class VsourceAC "Sin-wave voltage source" extends Twopini parameter Voltage VA 220 "Amplitude"; parameter Real f(unit="Hz") 50 "Frequency" i 3.141592653589793; constant Real PI equation v = VA*sin(2*PI*f*time) i end VsourceACi
In this Twopin~based model, four equations can be extracted from the model, of which the first three are inherited from TwoPin:
o v i v
p.i + n.i p.v - n.v p.i VA*sin(2*PI*f*time)
Chapter2 A QuickTour of Modelica 43
2.11.5 Ground
:1l:.
i
Figure 2-20. Ground component.
Finally, we define a class for ground points that can be instantiated as a reference value for the voltage levels in electrical circuits. This class has only one pin (Figure 2-20). class Ground "Ground" Pin Pi equation
p.v = 0; end Ground;
A single equation can be extracted from the Ground class. p.v = 0
2.12 The Simple Circuit Model Having collected a small library of simple electrical components we can now put together the simple electrical circuit shown previously and in Figure 2-21.
A2=100
L=O.1
Figure 2-21. The simple circuit model.
The two resistor instances Rl and R2 are declared with modification equations for their respective resistance parameter values. Similarly, an instance c of the capacitor and an instance L of the inductor are declared with modifiers for capacitance and inductance respectively. The voltage source AC and the ground instance G have no modifiers. Connect equations are provided to connect the components in the circuit. class SimpleCircuit Resistor Rl(R=10) i Capacitor C(C=O.Ol)i Resistor R2(R=lOO); Inductor L(L=O.l} i VsourceAC AC;
Ground
G;
44 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica equation connect (AC.p, Rl.p); connect (Rl.n, c.p); connect (C.n, AC.n); connect (Rl.p, R2.p); connect(R2.n, L.p)i connect (L.n, C.n); connect (AC.n, G.p)i end SimpleCircuit;
II 1, Capacitor circuit Wire 2 II Wire 3 II II 2, Inductor circuit Wire 5 II Wire 6 II II 7, Ground
2.13 Arrays An array is a collection of variables all of the same type. Elements of an array are accessed through simple integer indexes, ranging from a lower bound of 1 to an upper bound being the size of the respective dimension. An array variable can be declared by appending dimensions within square brackets after a class name, as in Java, or after a variable name, as in the C language. For example:
Real [3] positionvector Real [3,3] identi tymatrix Real[3,3,3] arr3d;
{1,2,3};
= {{ 1, O,O}, {O, 1, O}, {O, 0, i
)};
This declares a three-dimensional position vector, a transformation matrix, and a three-dimensional array. Using the alternative syntax of attaching dimensions after the variable name, the same declarations can be expressed as:
Real positionvector[3] = {1,2,3}; Rea l ident i t yma trix [3 , 3] = {{ 1 , 0 , 0 }, { 0 , 1 , 0 }, {O , 0 , 1 } } ; Real arr3d[3,3,3];
In the first two array declarations, declaration equations have been given, where the array constructor {} is used to construct array values for defining positionvector and identitymatrix. Indexing of an array A is written A [i, j, ... ] , where 1 is the lower bound and size (A, k) is the upper bound of the index for the kth dimension. Submatrices can be formed by utilizing the : notation for index ranges, for example, A [ i 1 : i 2, j 1 : j 2], where a range i 1 : i 2 means all indexed elements starting with i 1 up to and including i2. Array expressions can be formed using the arithmetic operators +, -, *, and I, since these can operate on either scalars, vectors, matrices, or (when applicable) multidimensional arrays with elements of type Real or Integer. The multiplication operator * denotes scalar product when used between vectors, matrix multiplication when used between matrices or between a matrix and a vector, and element-wise multiplication when used between an array and a scalar. As an example, multiplying positionvector by the scalar 2 is expressed by: positionvector*2 which gives the result: {2,4,6}
In contrast to Java, arrays of dimensionality > 1 in Modelica are always rectangular as in Matlab or Fortran. A number of built-in array functions are available, of which a few are shown in the table below.
transpose (A) zeros(nl,n2,n3, ... ) ones(nl,n2,n3, ... ) fill(s,nl,n2,n3, .. . )
Permutes the first two dimensions of array A. Returns an nt x n2 x 03 x... zero-filled integer array. Returns an nt x 02 x 03 X ••• one-filled integer array. Returns the nt x 02 x n3 x ... array with all elements filled with the
Chapter 2 A Quick Tour of Modelica 45
value of the scalar expression s, R.eturns the smallest element of array expression A. Returns the largest element of array expression A. Returns the sum of all the elements of array expression A.
min (A) max (A) sum (A)
A scalar Modelica function of a scalar argument is automatically generalized to be applicable also to arrays element-wise. For example, if A is a vector of real numbers, then cos (A) is a vector where each element is the result of applying the function cos to the corresponding element in A. For example: cos ( { 1 , 2,
{ cos (1), cos (2),
3})
cos (3) }
General array concatenation can be done through the array concatenation operator cat(k, A, B, C, ... ) that concatenates the arrays A,B,C, ... along the k:th dimension. For example, cat(I,{2,3}, (5,8,4}) gives the result {2,3,5,8,4}. The common special cases of concatenation along the first and second dimensions are supported through the special syntax forms [A; B ; C i • • • ] and [A, B , C, . • . ] respectively. Both of these forms can be mixed. In order to achieve compatibility with Matlab array syntax, being a de facto standard, scalar and vector arguments to these special operators are promoted to become matrices before performing the concatenation. This gives the effect that a matrix can be constructed from scalar expressions by separating rows by semicolons and columns by commas. The example below creates an m X n matrix: [expr 1 1 , expr 1 2 t exp r 2 1 , expr 2 2 ,
expr ml' expr m2 ,
•••
exprl n ; expr 2 n ; exprmnl
It is instructive to follow the process of creating a matrix from scalar expressions using these operators. For example: [1,2 ;
3,4]
First each scalar argument is promoted to become a matrix, giving: [{{I}}, {{2}}i
{{3}}, {{4}}1 Since [... , ...] for concatenation along the second dimension has higher priority than [... ; ...], which concatenates along the first dimension, the first concatenation step gives:
[{{I, 2}}; {{3,4}}]
Finally, the row matrices are concatenated gi ving the desired 2 X 2 matrix:
{{l, 2}, {3, 4}}
The special case of just one scalar argument can be used to create a 1x 1 matrix. For example: [1]
gives the matrix:
{{I}} See also Chapter 7, page 207, for a complete overview of Modelica arrays.
46 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica
2.14 Algorithmic Constructs Even though equations are eminently suitable for modeling physical systems and for a number of other tasks, there are situations where nondeclarative algorithmic constructs are needed. This is typically the case for algorithms, i.e., procedural descriptions of how to carry out specific computations, usually consisting of a number of statements that should be executed in the specified order.
2.14.1 Algorithms In Modelica, algorithmic statements can occur only within algorithm sections, starting with the keyword algor i thm. Algorithm sections may also be called algorithm equations, since an algorithm section can be viewed as a group of equations involving one or more variables, and can appear among equation sections. Algorithm sections are terminated by the appearance of one of the keywords equation, public, protected, algorithm, or end. algorithm
<statements> <some other keyword> An algorithm section embedded among equation sections can appear as below, where the example algorithm section contains three assignment statements. equation x = y*2; Z
=
Wi
algorithm xl .- Z+Xi x2 := y-5; xl := x2+Yi equation u = xl+x2;
Note that the code in the algorithm section, sometimes denoted algorithm equation, uses the values of certain variables from outside the algorithm. These variables are so called input variables to the algorithm-s-in this example x, y, and z. Analogously, variables assigned values by the algorithm define the outputs of the algorithm-s-ui this example xl and x2. This makes the semantics of an algorithm section quite similar to a function with the algorithm section as its body, and with input and output formal parameters corresponding to inputs and outputs as described above. See also Chapter 9, page 283, regarding algorithms and functions.
2.14.2 Statements In addition to assignment statements, which were used in the previous example, three other kinds of "algorithmic" statements are available in Modelica: if-then-else statements, for-loops, and whileloops. The summation below uses both a while-loop and an if-statement, where size (a,l) returns the size of the first dimension of array a. The elseif- and else-parts of if-statements are optional. sum := 0;
n
:=
size(a,l);
while n>O loop if a[n]>O then sum := sum + a[n]i
Chapter 2 A QuickTourof Modelica 47 elseif a[n] > -1 then sum .- sum - a[n] -1; else sum .- sum - a(n]; end if; n := n-l;
end while;
Both for-loops and while-loops can be immediately terminated by executing a break-statement inside the loop. Such a statement just consists of the keyword break followed by a semicolon. Consider once more the computation of the polynomial presented in Section 2.6.1 on repetitive equation structures, page 33. y
:=
a[1]+a[2]*x + a[3]*x Al + ... + a[n+l]*x A n
i
When using equations to model the computation of the polynomial it was necessary to introduce an auxliliary vector xpowers for storing the different powers of x. Alternatively, the same computation can be expressed as an algorithm including a for-loop as below. This can be done without the need for an extra vector---it is enough to use a scalar variable xpower for the most recently computed power of x. algorithm y := 0; xpower := 1; for i in l:n+1 loop y := y + a[i]*xpoweri xpower .- xpower*x; end for;
See Section 9.2.3, page 287, for descriptions of statement constructs in Modelica.
2.14.3 Functions Functions are a natural part of any mathematical model. A number of mathematical functions like abs, sqrt, mod, etc. are predefined in the Modelica language whereas others such as sin, cos, exp, etc. are available in the Modelica standard math library Modelica .Math. The arithmetic operators +, -, *, I can be regarded as functions that are used through a convenient operator syntax. Thus it is natural to have user-defined mathematical functions in the Modelica language. The body of a Modelica function is an algorithm section that contains procedural algorithmic code to be executed when the function is called. Formal parameters are specified using the input keyword, whereas results are denoted using the output keyword. This makes the syntax of function definitions quite close to Modelica block class definitions. Modelica functions are mathematical functions, i.e., without global side-effects and with no memory. A Modelica function always returns the same results given the same arguments. Below we show the algorithmic code for polynomial evaluation in a function named polynomialEval uator. function pclynomialEvaluator input Real a[:]; II Array, size defined at function call time input Real x := 1.0; II Default value 1.0 for x output Real y; protected Real xpower; algorithm y := 0;
xpower for i
:= 1;
in l:size(a,l) loop y := y + a[i]*xpoweri
48 Peter Fritzson Principlesof Object-OrientedModeling and Simulation with MOOeHca
xpower := xpower*xi end fori end polynomialEvaluatori Functions are usually called with positional association of actual arguments to formal parameters. For example, in the call below the actual argument {I, 2 , 3 , 4} becomes the value of the coefficient vector a, and 21 becomes the value of the formal parameter x. MOOeHca function parameters are read-only, i.e., they may not be assigned values within the code of the function. When a function is called using positional argument association, the number of actual arguments and formal parameters must be the same. The types of the actual argument expressions must be compatible with the declared types of the corresponding formal parameters. This allows passing array arguments of arbitrary length to functions with array formal parameters with unspecified length, as in the case of the input formal parameter a in the polynomialEvaluator function.
p
= polynomialEvaluator N
~
:>
~
:>
r-t
~
...:J
:>
·rt
:>
o
R2.v = R2.R*L~i Rl.p.v = AC.VA*sin(2*AC.f*AC.PI*time) L.v = Rl.p.v - R2.v Rl.v = Rl.p.v - C.v C.i = Rl.v/Rl.R der(L.i) L.v/L.L der(C.v) = C.i/C.C
Figure 2-30. Block lower triangularform of the SimpleCircui t example.
The remaining 26 algebraic variables in the equation system of the simple circuit model that are not part of the minimal 7-variable kernel ODE system solved above can be computed at leisure for those iterations where their values are desired-this is not necessary for solving the kernel ODE system. It should be emphasized that the simple circuit example is trivial. Realistic simulation models often contain tens of thousands of equations, nonlinear equations, hybrid models, etc. The symbolic transformations and reductions of equation systems performed by a real Modelica compiler are much more complicated than what has been shown in this example, e.g., including index reduction of equations and tearing of subsystems of equations. simulate{SimpleCircuit,stopTime=5)] plot(C.v, xrange={O,S}) 0.75 0.5 0.25
-0.25 -0.5 -0.75
Figure 2-31. Simulationof the SimpleCircuit model with a plot of the voltage c. v over the capacitor.
Chapter2 A QuickTour of Modelica 63
2.21 History In September 1996, a group of tool designers, application experts, and computer scientists joined forces to work together in the area of object-oriented modeling technology and applications. The group included specialists behind the object-oriented modeling languages Dymola, Omola, ObjectMath, NMF (Neutral Modeling Format), Allan-D.M.L, SIDOPS+, and Smile, even though not all were able to attend the first meeting. Initially the goal was to write a white paper on object-oriented modeling language technology including possible unification of existing modeling languages, as part of an action in the ESPRIT project Simulation in Europe Basic Research Working Group (SiE-WG). However, the work quickly focused on the more ambitious goal of creating a new, unified objectoriented modeling language based on the experience from the previous designs. The designers made an effort to unify the concepts to create a common language, starting the design from scratch. This new language is called Modelica. The group soon established itself as Technical Committee 1 within EurcSim, and as the Technical Chapter on Modelica within Society for Computer Simulation International (SCS). In February 2000, Modelica Association was formed as an independent nonprofit international organization for supporting and promoting the development and dissemination of the Modelica Language and the Modelica Standard Libraries. The first Modelica language description, version 1.0, was put on the web in September 1997, by a group of proud designers, after a number of intense design meetings. Today, in 2003, at the date of this writing, the Modelica 2.1 specification has been released--the result of a large amount of work including 34 three-day design meetings. Two complete commercial tools supporting textual and graphical model design and simulation with Modelica are currently available, as well as a rather complete open-source implementation, and several partial university prototypes. A large and growing Modelica Standard Library is also available. The language is quickly spreading both in industry and in academia. If we trace back a few steps and think about the Modelica technology, two important points become apparent: •
Modelica includes equations, which is unusual in most programming languages.
•
The Modelica technology includes graphical editing for application model design based on predefined components.
In fact, concerning the first point, equations were used very early in human history-already in the third millennium B.C. At that point the well-known equality sign for equations was not yet invented. That happened much later-the equation sign was introduced by Robert Recorde in 1557, in a form depicted in Figure 2-32.
Figure 2-32. Equation sign invented by Robert Recorde 1557. Reproduced from Figure 4.1- t on page 81 in (Gottwald, Gellert, Kuestner 1989), courtesy Thompson Inc. However, it took a while for this invention to spread in Europe. Even a hundred years later, Newton (in his Principia, vol. 1, 1686) still wrote his famous law of motion as text in Latin, as shown in Figure 2-33. Translated to English this can be expressed as: "The change of motion is proportional to the motive force impressed".
64 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica
Figure 2-33. Newton's famous second law of motion in Latin. Translated to English this becomes "The change of motion is proportional to the motive force impressed". Reproduced from Figure "Newton's laws of motion" on page 51 in (Fauvel, Flood, Shortland, and Wilson 1990), courtesy Oxford University Press. In modem mathematical syntax, Newton's law of motion appears as follows: !!...(m.v)
dt
=~ F. ~ ,
(2-14)
I
This is an example of a differential equation. The first simulators to solve such equations were analog. The idea is to model the system in terms of ordinary differential equations and then make a physical device that obeys the equations. The rust analog simulators were mechanical devices, but from the 1950s electronic analog simulators became predominant. A number of electronic building blocks such as adders, multipliers, integrators, etc. could be interconnected by cables as depicted in Figure 2-34. Concerning the further development, for a long time equations were quite rare in computer languages. Early versions of Lisp systems and computer algebra systems were being developed, but mostly for formula manipulation rather than for direct simulation. However, a number of simulation languages for digital computers soon started to appear. The first equation-based modeling tool was Speed-Up, a package for chemical engineering and design introduced in 1964. Somewhat later, in 1967, Simula 67 appeared--the first object-oriented programming language, with profound influence on programming languages and somewhat later on modeling languages. The same year the CSSL (Continuous System Simulation Language) report unified existing notations for expressing continuous system simulation models and introduced a common form of causal "equation", e.g.:
variable = expression
(2-15)
v = INTEG(F) I m The second equation is a variant of the equation of motion: the velocity is the integral of the force divided by the mass. These are not general equations in the mathematical sense since the causality is from right to left, i.e., an equation of the form expression = variable is not allowed. However, it is still a definite step forward toward a more general executable computer representation of equation-based mathematical models. ACSL, first introduced in 1976, was a rather common simulationsystem initially based on the CSSL standard. An important pioneering predecessor to MOOeHca is Dymola (Dynamic modeling language-not today's Dymola tool meaning Dynamic modeling laboratory) described in Hilding Elmqvist's PhD thesis 1978. This was the first work to recognize. the importance of modeling with acausal equations together with hierarchical submodels and methods for automatic symbolic manipulation to support equation solution. The GASP-IV system in 1974 followed by GASP-Va few years later introduced integrated continuous-discrete simulation. The Omola language (1989) is a modeling language with full object orientation including inheritance as well as hybrid simulation. The Dymola language was later (1993) enhanced with inheritance, as well as with mechanisms for discrete-event handling and more efficient symbolic-numeric equation system solution methods. Other early object-oriented acausal modeling languages include NMF (Natural Model Format, 1989), primarily used for building simulation, Allan-V.M.L, SIDOPS+ supporting bond graph modeling, and Smile (1995)-influenced by Objective C. Two other important languages that should be mentioned are ASCEND (1991) and gPROMS (1994).
Chapter 2 A QuickTourof Modelica 65
This author's acquaintance with equation-based modeling and problem solving started in 1975 by solving the SchrOdinger equation for a very specific case in solid-state physics, using the pseudopotential approximation. Later, in 1989, I initiated development of a new object-oriented modeling language called ObjectMath together with my brother Dag Fritzson. This was one of the earlier object-oriented computer algebra and simulation systems, integrated with Mathematica and with a general parameterized generic class concept, as well as code generation to C++ for efficient simulation of industrial applications. The fourth version of ObjectMath was completed in the fall of 1996 when I decided to join the Modelica effort instead of continuing with a fifth version of ObjectMath. Concerning the second aspect mentioned earlier-graphical specification of simulation modelsFigure 2-34 is tells an interesting story.
Figure 2-34. Analog computing vs. graphicalblock diagram modelingon modem digital computers. Courtesy Karl-Johan Astram and Hilding Elmqvist. The left part of the figure shows the circuitry of an analog computer with its building blocks connected by cables. The right figure is a block diagram of very similar structure, directly inspired by the analog computing paradigm but executed on digital computers. Such block diagrams are typically constructed by common tools available today such as Simulink or SystemBuild. Block diagrams represent causal equations since there is a specified data-flow direction. The connection diagrams used in Modelica graphical modeling include connections between instances of classes containing acausal equations, as first explored in the Hibliz system. This is a generalization inspired by the causal analog computing circuit diagrams and block diagrams. The Modelica connection diagrams have the advantage of supporting natural physical modeling since the topology of a connection diagram directly corresponds to the structure and decomposition of the modeled physical system.
2.22 Summary This chapter has given a quick overview. of the most important concepts and language constructs in Modelica. However, Chapter 3 to Chapter 11 together with Chapter 13 give a much more complete description of the language with many examples including a number of language and usage aspects not covered by this quick tour. We have also defined important concepts such as object oriented mathematical modeling and acausal physical modeling, and briefly presented the concepts and Modelica language constructs for defining components, connections, and connectors. The chapter concludes with an in-depth example of the translation and execution of a simple model, and a short history of equations and mathematical modeling languages up to and including Modelica from ancient times until today.
2.23 Literature Many programming language books are organized according to a fairly well-established pattern of first presenting a quick overview of the language, followed by a more detailed presentation according to the most important language concepts and syntactic structures. This book is no exception to that rule, where
66 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica this chapter constitutes the quick overview. As in many other texts we start with a HelloWorld example, e.g as in the Java programming language book (Arnold and Gosling 1999), but with a different contents since printing an "Hello World" message is not very relevant for an equation-based language. The most important reference document for this chapter is the Modelica tutorial (Modelica Association 2000), of which the first version including a design rationale (Modelica Association 1997) was edited primarily by Hilding Elmqvist. Several examples, code fragments, and text fragments in this chapter are based on similar ones in the tutorial, e.g. the SimpleCircuit model with the simple electrical components. the polynomialEvaluator, the low pass filter, the ideal Diode, the BouncingBall model, etc. Figure 2-8 on block oriented modeling is also from the tutorial. The hand translation of the simple circuit model is inspired by a similar but less elaborated example in a series of articles by Martin Otter et al (Otter 1999). The recent history of mathematical modeling languages is described in some detail in (Astrom, Elmqvist, and Mattsson 1998), whereas bits and pieces of the ancient human history of the invention and use of equations can be found in (Gottwald, Gellert, and Kuestner 1989), and the picture on Newton's second law in latin in (Fauvel, Flood, Shortland, and Wilson 1990). Early work on combined continous/discrete simulation is described in (Pritsker 1974) followed by (Cellier 1979). This author's first simulation work involving solution of the Schrodinger equation for a particular case is described in (Fritzson and Berggren 1976). Current versions of several Modelica tools are described in Chapter 19, including OpenModelica, MathModelica, and Dymola meaning the Dynamic Modeling Laboratory. The predecessors of the Modelica language are briefly described in Appendix F, including Dymola meaning the Dynamic Modeling Language: (Elmqvist 1978; Elmqvist, Bruck, and Otter 1996), Omola: (Mattsson, Andersson, and Astrom 1993; Andersson 1994), ObjectMath: (Fritzson, Viklund, Herber, Fritzson 1992), (Fritzson, Viklund, Fritzson, and Herber 1995; Viklund and Fritzson 1995), NMF: (Sahlin, Bring, Sowell 1996), Smile: (Ernst, Jahnichen, and Klose 1997), etc. Speed-Up, the earliest equation-based simulation tool, is presented in (Sargent and Westerberg 1964), whereas Simula-67--the first object-oriented programming language-is described in (Birtwistle, Dahl, Myhrhaug, and Nygaard 1974). The early CSSL language specification is described in (Augustin, Fineberg, Johnson, Linebarger, Sansom, and Strauss 1967) whereas the ACSL system is described in (Mitchell and Gauthier 1986). The Hibliz system for an hierarchical graphical approach to modeling is presented in (Elmqvist 1982). Software component systems are presented in (Assmann 2002; Szyperski 1997). The Simulink system for block oriented modeling is described in (MathWorks 2001), whereas the MATLAB language and tool are described in (MathWorks 2002). The DrModelica electronic notebook with the examples and exercises of this book has been inspired by DrScheme (Felleisen, Findler, Flatt, and Krishnamurthi 1998) and DrJava (Allen, Cartwright, and Stoler 2002), as well as by Mathematica (Wolfram 1997), a related electronic book for teaching mathematics (Davis, Porta, and UhI1994), and the MathModelica environment (Fritzson, Engelson, and Gunnarsson 1998; Fritzson, Gunnarsson, and Jirstrand 2002). The first version of DrModelica is described in (Lengquist-Sandelin and Monemar 2003; Lengquist-Sandelin, Monemar, Fritzson, and Bunus 2003). General Modelica articles and books: (Elmqvist 1997; Fritzson and Engelson 1998; Elmqvist, Mattson, and Otter 1999), a series of 17 articles (in German) of which (Otter 1999) is the first, (Tiller 2001; Fritzson and Bunus 2002; Elmqvist, Otter, Mattsson, and Olsson 2(02). The proceedings from the following conferences, as well as some not listed here, contain a number of Modelica related papers: the Scandinavian Simulation Conference: (Fritzson 1999), and especially the International Modelica Conference: (Fritzson 2000; Otter 2002; Fritzson 2003).
Chapter 2 A Quick Tourof Modelica 67
2.24 Exercises Exercise2-1: Question: What is a class? Creating a Class: Create a class, Add, that calculates the sum of two parameters, which are Integer numbers with given values. Exercise 2-2:
Question: What is an instance? Creating Instances:
class Dog constant Real legs = 4; parameter String name = "Dummy"; end dog; • •
Create an instance of the class Dog. Create another instance and give the dog the name "Tim".
Exercise 2-3: Write a function, average, that returns the average of two Real values. Make a function call to average with the input 4 and 6. Exercise 2-4:
Question: What do the terms partial, class, and extends stand for? Exercise 2-5:
Inheritance: Consider the Bicycle class below.
record Bicycle Boolean has wheels Integer nrOfWheels end Bicycle;
true; 2;
Define a record, ChildrensBike, that inherits from the class Bicycle and is meant for kids. Give the variables values. Exercise 2-6:
Declaration Equations and Normal Equations: Write a class, Birthyear, which calculates the year of birth from this year together with a person's age.
Point out the declaration equations and the normal equations. Modification Equation: Write an instance of the class Birthyear above. The class, let's call it MartiIisBirthyear, shall calculate Martin's year of birth, call the variable martinsBirthyear, who is a 29-year-old. Point out the modification equation. Check your answer, e.g. by writing as below
12
val (martinsBirthday.birthYear,0)
12 In OpenModelica, the expression val (martinsBirthday. birthYear, 0) means the birthYear value at time=O, at the beginning of the simulation. Interpolated values at other simulated time points can also be obtained. Constantexpressions such as 33+5, and function calls, can also be evaluated interactively.
68 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Exercise 2-7:
Classes: class Ptest parameter Real Xi parameter Real Yi Real Zi Real Wi equation x + Y = Zi end Ptest;
Question: What is wrong with this class? Is there something missing? Exercise 2-8:
Create a record containing several vectors and matrices: • • • •
A vector containing the two Boolean values true and false. A vector with five Integer values of your choice. A matrix of three rows and four columns containing String values of your choice. A matrix of one row and five columns containing different Real values, also those of your choice.
Exercise 2-9:
Question: Can you really put an algorithm section inside an equation section? Exercise 2-10:
Writing an Algorithm Section: Create the class, Average, which calculates the average between two integers, using an algorithm section. Make an instance of the class and send in some values. Simulate and then test the result of the instance class by writing instanceVariable.classVariable.
Exercise 2-11: (A harder exercise)
Write a class, AverageExtended, that calculates the average of 4 variables (a , b , c , and d). Make an instance of the class and send in some values. Simulate and then test the result of the instance class by writing instanceVariable.classVariable.
Exercise 2-12:
If-equation: Write a class Lights that sets the variable switch (integer) to one if the lights are on and zero if the lights are off. When-equation: Write a class LightSwi tch that is initially switched off and switched on at time 5. Tip: sample (start I interval) returns true and triggers time events at time instants and rem (X, Y) returns the integer remainder of x/y, such that di v (x , y) * y + rem (x, y) = x, Exercise 2-13:
Question: What is a Package? Creating a Package: Create a package that contains a division function (that divides two Real numbers) and a constant k = 5.
Chapter 2 A QuickTourof Modelica 69
Create a class, containing a variable x. The variable gets its value from the division function inside the
package, which divides 10 by 5.
71
Part II
The Modelica Language
73
Chapter 3 Classes, Types, and Declarations
The fundamental unit of modeling in Modelica is the class. Classes provide the structure for objects, also known as instances, and serve as templates for creating objects from class definitions. Classes can contain equations which provide the basis for the executable code that is used for computation in Modelica. Conventional algorithmic code can also be part of classes. Interaction between objects of well-structured classes in Modelica is usually done through so-called connectors, which can be seen as "access ports" to objects. All data objects in Modelica are instantiated from classes, including the basic data types-Real, Integer, String, Boolean-and enumeration types, which are built-in classes or class schemata. A class in Modelica is essentially equivalent to a type. Declarations are the syntactic constructs needed to introduce classes and objects. This chapter is organized into two parts. The first part comprising sections 3.1 to 3.6 gives a tutorial introduction to the Modelica class concept using the Moon landing example as well as the contract idea. The rest of the chapter is presented in a somewhat more formal style, giving a complete description of most aspects of Modelica classes, types, declarations, and lookup, except inheritance covered in Chapter 4 and component aspects covered in Chapter 5.
3.1 Contract Between Class Designer and User Object-oriented modeling languages try to separate the notion of what an object is from how its behavior is implemented and specified in detail. The "what" of an object in Modelica is usually described through documentation including graphics and icons, together with possible public connectors, variables, and other public elements, and their associated semantics. For example, the "what" of an object of class Resistor is the documentation that it models a "realistic" ideal resistor coupled with the fact that its interaction with the outside world is through two connectors n, p of type Pin, and their semantics. This combinationdocumentation, connectors and other public elements, and semantics-is often described as a contract between the designer of the class and the modeler who uses it, since the "what" part of the contract specifies to the modeler what a class represents, whereas the "how" provided by the class designer implements the required properties and behavior. An incorrect, but common, assumption is that the connectors and other public elements of a class (its "signature") specify its entire contract. This is not correct since the intended semantics of the class is also part of the contract even though it might only be publicly described in the documentation, and internally modeled through equations and algorithms. Two classes e.g., a Resistor and a temperaturedependent Resistor, may have the same "signature" in terms of connectors but still not be equivalent since they have different semantics. The contract of a class includes both the signature and the appropriate part of its semantics together.
74 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica The "how" of an object is defined by its class. The implementation of the behavior of the class is defined in terms of equations and possibly algorithmic code. Each object is an instance of a class. Many objects are composite objects i.e., consist of instances of other classes.
3.2 A Class Example The basic properties of a class are given by: • •
Data contained in variables declared in the class. Behavior specified by equations together with possible algorithms.
Here is a simple class called CelestialBody that can be used to store data related to celestial bodies such as the earth, the moon, asteroids, planets, comets, and stars: class CelestialBody constant Real 9 = 6.672e-l1; parameter Real radius; parameter String name; Real mass; end CelestialBody;
The declaration of a class starts with a keyword such as class, model, etc., followed by the name of the class. A class declaration creates a type name in Modelica, which makes it possible to declare variables of that type, also known as objects or instances of that class, simply by prefixing the type name to a variable name: CelestialBody moon;
This declaration states that moon is a variable containing an object of type CelestialBody. The declaration actually creates the object i.e., allocates memory for the object. This is in contrast to a language like Java, where an object declaration just creates a reference to an object. This first version of CelestialBody is not very well designed. This is intentional, since we will demonstrate the value of certain language features for improving the class in this and the following two chapters.
3.3 Variables The variables belonging to a class are sometimes called record fields or attributes; the CelestialBody variables radius, name, and mass are examples. Every object of type CelestialBody has its own instances of these variables. Since each separate object contains a different instance of the variables this means that each object has its own unique state. Changing the mass variable in one CelestialBody object does not affect the mass variables in other CelestialBody objects. Certain programming languages e.g., Java and C++, allow so-called static variables, also called class variables. Such variables are shared by all instances of a class. However, this kind of variable is not available in Modelica. A declaration of an instance of a class e.g., moon being an instance of CelestialBody, allocates memory for the object and initializes its variables to appropriate values. Three of the variables in the class CelestialBody have special status: the gravitational constant 9 is a constant that never changes, and can be substituted by its value. The simulation parameters radius and name are examples of a special kind of "constant" denoted by the keyword parameter in Modelica. Such simulation parameter "constants" are assigned their values only at the start of the simulation and keep their values constant during simulation.
Chapter 3 Classes, Types, and Declarations 75
In Modelica variables store results of computations performed when solving the equations of a class together with equations from other classes. During solution of timedependent problems, the variables store results of the solution process at the current time instant. As the reader may have noted, we use the terms object and instance interchangeably with the same meaning; we also use the terms record field, attribute, and variable interchangeably. Sometimes the term variable is used interchangeably with instance or object, since a variable in MOOeHca always contains an instance of some class.
3.3.1 Duplicate Variable Names Duplicate variable names are not allowed in class declarations. The name of a declared element e.g., a variable or local class, must be different from the names of all other declared elements in the class. For example, the following class is illegal: class IllegalOuplicate Real duplicate; Integer duplicate; end IllegalDuplicate;
II Error! Illegal duplicate variable name
3.3.2 Identical Variable Names and Type Names The name of a variable is not allowed to be identical to its type specifier. Consider the following erroneous class: class IllegalTypeAsVariable Voltage Voltage; II Error! Variable name must be different from type Voltage voltage; II Ok! Voltage and voltage are different names end IllegalTypeAsVariable;
The first variable declaration is illegal since the variable name is identical to the type specifier of the declaration. The reason this is a problem is that the Vol tage type lookup from the second declaration would be hidden by a variable with the same name. The second variable declaration is legal since ·the lowercase variable name voltage is different from its uppercase type name Voltage.
3.3.3 Initialization of Variables The default suggested (the solver may choose otherwise, if not fixed) initial variable values are the following, if no explicit start values are specified (see Section 2.3.2, page 27, and Section 8.4 below on page 250): • • • •
The value zero as the default initial value for numeric variables. The empty string "" for String variables. The value false for Boolean variables. The lowest enumeration value in an enumeration type for enumeration variables.
However, local variables to functions have unspecified initial values if no defaults are explicitly given. Initial values can be explicitly specified by setting the sta.rt attributes of instance variables equal to some value, or providing initializing assignments when the instances are local variables or formal parameters in functions. For example, explicit start values are specified in the class Rocket shown in the next section for the variables mass, altitude, and velocity.
76 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica
3.4 Behavior as Equations Equations are the primary means of specifying the behavior of a class in Modelica, even though algorithms and functions also are available. The way in which the equations interact with equations from other classes determines the solution process i.e., program execution, where successive values of variables are computed over time. This is exactly what happens during dynamic system simulation. During solution of timedependent problems, the variables store results of the solution process at the current time instant.
Figure 3-1. Apollo12rocket for landing on the moon. The class Rocket embodies the equations of vertical motion for a rocket (e.g. as depicted in Figure 3-1) which is influenced by an external gravitational force field gravity, and the force thrust from the rocket motor, acting in the opposite direction to the gravitational force, as in the expression for acceleration below: . acce Ieration
thrust - mass- gravity =-----------
mass
The following three equations are first-order differential equations stating well-known laws of motion between altitude, vertical velocity, and acceleration: mass' = -massLossRate . abs~hrust) altitude' = velocity velocity' = acceleration
All these equations appear in the class Rocket below, where the mathematical notation () for derivative has been replaced by the pseudofunction der() in Modelica. The derivative of the rocket mass is negative since the rocket fuel mass is proportional to the amount of thrust from the rocket motor. class Rocket "rocket class"· parameter String name; Real mass{start=1038.358); Real altitude(start= 59404); Real velocity(start= -2003); Real acceleration; Real thrust; II Thrust force on the rocket Real gravity; II Gravity forcefield parameter Real massLossRate~0.000277; equation (thrust-mass*gravity)/mass acceleration; der(mass) = -massLossRate * abs(thrust); der(altitude) velocity; der(velocity} = acceleration; end Rocket;
Chapter 3 Classes,Types, and Declarations 77 The following equation, specifying the strength of the gravitational force field, is placed in the class MoonLanding in the next section since it depends on both the mass of the rocket and the mass of the moon:
.
g
gravity =
. mass
~ltitudeapollo + radiusmoon y moon
moon
The amount of thrust to be applied by the rocket motor is specific to a particular class of landings, and therefore also belongs to the class MoonLanding: thrust = if ~ime < thrustDecreaseTime ) then forcel else if ~ime < thrustEndTime ) then force2 else 0
3.5 Access Control Members of a Modelica class can have two levels of visibility: public or protected. The default is public if nothing else is specified e.g., regarding the variables force1 and force2 in the class MoonLanding below. The public declaration of force1, force2, apollo, and moon means that any code with access to a MoonLanding instance can read or update those values. The other possible level of visibility, specified by the keyword protected--e.g., for the variables thrustEndTime and thrustDecreaseTime, means that only code inside the class as well as code in classes that inherit this class are allowed access. Code inside a class includes code from local classes, see Section 3.7.2 on page 80. However, only code inside the class is allowed access to the same instance of a protected variable---classes that extend the class will naturally access another instance of a protected variable since declarations are "copied" at inheritance. This is different from corresponding access rules for Java. Note that an occurrence of one of the keywords public or protected means that all member declarations following that keyword assume the corresponding visibility until another occurrence of one of those keywords. The variables thrust, gravity, and altitude belong to the apollo instance of the Rocket class and are therefore prefixed by apollo in references such as apollo. thrust. The gravitational constant g, the mass, and the radius belong to the particular celestial body called moon on which surface the apollo rocket is landing. class MoonLanding parameter Real force1 parameter Real force2 protected par~eter
36350; 1308;
Real thrustEndTime = 210;
parameter Real thrustDecreaseTime
=
43.2;
public
Rocket CelestialBody
apollo (name="apollo12") ; moon(name="moon",mass=7.382e22,radius=1.738e6);
equation
apollo. thrust
if (time= min and 'value' A variable specifier has the following structure, where all elements apart from the identifier are optional:
<arraydimension descriptor> <modifiers» <declaration equation/initializer» The type specifier part of a declaration describes the kind of values that can be represented by the declared variable(s). It consists of a type name optionally followed by an array dimension descriptor. There is no difference between variables declared in a single declaration or in multiple declarations. For example, regard the following single declaration of two matrix variables: Real[2,2]
A, B;
That declaration has the same meaning as the following two declarations together: Real[2,2] Real [2,2)
A; B;
The array dimension descriptors may instead be placed after the variable name in the variable specifier, giving the two declarations below, with the same meaning as in the previous example: Real Real
A[2,2]; B[2,2];
The following declaration is different, meaning that the variable a is a scalar and B is a matrix as above: Real
a, B[2,2];
3.11 Declaration Prefixes Both class and variable declarations can contain various qualifier prefixes. These prefixes associate certain properties with the declaration and are placed at the beginning of the declaration. The following sections give an overview of the Modelica declaration prefixes.
3.11.1 Access Control by Prefixes: pubtlc and protected As was already described in the section on access control on page 77, an optional access prefix may be specified at the beginning of a declaration. The access prefixes available in Modelica are public and protected, giving two possible levels of visibility for Modelica variables. This is illustrated by the class AccessDemo below.
Chapter 3 Classes, Types, and Declarations 89 Note that an access prefix is implicitly applied to all subsequent declarations without access prefix following the current declaration until the next declaration with an access prefix in the same scope. This makes it natural to view an access prefix as a heading for a section of declarations. The initial default is public if nothing yet has been specified within the current scope. Thus, the variables a,. x, y, Z, u3 are public, whereas w, u, and u2 are protected. class AccessDemo "Illustration of access prefixes" Real a; public Real Xi Real y, z; protected Real w, U; Real u2; public Real u3; end AccessDemo;
The public declaration of variables a, x, y, Z, u3 means that any code with access to an AccessDemo instance can read or update those variables. The other possible level of visibility, specified by the keyword protected, means that only code inside the class AccessDemo as well as code in classes that inherit this class are allowed access to the variables w, u, and u2. In fact, only code inside the class AccessDemo has access to the same instance of the protected variables W u, and u2. Elements are inherited with their own protection, i.e., public and protected elements keep being public and protected, respectively, after being inherited into another class. However, the access prefixes public and protected from a parent class are not inherited as elements themselves, and can therefore never influence the protection status of the declarations in a child class. 1
3.11.2 Variability Prefixes: constant, parameter and discrete The prefixes constant, parameter, discrete of a variable declaration are called variability prefixes and define in which situations the value of variable may change and when it is kept constant. The term variability here should be interpreted as time variability. The variability prefixes can be used to define the following four classes of variables (see Figure 3-7): •
•
•
Named constants i.e., variables with the constant prefix, which never change value once they have been defined. This can, for example, be used to define mathematical constants. The derivative of a constant is zero. A constant definition is automatically final i.e., behaves as if final prefix (see Section 3.11.5, page 91) is present in the definition. Therefore a, constant definition can never be redefined, not even an inherited copy of a constant definition. Named constant parameters i.e., variables with the parameter prefix, which remain constant during time-dependent simulation and have time derivative equal to zero. These "constants" may be assigned values e.g., during the initialization phase or interactively by the user via a simulation tool immediately before time-dependent simulation starts). Interactive setting of simulation parameters is usually done very conveniently via the graphical user interface of the simulation tool. The built-in der( ... ) derivative operator need not be applied to such variables since the result is always zero. Discrete-time variables with the optional associated prefix di screte are piecewise constant signals that change their values only at event instants during simulation (see Section 13.2.2 in Chapter 13), and have time derivative equal to zero. However, it is illegal to apply the der() operator to a discrete-time variable. Boolean, Integer, String, and enumeration variables are discrete-time by default and cannot be continuous-time. A Real variable with the prefix
90 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica
•
di screte is a discrete-time variable. However, note that a Real variable without the discrete prefix but assigned a value in a when-statement or when-equation is also a discrete-time variable. Continuous-time variables evolve their values continuously during simulation. This is default for Real variables if no variability prefix is specified and they are not assigned in a when-equation or when-statement. This is the most common kind of variable in continuous models.
_-~-~~-
A continuous-time variable
. . . - - - A discrete-time variable
J.----------------- A parameter variable 1 - - - - - - - - - - - - - - - - - - A constant "variable" event 1
event 2
event3
time
Figure 3-7. Illustrating variables with different variability. Named constants can be defined in Modelica by using the prefixes constant or parameter in declarations and providing declaration equations as part of the declarations. For example: Real String Integer parameter Real constant Real
constant constant constant
PI = 4*arctan{l)i redcolor = "red"; one = 1; mass = 22.5; tobespecified; II to be given value through a modification
Parameter "constants" can bedeclared without a declaration equation containing a default value since their value can be defined e.g., by reading from a file, before simulation starts. For example: parameter Real
mass, gravity, length;
Parameter "constants" may also be used as structural parameters i.e., parameters whose values influence the structure of the model, i.e., the set of active equations. For example, in the model Inertia below two equations are effectively removed from influencing the simulation if the user sets condflg to false before simulation starts. model Inertia parameter Boolean condflg; equation J*a = tl - t2;
if condflg then der(v) a; der(r) v; end if
II Two conditional equations, II deactivated if condflg=false
end Inertia;
Variables of type Real are normally continuous-time variables as the default without explicit declaration of a more restrictive variability prefix. Piecewise constant (discrete) Real variables can be declared but are rarely needed. However, Real variables that are explicitly assigned in when-statements or implicitly assigned values through solution of equations in when-equations are also discrete i.e., piecewise constant.
Chapter 3 Classes, Types, and Declarations 91 Variables of type Integer, Boolean, String, or enumeration have data types that change value in discrete steps. Such variables may change their values only at events, which makes the default variability discrete natural. Variables and expressions in functions behave as though they were discrete-time expressions since a function is always called and evaluated at some point in time i.e., time does not go forward during evaluation of a function call, similar to the evaluation of a when-equation at an event. Function calls can, however, occur at any point in time, not only at events. For further discussion concerning variability of expressions, see Chapter 6, page 192.
3.11.3 Causality Prefixes: input and output One of the major advantages of an equation-based language such as Modelica is that acausal mathematical models can be specified since equations do not prescribe a certain data-flow direction. However, certain model components such as functions and blocks have specified causality. When calling a function, data are supplied as actual input arguments and results are returned from the function. The same is true for blocks since a block is a kind of restricted Modelica class with specified causality for all variables in its interface. The prefixes input and output are available for specifying and thus restricting the direction of data flow for declared variables. This is required for interface variables of blocks and functions, but can be used for a variable in any class e.g., to simplify the solution process when the data-flow direction is fixed and known. A simple block with one input and one output variable is shown below: block SquareDance input Real Xi output Real squared; equation squared = X*Xi end SquareDance;
3.11.4 Flow Prefix: flow The flow prefix is required for variables which belong to instances of connector classes and specify flow quantities e.g., current flow, fluid flow, force, etc. Such quantities obey laws analogous to Kirchhoffs current law of summing all flows into a specific point to zero. Variables without the f low prefix are assumed to be potential (nontlow) quantities e.g., voltage, pressure, position, etc., which obey laws analogous to Kirchhoff's first law of setting all potential quantities connected to the same point equal. The type of variables declared with the flow prefix must be a subtype of Real. For more in-depth information concerning the flow prefix including examples, see Chapter 5, page 148. A small example of a flow variable: flow Current i;
3.11.5 Modification Prefixes": replaceable, redeclare, and final Modification prefixes control modification of declared elements in classes. What is a modifier? It can be regarded as a kind of (incomplete) declaration that is used to change certain declarations from an inherited class. We have already seen several examples of simple modifiers that are used to change default class
13 The reader who wants a more accessible and in-depth treatment of this topic should read Chapter 4 instead of the short presentation in this section.
92 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica attribute values. For example, the following type declaration contains three modifiers to the built-in class Real that modifes the attributes uni t, min, and max. type Voltage = Real(unit=IV", min=-220.0, max=220.0)i
The final prefix used at the front of a declaration or modifier prevents all modifications of a declared element and further modifications of a' modified element. The motivation behind the final prefix is to prevent users from unknowingly introducing certain errors, which can be avoided by forbidding modifications of sensitive elements. The use of final also prevents interactive setting of parameter variables in the simulation environment since this is a kind of modification. The final prefix prohibits further modification of the uni t attribute in the next example: type Angle = Real(final unit = "rad"); Angle al(unit="deg")i II Error, since unit declared as final!
The modification prefix replaceable used in front of a declaration enables modification in the form of a redeclaration of that declaration. The following is an example of a replaceable declaration from the class C below, of the example variable pobj 1 where pobj 1 also has a local modifier pl=5: replaceable GreenClass
pobjl(pl=5)i
However, modification of the default attribute value of a declared element is allowed also without the replaceable prefix; as for the uni t attribute in the above Vol tage declaration. The class C, also presented previously in Chapter 2, Section 2.5.1, page 30. class C replaceable replaceable replaceable RedClass equation
GreenClass pobjl(pl=5)i YellowClass pobj2i GreenClass pobj3i obj4;
end C; When a modifier contains a complete declaration including type and/or prefixes, the redeclare prefix is required at the front of the modifier, which then replaces the original declaration. Such a modifier is called a redeclaration, and usually (but not always-see Chapter 4, page 125) requires the original declaration to be declared with the prefix replaceable. For example: class C2 = C(redeclare RedClass pobjl)i
The modification prefix replaceable when used in a modifier enables further modification of the resulting modified element. For example, in class C3 this is used to enable further modification of pobj 1 when creating C4: class C3 C(redeclare replaceable RedClass pobjl); class C4 = C3(redeclare YellowClass pobjl)i II OK, since replaceable class C4 = C2(redeclare YellowClass pobjl)i II Error, not replaceable
Modelica classes and packages can be parameterized in a general way, corresponding to generic classes or packages (see Chapter 2, page 30, and Chapter 10, page 346). Both classes and variables which are members of some class can be used as a kind of class parameter by attaching the prefix replaceable in front of their declarations. It is required to have the prefix replaceable in an element declaration to allow replacing the declaration, except when only changing the default attribute value, and/or restricting the variability and possible dimension sizes. For more details and examples regarding modifiers, see Chapter 4, page 119, regarding redeclaration and generic classes see page 125 and page 133 respectively, and on the semantics of final see page 128 in the same chapter.
Chapter 3 Classes, Types, and Declarations 93
3.11.6 Class Prefix: partial The class prefix part ial is used to indicate that a class is incomplete such that it cannotbe instantiated. The keyword is optional i.e., a class can be incomplete without having the prefix partial. On the other hand the partial prefix is required for those partial classes for which type checking of the class declaration cannot be performed without generating type errors e.g., because a type used by the partial class might not be available where the class is declared, only where it is used. Partial classes are aimed for reuse through inheritance (see Chapter 4, page 138 for more details). The common terminology for partial class in other prograrnming languages is abstract class.
3.11.7 Class Encapsulation Prefix: encapsulated The class encapsulation prefix encapsulated is used to achieve lookup encapsuiation of classes, i.e., the lookup stops at the class boundary. This mechanism is primarily intended for Modelica packages, since the common concept of packages entails an independent software unit used for organization of large software systems. An encapsulated package (or class) has no implicit dependencies on the declaration context within which it is placed. All dependencies are explicit via import statements. See Chapter lOon packages, page 335, for more information.
3.11.8 Instance Hierarchy Lookup Prefixes: inner and outer Lookup of names in Modelica is normally done in the usual way for lexically scoped languages with nested scopes. First the current scope containing the name reference is searched for a definition of the name; if not found the next outer scope is searched, etc. However, lookup through the instance hierarchy instead of through the class nesting hierarchy is more suitable when a pervasive object property such as a force field or an environment temperature should affect all parts of the object. In Modelica such a common property can be declared as a definition declaration using the inner prefix, and subsequently accessed by reference declarations using the outer prefix. The lookup is performed through the instance hierarchy instead of through the nested class declaration hierarchy. See Section 5.8 on page 173 for a comprehensive description of applications of this concept and Section 3.13.3 on page 99 in this-chapter for a presentation of the instance hierarchy lookup mechanism.
3.11.9 Ordering of Prefixes The ordering of Modelica declaration prefixes within a declaration is strictly specified according to the list below. Not all combinations of prefixes are meaningful e.g., a constant input variable is not very interesting since it can never change value. The modification prefix redeclare may only occur in modifiers, whereas the access prefixes public and protected may never occur in a modifier. The prefixes encapsulated and partial may be used only for classes, whereas flow, discrete, parameter, constant, input, and output may be used only in variable declarations. The prefixes are placed at the beginning of a declaration element and should be used in the following order whenever more than one prefix occurs in the same declaration:
l. 2. 3. 4. 5.
Access prefixes public and protected. Modification prefix final. Instance hierarchy lookup prefixes inner and outer. Modification prefix redeclare. Modification prefix replaceable.
94 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
6. Class encapsulation prefix encapsula ted. 7. Class prefix partial. 8. The flow prefix flow.
9. Variability prefixes constant, parameter, and discrete. 10. Causality prefixes input and output. A subset of the prefixes are denoted type prefixes i.e., flow, discrete, parameter, constant, input, output, and are considered part of the class type when type checking. See also Section 3.14.5 on page 104 in this chapter.
3.11.10
Variable Specifiers
After having discussed declaration prefixes in detail in the previous sections, it is useful to recall the structure of a declaration:
<prefixes> Each variablespecifier also has a structure, where all parts apart from the identifier are optional:
<arraydimension descriptor> <modifiers> <declaration equation/initializer» As previously stated, an array dimension descriptor can either be part of the type or be put directly after the identifier in the variable specifier. The modifiers should always be placed after the array dimension descriptor if present, otherwise directly after the identifier. More information on modifiers is available in Chapter 4, page 119. The next section shows examples of modifications of start values for specifying default initial values of variables.
3.11.11
Initial Values of Variables
A Modelica variable is either statically allocated and instantiated, which is normally the case for instantiations of models, or is dynamically instantiated as is the case for function formal parameters and local variables. The start value of a variable is the default initial value of the variable normally used at the beginning of a simulation. The simulation tool i.e., the solver, is, however, free (unless specifically prohibited in each declaration by setting the built-in attribute fixed to true) to choose another start value for the variable if this is necessary to be able to solve the systems of equations. If nothing else is specified, the default start value of all statically allocated numerical variables is zero or an array containing elements of the value zero, apart from function results and local variables where the initial value is unspecified. Other start values than the default zero can be specified by setting the start attribute of instance variables. For example, a start value can be specified in the class MyPoints: class MyPoints Point pointl(start={1,2,3}); Point point2; Point point3; end MyPoints;
Alternatively, the start value of pointl can be specified when instantiating MyPoints as below: class Main MyPoints fool end Main;
pts(pointl.start={l,2,3}) ; fli
Note that the s tart attribute of an array variable has the same dimensionality as the variable itself. Single elements of the start value can be modified by indexing the attribute in the modification equation e.g.,
Chapter 3 Classes, Types, and Declarations 95 start [2 , 1] in the array AS example. Below are a few declarations with different combinations of array dimension descriptors and modifiers. Real Real Real
A3[2,2]; A4[2,2] (start={{l,O},{Of1}});
II Array variable II Array with. explicit start value
AS[2,2] (start[2,1]=2.3); II Array with single element modification
Do not make the mistake of using declaration equations for specifying initial values since this will set the variable equal to a constant value throughout the simulation. This is fine for constants or parameters since their values should be fixed during simulation, but is usually not what is expected for a normal variable. For example: class test2 parameter Real xl
35.2;
Real x2 = 99.5; end test2;
1* OK, since xl has a fixed value */ 1* Probably a mistake *1
No equations are present in functions, not even equations for start values, since functions can contain only algorithmic code. Instead, assignment statements can be used to specify default initial values of formal parameters, function results, or local variables. Consider the example function f 2 below: function f2 input Real Xi input Real y := 2i output Real rl; output Real r2 := 3i algorithm
rl := 2*x; if rl>S then r2 := 2*Yi end f2;
A call to f2 using positional parameter passing always requires specifying values of all the arguments, which leaves the default value of y unused: (zl,z2) := f2{33.3,44.4};
On the other hand, a call to f 2 using named parameter passing as below can leave out the second argument since the default is available for this argument. Note that because the conditional assignment to r2 will never take place as a result of the call below, the default result of 3 will be used for the second result r z: (zl, z2) : = f2 (x=l) ;
3.12 Declaration Order and Use Before Declaration In Modelica, as well as in Java, variables and classes can be used before they are declared. This gives maximum flexibility in organizing the code to achieve logical structuring and maximum readability. For example, the well-known top-down design methodology emphasizes the major building blocks at the top level of the system structure and puts less emphasis on low-level details. A declaration before use constraint, common in several older programming languages, would force the low-level model components to be declared first, making it harder to use top-down design. In fact, in Modelica declaration order is significant only in the following two cases: •
•
Declaration order is significant for input or output formal parameter declarations in functions with more than one input formal parameter or more than one result. The reason is that functions may be called with positional parameter passing e.g., as in the examples in the previous section. Declaration order is significant for the variable declarations within record classes. The reason is that any record can be passed as an argument to an external function, in which case the variable
96 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica ordering in the Modelica record is reflected in the variable ordering of the corresponding external record data structure. In the example class below, which is perfectly legal, the types Voltage and Current are used before they are declared: class UseBeforeDecl
Voltage vI; Current il; Voltage v2; type Voltage = Real(unit=lkV"); type Current = Real(unit="mA")i end UseBeforeDecl;
3.13 Scoping and Name Lookup The scope of a name in Modelica is the region of the code where the name has'a meaning corresponding to its intended use. For example, we may have declared a Real variable x in a class RC and an Integer variable x in another class IC: class RC Real x; class Ie Integer
Xi
equation x = 2; end IC;
class BC Real Yi
equation x = Yi end BC; equation x = 3.14; end RC;
The scope of the Real variable x includes the whole class RC apart from the class IC where the Real x is hidden by a local declaration of an Integer variable x within IC, which has a scope that is precisely IC. Thus, scopes usually correspond to class declarations.
3.13.1 Nested Name Lookup Modelica uses nested lookup of names like most other programming languages. The lookup procedure searches for declarations of names within local nested scopes before going out to enclosing scopes. This is the reason why the Real x is hidden within Ic-the search procedure finds the declaration of the integer x first: it does not even need to investigate the declarations within ac. However, even if there was no local declaration of the variable x, it would still be illegal to refer to the Real x if) the enclosing scope Rc-references to variables and parameters in enclosing scopes is illegal in Modelica-such nested lookup is only allowed for names of constants and declared classes. For example: package A
constant Real z = 2;
Chapter 3 Classes, Types, and Declarations 97 model B Real Zi function foo output Real y algorithm y := Zi II Illegal since reference to non-constant z in B
It is not only classes that introduce declarations with local scopes. The iteration variable in Modelica forloops has a scope that extends throughout the for-loop, and hides declarations of variables with the same name in enclosing scopes. For example: function PolynomialEvaluator3 input Real a[:] i input Real Xi output Real Yi protected Real xpower; Integer i; (* Declared local variable i *) algorithm Y := 0;
xpower := 1; for i in l:size(a, 1) loop y := y + a[i]*xpower; xpower := xpower*x; end for; end PolynomialEvaluator3i
(* Iteration variable i *)
The iteration variable i introduced by the for-loop in the body of the function PolynomialEvaluator3 has a scope that extends throughout that for-loop, thus preventing access to the declared local variable i from within the for-loop.
3.13.2 Nested Lookup Procedure in Detail The following stepwise procedure specifies the semantics of lookup for a name used within some piece of Modelica code. The lookup starts in the innermost scope containing the code, usually a class, and proceeds through enclosing scopes until the outermost scope or an encapsulated package or class is encountered. The notion of class should be interpreted in the general sense, i.e., it can also be a function or package. Certain language constructs referred to below like import statements, encapsulated packages, and encapsulated classes are explained in more detail in Chapter 10. To summarize, the statement import A.B.Myclassi
makes it possible to access Myclass using the short name Myclass instead of A. B. Myclass. When importing a whole package import A.B;
makes it possible to use the name B. Myclass with a short package prefix B for access, whereas import A.B.*;
allows the use of short names such as Myclass for all classes in A. B. The lookup procedure is as follows, excluding lookup of names with the prefix outer, which is described in Section 3.13.3, page 99: I.
First look for implicitly declared iteration variables in possible enclosing for-equations or forstatements, if the analyzed code is inside the body of a for-construct. Regarding for-equations, see Section 8.3.2, page 241, and for-statements, see 9.2.5, page 288.
98 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica 2. When a piece of Modelica code is analyzed, e.g. a class or variable declaration, an extends clause, an equation or algorithm, encountered names in the code are looked up. Each such name is looked up in the sequence of enclosing scopes starting at the innermost scope. The search continues until a match is found or the outermost scope or a scope corresponding to an encapsulated class or encapsulated package has been reached. (However, even if found, it is illegal to reference ~ variable or parameter declaration in an enclosing scope, whereas constants and classes can be accessed-similar to the rules for definitions in packages). If not found the lookup continues in the global scope containing the predefined Modelica types, functions, and operators. (For example, the predefined function ahs is searched upwards in the hierarchy as usual. If an encapsulated boundary is reached, ahs is searched for in the global scope instead. The operator ahs cannot be redefined in the global scope, because an existing class cannot be redefined at the same level.) Certain operators are denoted by reserved words or special characters and therefore do not need lookup (see the Modelica Grammar in Appendix A). The lookup in each scope is performed in the following order until a match is found: •
•
•
Search among declared named elements i.e., classes and variables declared in the scope, including elements inherited from other classes. Note that import statements are not inherited from other classes. Regarding inheritance see Chapter 4, and concerning import see Chapter 10, page 335. Search among the import names of qualified import statements in the scope. Such an import name may refer only to an imported package, class, or constant. The import name of the qualified import statement import A. B . C ; is c and the import name of the renaming qualified import statement i mpo rt D=A. B • c, is D. In both cases A. B must be a package. Regarding the special case import E;, E can be any class or package as an element of the unnamed top-level package. Search among the public members of packages imported via unqualified import statements in the current scope e.g., import A. B . * ;. It is an error if this step produces matches from several unqualified imports. Unqualified import statements may only import from packages i.e., A. B must be a package in the statement import A. B. * ;.
Lookup of the name of an imported package or class e.g., A. B . C in the statements import A. B. C; import D=A. B • C; import A. B • C • * ;, deviates from the normal lookup by starting the lookup of the first part of the package/class name at the top level of the hierarchy. The lookup procedure for qualified names i.e., names like c. x and A. B • D • y with dot notation, is a somewhat more involved procedure. The lookup for the first part of a name i.e., c in c. x, or A in A. B . D • ¥, proceeds as described above, starting with the current scope. If no matching variable declaration is found, the first part of the name is assumed to be a package name. For a qualified name of the form A. B, or A. B • C, etc., lookup is performed as follows: 1. The first part of the name e.g., A, is looked up as defined in step 1 above. 2. If the first part of the name matches the name of a declared variable, the rest of the name e.g., B or B. C, is looked up among the named attributes (variables) of that variable, since the variable must be an instance of a record or other kind of class. 3. If the first part of the name denotes a class, typically a package, that class declaration is analyzed and temporarily expanded i.e., performing inheritance and modifications of the class in the lookup context of the hierarchy of enclosing classes of that class. The rest of the name e.g., B or B • c, is looked up among the declared named elements of that temporarily expanded class declaration. If the class is not a package, the lookup of the rest of the name is restricted to elements that are encapsulated packages or encapsulated classes. Such lookup can be used, e.g. to access a local version of the Modelica library embedded within a model restricted class that is not a package. See also Chapter 10, page 353. The top level of the package/class hierarchy referred to above can be viewed as an unnamed package containing declared elements loaded into the current workspace together with packages stored in the file
Chapter 3 Classes, Types, and Declarations 99 system at positions specified by MODELICAPATH. See Chapter 10, page 344 for more information on
MODELICAPATH.
3.13.3 Instance Hierarchy Lookup Using inner and outer As we already stated briefly in Section 3.11.8, standard nested lookup as described in the previous sections is not convenient in some situations where a pervasive object property should be accessible to all components of the object. For example: • • •
The components of a planetary system influenced by a common gravitational field. Electrons influenced by an electromagnetic field. An environmental temperature or pressure influencing the components of the system in question.
Section 5.8 in Chapter 5, page 173 contains a more thorough discussion of such applications, including the modeling of gravitational fields. As an example, the temperature of a circuit board (see the example below) should be accessible to all components on the board even though the classes of those components are not declared inside i.e., nested inside, the class of the board itself. Regarding the circuit board model, it is not practical to place the class definitions of the components inside a specific board class, since they should be usable also for models of other boards. Rather, the common property belongs to the object which contains the components in question. This leads us to the concept of lookup within the instance hierarchy. Based on these considerations, the inner/outer concept has been introduced in Modelica to provide access to common properties by specific definition and reference declarations, with lookup through the instance hierarchy that overrides the usual nested lookup: •
•
A declaration with the prefix inner is a definition declaration of an element that defines an object property or element in common to the components of the object, and therefore should be accessible from within those components. A declaration with the prefix outer is a reference declaration of an element that references a common property or element defined by a definition declaration in the enclosing instance hierarchy.
Note that the enclosing instance hierarchy is the hierarchy of parts/instances that the current instance is a member of. The following holds for an instance hierarchy lookup of the name of a reference declaration: •
• •
The search for a matching definition declaration (inner) with the same name as in the reference declaration (outer) is from the current instance to containing instances within the instance hierarchy of the reference declaration, not necessarily within the class nesting hierarchy. The definition declaration (inner) can be shadowed by nested declarations with the same name. The item declared in the definition declaration (inner) should be a subtype (see Section 3.14, page 100 in this chapter) of the type of the corresponding reference declaration (outer) or a subtype of an explicitly given constraining type. Also, the reference declaration should not have any modifications.
Note that instance hierarchy lookup is more selective than conventional lookup of global variables found in many other programming languages, since the search is only in the hiearchy starting at a specific instance. We give a simple example in terms of an electric circuit board CircuitBoardl containing temperature-dependent components that depend on a common board temperature. The two kinds of hierarchies, the usual class nesting hierarchy as well as the instance hierarchy, are depicted in Figure 3-8 for the EoardExample class shown in the following.
100 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica CircuitBoardl boardl: inner Real boardTempi
boardl
BoardExample
1\
c
TempResistor r: outer Real boar
r CircuitBoardl TempCapacitor
a) Instancehierarchy
TempResistor
b) Class nesting hierarchy
Figure 3-8. Instance hierarchy (a) and class nestinghierarchy (b) for the electriccircuit board example.
All components in the electric circuit board should reference exactly the same board temperature variable boardTemp, which is defined by an inner declaration within the Cireui tBoardl class. Each component contains an outer reference declaration referring to the board temperature boardTemp, which is found during the instance hierarchy lookup to be the inner board temperature boardTemp of CircuitBoardl since the components e and r belong to boardl. class BoardExample class CircuitBoardl inner Real BoardTempi
TempCapacitor c TempResistor r end CircuitBoardl;
II Definition of the board temperature variable "Component within CircuitBoardl instance"; "Component within CircuitBoardl instance";
class TempCapacitor outer Real BoardTempi
II Reference to the board temperature variable
Real Ti equation
T
= BoardTempi
end TempCapacitori
class TempResistor outer Real BoardTemp; Real T; equation T = BoardTemp; end TempResistori
CircuitBoardl board! end BoardExamplei
II
Reference to the board temperature variable
"CircuitBoardl instance";
For additional examples on how to use this facility see Section 5.7.5.5 in Chapter 5, page 172.
3.14 The Concepts of Type and Subtype What is a type? This is a relevant question in the context of programming languages. We are talking about the type of variables, of values, of classes, etc., making it important to convey some intuition about the concept. A type can conceptually be viewed as a set of values. When we say that the variable x has the type Real, we mean that the value of x belongs to the set of values represented by the type Real i.e., roughly the set of floating point numbers representable by Real, for the moment ignoring the fact that Real is also viewed as a class with certain attributes. Analogously, the variable b having Boolean type means that
Chapter 3 Classes, Types, and Declarations 101 the value of b belongs to the set of values {false, true} . The built-in types Real, Integer, String, Boolean are considered to be distinct types. The subtype relation between types is analogous to the subset relation between sets. A type Al being a subtype of type A means that the set of values corresponding to type Al is a subset of the set of values corresponding to type A. Thus the type TempResistor below is a subtype of Resistor since the set of temperature-dependent resistors is the subset of resistors having the additional variables (attributes) RT, Tref and Temp.The type Integer is not a subtype of Real in Modelica even though the set of primitive integer values is a subset of the primitive real values since there are some attributes of Real that are not part of Integer (see Figure 3-9).
Figure 3·9. Relationbetween the concepts of subtype and subset in the domainsof electrical components and animals. The supertype relation is the inverse of the subtype relation. Since TempResistor is a subtype of Resistor, then Resistor is a supertype ofTempResistor. model Resistor "Electrical resistor" Pin p, n "positive and negative pins"; Voltage v; Current i; parameter Real R(unit="Ohm") "Resistance"; equation v = i*R ; end Resistor ; model TempResistor "Temperature dependent electrical resistor" Pin p, n "positive and negative pins"; Voltage v; Current i; parameter Real R(unit="Ohm") "Resistance at reference Temp."; parameter Real RT(unit="Ohm/degC")=0 "Temp . dependent Resistance."; parameter Real Tref(unit="degC")=20 "Reference temperature."; Real Temp=20 "Actual temperature"; equation v = i*(R + RT*(Temp-Tref»; end TempResistor; The definitions of Pin, Voltage, and Current that are used in the resistor classes above were previously defined in Section 2.8.3, page 38.
102 Peter Fritzson Principles of Object-OrientedModeling and Simulation with Modelica
3.14.1 Conceptual Subtyping of Subranges and Enumeration Types Conceptually, a subrange is a subset of an ordered set of elements, defined as the ordered set of all elements from the first to the last element in the subrange. A number of programming languages e.g., Ada, Pascal, etc., allow the user to define subrange types of enumerable types, for example integer, subranges which appear as follows in Pascal: 2 . . 10
This subrange is conceptually a subtype of Integer and also a subrange type of integers from 2 to 10. The general idea of subrange subtypes as subsets of ordered enumerable elements is illustrated in Figure 3-10, where 5ma1l5izes is a subtype of A1l5izes, Int_l_2 a subtype of Int_l_4, and FalseBoolean a subtype of Boolean.
Figure 3·10. Conceptual subtypingexamples of enumeration types, integer ranges, and boolean ranges. However, general subrange subtyping as illustrated in this figure is not in the current version of Modelica. In Modelica we can define enumeration types e.g., as follows: type All5izes type 5mal15izes
= enumeration (small,
= enumeration (small,
medium , large, xlarge) i medium) i
According to the examples in Figure 3-10 and general subset relations, 5ma1l5izes should be a subtype of A1l5izes. However, this is not the case in the current version of Modelica, which does not support definition of subrange subtypes. Instead , subtyping of enumeration types usually requires type identity, see Section 3.14.9, page 107, based on the fact that two identical sets are subsets of each other. This restrictive subtyping rule might be extended in the future, but that will require enhancements in several places of the Modelica language. There is also a special enumeration type enumeration ( : ), which is a supertype of all possible enumeration types. For example: 51 52 53 54
enumeration (small, medium) i enumeration(small,medium ,large)i enumeration (small, medium, large) i enumeration ( :) i
II II II II
51 not subtype of 52 52 is not a supertype of 51 53 is a subtype of 52 51, 52, 53 are subtypes of 54
3.14.2 Tentative Record/Class Type Concept A record/class type in Modelica is conceptually the set of all possible record values of that record type, where each value contains named values for the variables (also known as fields or attributes) of that record. Thus, both the record field names and the record field types are significant when defining a record type. Duplicate field names in a type are not allowed. In general, a tentative definition of the type of a record/class with N elements can be given by a descriptor that is a set of pairs of the form (field-name, field-type) where field ordering is unspecified, analogous to several type systems for object-oriented languages by Luca Cardelli et aI. [Abadi-Cardelli-96]: (nameJ:typel, name2:type2, ... nameN:typeN)
Chapter3 Classes, Types, and Declarations 103 We will gradually develop this tentative type concept into a more general type concept suitable for all type aspects of the Modelica language. However, returning to the view of a record type as a set of record values, consider the Person record declaration below: record Person String name; Real weight; Real length; end Person;
A set of Person values might appear as follows, using a pseudosyntax for record values (not conforming to MOOeHea syntax), where both the field name tag and the field data value are part of a Person value: {(name:"Eve", weight:65, length:170) , (name r v.Adam'", weigth:80, length:180), etc. }
In general the ordering between the variables of a class is not considered significant except in two cases: 1. The ordering within the two sets: function formal parameters and function results. 2. The ordering between the variables of a record being passed to an external function. However, except for the case of function types, the ordering between variables (fields) is not considered significant for type checking. Therefore the following record value is also considered compatible with type Person: (weight:6S, length:170, name:"Carl")
3.14.3 Array Type An array type is conceptually a set of array values, where each array value can be considered as a set of pairs (array-element-index, array-value) analogous to the set of pairs (record-field-name, record-fieldvalue) that make up a record value. Thus, for a vector type with four elements, with the possible array indices '1" '2', '3" '4', where the array index is used as a name instead of the field name in a record, a set of array values with labeled array elements could appear as follows in pseudocode: { ('1' :35.1, ('1' :5.1,
'2' :77, '2' :11,
'3' :38, '4' :96), '3' :305, '4' :83), etc ...
}
Following our informal definition of array type, each possible index value for an array should also be part of the array type in the same way as all variable names of a record are significant. However, this is impractical when there is a large number of array elements and in cases where the number of array elements is unknown. Instead we will soon tum to a more compact type representation. Unspecified dimension sizes is generally the case for library functions operating on arrays. For example, the library function for inverting a matrix should work on any size of matrix, and therefore has the dimension sizes unspecified, causing the number of array elements to be unspecified. It would not make sense to have a separate inverting function for.2 x 2 matrices, another for 3 x 3 matrices, etc. Thus it must be possible to define array types for which certain array dimension sizes are unspecified. Two vector types in Modelica are shown below: type Vec2 = Real [2] ; type Vee = Real[:l;
II Vector type with specified dimension size II Vector type with unspecified dimension size
We now replace our informal set definition of array type above with a more compact type descriptor still with the same form as the one used for record types. This descriptor is a set containing a single pair (indexspecifier, element-type), which can be used since all array elements share the same clement type in contrast to records where variables (fields) usually have different types. In this array type representation the element-type is the type of the array elements and the index-specifier represents all possible legal indices
104 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica for the array where each dimension in an index is represented by a nonnegative size expression for the maximum index value of that the dimension, or a colon (:) representing unspecified dimension size: ( (index-specifier, element-type» The array type descriptors for the two types Vec2 and Vec would then become the following: ( (' 2', Real) ) ( (':', Real) )
Turning to the problem of representing multidimensional arrays we observe that in Modelica as well as in many programming languages a multidimensional array is defined as an array of arrays. Thus a 2 x 3 matrix type is viewed as a 2-sized vector of 3-sized vectors. For example: type Mat23 type 'Mat
= Real[2,3]i II Matrix type with specified dimension size
Real[:,:]i II Matrix type with unspecified dimension size
These two matrix types will have the following type representation given the array of arrays representation: ( (' 2',
« , 3', Real»
( (':', «':', Real»
) ) ) )
The subtype relation between two array types, A subtype of B, requires that the element-type of A is a subtype of the element-type of B and each corresponding dimension specifier in the index-specifier is either identical size or the dimension specifier of B is a colon (:). Thus, Mat 23 is a subtype of Mat. This is reasonable since arrays of type Mat23 can be used in places where type Mat is required, but not vice versa.
3.14.4 Function Type The definition of a function type is analogous to our definition of general class type above with the additional properties that the ordering between the fields (variables) i.e., the formal parameters of the function, is significant and that the prefixes input and output for each formal parameter are also part of the function type. A function with three input formal parameters and one result is actually quite different from a function with two input formal parameters and two results, even if the names and types of the formal parameters are the same in both cases. Two function types that are subtypes of each other also need to fulfill type equivalence as defined further below. This is more restrictive than subtyping for general class types. The reason is to avoid dealing with certain problematic issues regarding substitutability of functions (see Chapter 9 for more details on functions).
3.14.5 General Class Type Regarding function types we concluded in the previous section that the prefixes input and output are also part of the type. In fact, all type prefixes when present in the variable declarations within a class declaration i.e., flow, discrete, parameter, constant, input, output, as well as the final element prefix, are considered part of the class type not only for functions but for all kinds of classes in Modelica. The variability prefixes discrete, parameter, constant are considered part of the type since they influence the semantics and type checking of assignment statements and equations. The f low prefix is part of the type since it affects the semantics of connection equations. Finally, the final prefix influences the semantics of inheritance and modifications, described in more detail in Chapter 4. Thus, our tentative definition of a class type is generalized to be a sequence of pairs (element-name, element-prefixes&type) for all N public elements in the class, where element ordering is part of the type
Chapter 3 Classes, Types, and Declarations 105
but not used in type checking except in certain situations such as regarding functions, and index-specifier is used instead of element-name for array types: (namel: prefixesl&typel, name2: prefixes2&type2, ... nameN: prefixesN&typeN) Given the simple example function multiply below: function multiply; input Real Xi input Real Yi output Real resulti algorithm result := X*Yi end multiplYi
Using our general definition of type to represent this function we obtain the following: (x: input&Real, y: input&Real, result: output&Real)
3.14.6 Types of Classes That Contain Local Classes So far we have dealt primarily with classes that only contain attributes or fields (variables) that can contain data (,'data fields") i.e., similar to a classical record type. However, in Modelica it is possible to declare local classes inside a class, as, for example, the classes I C and BC inside the class RC2 below. class RC2 Real X; class IC Integer X; equation x = 2; end IC;
class
II
field
X
/1 Refers to local x inside
Ie
Be
Real y; equation
x
=
1/ Refers to x in
y;
end BC; IC ix; BC bx;
RC2
II field ix, instance of IC
II
field bx, instance of BC
equation X =
3.14;
end RC2; RC2
Z;
The three variables ("data fields") of class RC2 are x, ix, and bx. There are also two local classes (not "data fields") rc and BC inside RC2. They can be referred to only within the local scope of RC2, but in principle they could be moved outside RC2 with some changes of names. An outside class BC could appear as follows: class RC2 BC Real y;
II
Hypothetical BC outside RC2
II
Refers to x in the z instance of RC2
equation
z.bx.x
=
y;
end RC2_BC;
A version of RC2 referring to such external classes would appear as follows: class RC2 v2
II
Hypothetical RC2 referring to outside IC and BC
106 Peter Fritzson Principlesof Object-OrientedModeling and Simulation with Modelica Real X;
II field x
RC2_IC ix; RC2_BC bx;
II field ix, instance of RC2 IC II field bx, instance of RC2_BC
equation x
=
3.14;
end RC2_v2i
From this perspective it would be natural to include only the three "data fields" x, ix, and bx in the type of RC2. Operations on and use of data objects of type RC2 involve only these three "data fields". On the other hand the class RC2_ BC is not very general since it refers only to the z instance of RC2 in its equation z . bx. x = y. The hypothetical notation RC2 . bx. x in that equation is not possible since that would imply that bx is a class variable (see page 74), which is not the case. Also, class variables are not currently allowed in Modelica. Furthermore, one might argue that a class containing local classes is different from a class without local classes, and that the local types IC and Be need to be included anyway since they are referred to by ix and bx. These considerations have led to the design decision that in Modelica local classes are considered as elements of the type of the class within which they are declared. The "field name" of such a local class is the class name, and the type is the type representation of the local class as a set of pairs according to our general type representation, but for brevity denoted by names such as RC2 . IC and RC2 . BC. The general type representation of class RC2 then becomes as follows: (x: Real, tc. RC2.IC, Be: RC2.BC, ix: RC2.IC, bx: RC2.IC)
3.14.7 Subtyping and Type Equivalence Having defined the notion of type for the different kinds of classes and objects that can occur in Modelica, we need to tum to the issue of how and when types are used. Type equivalence is needed to ensure compatibility of data and objects in different situations such as equality between the left-hand side and the right hand-side in equations, ensuring that the types of all arguments to the array constructor are equivalent, etc. We have informally defined the notion of subtype as analogous to the notion of subset e.g., with the example of TempResistor being a subtype of Resistor. The notion of subtype is usually associated with the idea of specialization and substitutability: if T2 is a subtype of T 1, then an object of T2 should usually be allowed to be substituted instead of an object of TI, or assigned to a variable of type Tl e.g., a TempResistor being substituted for a Resistor. Below we will discuss the use of subtyping and type equivalence, and provide more precise definitions of those notions.
3.14.8 Use of Type Equivalence Type equivalence has the following main uses: •
•
The types of the left- and right-hand sides of equations (e.g., x = y) must be equivalent after first doing type coercion, e.g. an Integer expression at one side of an equation is automatically converted to a Real expression if the other side has type Real. Assignment statements. In an assignment statement e.g., a := expr, the type T2 of the right-hand side must be equivalent to the type 'I'l of the left-hand side after possible type coercions. For example, type conversions makes assignments such as Real [ :] vec : = {I, 2} possible, where the right-hand side has type Real [2] and the left side has type Real [: J, where the type of the left-hand side is coerced into Real [2 J• Additionally, the standard coercion rule of converting an Integer expression to a Real expression when it occurs at the right-hand side of an assignment to a Real variable is automatically applied in order to satisfy type equivalence.
Chapter 3 Classes, Types, and Declarations 107 •
The types of the arguments to the array construction function {} as well as to the relational operators (=, , ==, <arraydimension descriptor> <modifiers> A few simple examples of short class definitions with modifiers are shown below, all being modifications of the superclass Real: class Current
type Force3 type Voltage
Real(unit="mA"); Real [3J (un i t.«] "Nil, "N", liN"}) ; Real (unit="V", min=-220.0, max=220.0);
The mechanism of modifiers in a class definition is to replace inherited element declarations with the same names as in the modifiers by appropriately modified element declarations, where the modifications are merged with the original declarations. We show an example based on the class LowPassFilterl below. model LowPassFilterl constant Real ystart = 1; parameter Real T = 1; Real u, y(start=ystart); equation T*der(y) + y = Ui end LowPassFilterli
The contents of the class LowPassFilterl is inherited into LowPassFilter20, for which the declarations of ystart and T are modified. model LowPassFilter20 = LowPassFilterl(ystart=O, T=20);
The resulting class LowPassFilter20 is equivalent to the class LowPassFilter20B. model LowPassFilter20B constant Real ystart = 0; parameter Real T = 20; Real u, y(start= ystart); equation
T*der(y) + y = Ui end LowPassFilter20Bi
4.2.5 Modifiers in extends Clauses Modifiers may also occur in extends clauses, and are applied to inherited element declarations in a similar way as modifiers in short class definitions. Consider the previous example class LowPassFilterl. We inherit the contents of this class into the class LowPassFilter20C below, and give the same modifiers as in the short class definition of LowPassFilter20 above. The result is the same, and is equivalent to the class LowPassFilter20B.
Chapter 4 Inheritance, Modifications, andGenerics 123 model LowPassFilter20C extends LowpassFilterl(ystart=O, T=20); end LowPassFilter20Ci Another example demonstrates that modifiers in extends clauses can be applied to elements that are local classes such as Vol tage within the class LowVoltage below. class LowVoltage type Voltage = Real (unit=nv,,) ; Voltage vl; Voltage v2; end LowVoltage; class HighVoltage extends LowVoltage(Voltage(unit="kVn)); end HighVoltage; HighVoltage vhigh; The class HighVoltage has a local type Voltage with unit "kV", since it was modified compared to the original version of Vol tage in class LowVoltage. Thus, both variables vhigh. vl and vhigh. v2 have the unit "kv",
4.2.6 Modification of Nested extends Clauses The possibilities to apply modifiers are not limited to declared elements that are variables or local classes. In the example below we have a modifier in an extends clause: class
A
Real a; parameter Real h; end A; pa~ameter
class B extends A(b=3); end B; The class B inherits the class A and applies the modifier b=3 in the extends clause. The result is equivalent to the class Bexpanded. class Bexpanded parameter Real a; parameter Real b=3; end Bexpanded; It is actually possible to modify elements that are extends clauses in superclasses, so-called nested extends clauses, even though such clauses disappear in the expanded subclass, as shown below.
4.2.7 Priority of Modifications The more recent "outermost" modifications in a chain of modifications have priority over earlier modifications. However, consider the class c below with the modifier A (b=2) that modifies the nested extends clause extends A (b=3) of class B, which can be considered to be nested one level down in the inheritance chain where c inherits B, which inherits A. The modified extends clause then becomes extends A (b=2), giving a class C that is equivalent to Cexpanded with b=2. The most recent, i.e., "outermost", modifiers in the inheritance chain have priority over previous modifiers. In other words, the "innermost" extensions are expanded first. class C extends B(a=l, A(b=2));
124 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica end C; class Cexpanded parameter Real a=li parameter Real b=2i end Cexpandedi
The class Cl below illustrates the rule that the most recently applied "outermost" modifications like b= 1 override "inner" modifications such as A (b=2) of a nested extends clause, since b=2 is further down in the modification chain. The instance bcomp has bcomp.b=l, which overrides b=2 from the nested modifier. class Cl B
bcomp(b=l, A(b=2)
i
end Cli
Another example: the "outermost" modifier in the chain, b=66 in the class C4 below, overrides the nested modification of b in extends C2 (b=6) . Thus, merging the modifications (b=66), (b=6) gives the result (b=66). class C2 parameter Real bi parameter Real Ci end C2; class C3 extends C2(b=6,c=77)i end C3;
II
Inherited b gets default value 6
class C4 extends C3(b=66)i end C4;
II
The most recent modification of b
4.2.8 Modification of Protected Elements Protected elements may not be modified or redeclared in class modifications, despite the fact that protected elements are inherited. Consider the class D below, inherited by class Dl, which is correct. On the other hand, the definition of class D2 is illegal since it tries to modify the declaration of the variable b, which is protected. class D
Real ai protected
Real hi
II
a is a public element
II
b is a protected element
end D; class D1
D(a=lO)i
class D2
D(b=20)i
II II
Ok, since a is public Illegal since b is protected!
4.2.9 Hierarchical Modification Hierarchical modification means that elements one or more levels down in the instantiation hierarchy are modified. Such modifiers can use nested notation using parentheses or dot notation. We use a slightly enhanced version of the low-pass filter model from Section 2.3.4 on page 28 as an example. model LowPassFilter parameter Real T=l; parameter Real k=l; Real u, y(start=l)i
Chapter 4 Inheritance, Modifications,and Generics 125
equation T*der(y) + y = k*u; end LowPassFilteri Two instances of the filter with different time constants T are put together to form the class Fi 1 ters InSeries: model FilterslnSeries LowPassFilter Fl(T=2), F2(T=3); equation Fl.u = sin(time); F2.u = Fl.y; end FilterslnSeries;
Finally, two different instances F12 and F34 of FilterslnSeries are created in the class ModifiedFilterslnSeries with modified time constants. Both instances have identical time constants, but the first uses nested notation and the second uses dot notation for hierarchical modification. model ModifiedFilterslnSeries FilterslnSeries F12(Fl(T=6), F2(T=11, k=2)); FilterslnSeries F34(Fl.T=6, F2.T=ll, F2.k=2)i end ModifiedFilterslnSeries;
II nested notation II dot notation
Another example of hierarchical modification is shown for the class cs, where the instance anest uses nested syntax and the instance adot dot notation. Both of them produce identical results. class CS Real X; end C5i C5 anest(x(unit = "Vu, displayUnit="mVU) = 5.0)); CS adot(x.unit = "V", x.displayUnit="mV",
X=5.0)i
When using qualified names, the different qualified names starting with the same identifier are merged into one modifier during analysis of the modifiers. In the above example this would have the effect of converting the modifiers with dot notation in the declaration of adot to the nested notation used in the declaration of anest.
4.2.10 Single Modification Rule Two arguments of a modification are not allowed to denote the same attribute of a declared element. This is usually self-evident, but in the context of classes with array variables one may sometimes forget that the variable name denotes an array. For example, the first modifier argument to Cl below, x= {1 , 1 ,I}, means that all three array elements X [1] , x [2] , x [3] are set equal to I, which is in conflict with the second modifier x [2] =2. ("lass Cl Real x[3]; end Cli class C2 = Cl{x={l,l,l}, x[2]=2)i
II Error: x[2] designated twice
4.3 Redeclaration So far we have primarily dealt with modifiers that change the default value in a declaration. A more dramatic change is to modify the type and/or the prefixes of a declared element, i.e., the original
126 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica declaration is actually replaced by the "new declaration" given in the modifier merged with the modifiers of the original declaration should. This kind of modification is called a redeclaration and requires the special keyword redeclare to be used in the corresponding modifier in order to reduce the risk for accidental programming errors. The element to be redeclared has to be declared replaceable, except for the rather specific case when the only change is to restrict its variability (see Section 4.3.2 on page 127) and/or dimension sizes. The following contrived example illustrates a redeclaration. The used definitions of Resistor and TempResistor are available on page 100 in Chapter 3. class MiniCircuit replaceable discrete Resistor Rl; end MiniCircuit; MiniCircuit tempcircuitl(redeclare parameter TempResistor Rl);
The redeclaration of the Rl element changes its type from Resistor to TempResistor and its prefix from discrete to parameter. The resulting anonymous modified class, which is the type of tempcircui tl, is equivalent to MiniCircui t2. class MiniCircuit2 parameter TempResistor Rl; end MiniCircuit2;
The element that is provided in a redeclaration must have a type that is a subtype of the corresponding replaceable element in the modified class or a subtype of an explicitly given (optional) constraining type. This is fulfilled in the above example since TempResistor is a subtype of Resistor. The next example illustrates a redeclaration redeclare A2 z (y=2) used in an extends clause to replace the original declaration A z (x= 1) from class B, but merging the original nested modifier (x= 1 ) with the modifiers in the redeclaration to effectively get A2 z (x=l, y=2). The type of the redeclared variable z in class B is changed from A to A2 in class B2, which is correct since A2 is a subtype of A. class A parameter Real Xi end Ai class A2 parameter Real x=3.14; parameter Real Yi end A2;
II A2 is a subtype of A
class B replaceable A z(x=l)i end Bi class B2 extends B(redeclare A2 end B2;
z(y=2»i
The class B2 is equivalent to the class B2expanded below: class B2expanded A2 z(x=l,y=2)i end B2expanded;
4.3.1 Redeclaration of Elements not Declared replaceable Redeclarations usually require the modified element to be declared with the replaceable prefix. There are only two kinds of redeclarations that do not require the modified element to be declared replaceable:
Chapter 4 Inheritance, Modifications, and Generics 127
t. Restricting the variability of a declared variable, e.g., from parameter to constant. 2.
Restricting array dimension sizes, e.g., from (:) to a specified size.
The following example demonstrates these kinds of redeclarations: class C3 Real xl; Real [:] vec; end C3; class C4 = C3(redeclare parameter Real xl, redeclare Real[20] vec);
The class C4 is equivalent to the class C4expanded below. The variable xl has been restricted from continuous-time to parameter variability. class C4expanded parameter Real Real(20] end C4expanded;
xl; vec;
4.3.2 Modification Prefix: replaceable In the introduction to the topic of redeclaration we mentioned that the prefix replaceable usually must be attached at the front of those declarations in a superclass that are enabled for redeclaration in a subclass. This corresponds to virtual in some other object-oriented languages like C++ and Simula, Note that, e.g., in Java, the default rule is to allow redeclaration of all members at inheritance, i.e., all members are replaceable. Only members declared final in Java are not allowed to be redeclared. In Modelica the default is to disallow redeclaration of class members unless they have been explicitly declared as replaceable, apart from the two exceptions mentioned in the previous section. The main motivation for this rule is that a class needs to be designed for inheritance that includes redeclaration. Otherwise unexpected errors may occur. We have previously stated that the element that is provided in a redeclaration must have a type that is a subtype of the corresponding replaceable element in the modified class or a subtype of an explicitly given (optional) constraining type (see Section, 4.3.5, page 129). The motivation to this rule is similar to the above, i.e., to prevent errors. An element that fulfills the subtype condition has a reasonable chance of keeping the contract of the original element to be replaced. Summarizing the main points of the replaceable prefix: •
A declared element of a class must have the prefix replaceable in order to be redeclared, apart from redeclarations that only change the attribute value and/or restrict the variability and possibly the dimension sizes.
A trivial example of a class with a replaceable element: class MicroCircuit replaceable Resistor Rl; end MicroCircuit;
Replaceable elements of a class can be regarded as a kind of formal parameters of that class. The use of such class parameters is described in more detail in Section 4.4 regarding generic classes on page 133.
4.3.3 Modification Prefix: redeclare The modification prefix redeclare is used only in modifiers and is needed when a whole declaration is included in the modifier. Those modifiers that use the prefix redeclare are known as redeclarations. To summarize the main points:
128 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica •
The redeclare prefix is used at the front of a modifier containing a new variable or type declaration t hat replaces the original variable or type declaration element in the modifiedclass.
The reason for requiring a special keyword like redeclare to be used in a redeclaration is to reduce the risk for accidental programming errors that otherwise might occur when whole declarations are replaced by declarations of different types. A correct example is shown below where the variable Rl of type Resistor is redeclared as a TempResistor, which is a subtype of Resistor, obtaining a temperature-dependent circuit: TempMicroCircuit
= MicroCircuit(redeclare TempResistor Rl)i
In order to allow further redeclarationof a redeclared element the replaceable prefix should be present also in the modifier: TempMicroCircuit2 = MicroCircuit(redeclare replaceable TempResistor Rl)i
This allows further redeclaration, which otherwise would not be possible: SuperTempMicroCircuit
=
TempMicroCircuit2(redeclare SuperTempResistor Rl)i
Redeclarations can sometimes be regarded as a kind of actual arguments to classes when modifying generic classes in order to create more specialized classes, see Section 4.4 regarding generic classes on page 133.
4.3.4
Modification Prevention Prefix: final
The class designer may wish to prevent certain modifications since the correct semantics of a class can be dependent on details of its declared members. A user who is not aware of those details can otherwise unknowinglyintroduce errors. The final prefix can be used to prevent such modifications. A variable declared as final in a member modification cannot be further modified by another modification. All members of a final member are also final, e.g., the variables of a final member that is a record are final. To summarize the rules for final: • •
The final prefix in front of a variable or class declaration prevents modification and redeclaration of the variable, the class, and the membersof the class. The f ina1 prefix in a modifier preventsfurther modifications of the modifiedelement.
In the example with the type Angle below, the members quantity and unit are declared final and cannot be further modified, whereas it is fine to modify the declarationof the variable di splayUni t. type Angle = Real(final quantity "Angle", final unit = "rad", displayUnit = "deg")i Angle al(unit="deg")i II Error, since unit declared as finall Angle a2(displayUnit="rad")i II Fine!
Another, slightly more advanced example of the use of final involves a model that is used as a transfer function within a PI controller. The numeratorand denominator coefficient vectors b and a of the transfer block instance tf in the PI controller cannot be modified since they have been declared final. For a detailed explanation of the array notation see Chapter 7. block TransferBlock II works like a" transfer function parameter Real b[:] = {l} "numerator coefficient vector"i parameter Real a[:] = {l,l} "denominator coefficient vector"; protected size(b,l); constant Integer nb(max=na) size(a,l); constant Integer na
Chapter 4 Inheritance, Modifications, and Generics 129 constant Integer n Real[n] x Real rna] bO equation
na-I; "State vector"; cat(I,zeros(na-nb), b);
end TransferBlock; model PI "PI controller" parameter Real k=l "gain"; parameter Real T=l "time constant"; TransferBlock tf(final b={T,l}, final a={T,O})i end PI; model Test PI cl(k=2, T=3)i PI c2 (t f .b= {1 }) ; end Test;
II Fine!
II
Error, b is declared as final
A final declaration of a variable also has implications for interactive setting of parameter variables in the simulation environment, since setting of the value of a parameter in a simulation environment is conceptually treated as a modification. This implies that a final declaration or modification of a parameter cannot be changed in a simulation environment.
4.3.5 Constraining Type of Replaceable Elements A declaration of a replaceable element of a class can have one of the following two forms, where the element declaration represents either a variable or a local class declaration. The extends keyword in the second form has nothing to do with inheritance; it is just a reuse of the keyword for a different purpose. I. 2.
replaceable <element declaration> replaceable <element declaration> extends
So far, we have only seen examples of the first form of replaceable element. However, it will soon be apparent that the second form is quite useful in certain situations. It is, however, recommended to avoid modifiers in the constraining type. We state once more the subtyping condition of redeclaration: •
The declaration element that is provided in a redeclaration must have a type that is a subtype of the type of the corresponding replaceable element in the modified class or a subtype of an explicitly given (optional) constraining type.
Thus, the constraining type is either stated explicitly or otherwise defined as the type of the replaceable element. Being a subtype of the replaceable element is fulfilled in the example below, e.g., when replacing the resistor component compI with a temperature-dependent resistor: class MicrOCircuit replaceable Resistor compl; end MicrOCircuit; TempMicroCircuit = MicroCircuit (redeclare TempResistor compl);
We turn MicroCircuit into a more generic circuit called GenMicroCircuit. The type CompType of the component campl has been made replaceable. class GenMicroCircuit replaceable type CompType = Resistor; replaceable CompType compl; end GenMicroCircuit;
130 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica The idea is to be able to specialize the generic circuit into a circuit that can use types of components other than resistors, e.g., capacitors or inductors. We try to define an inductor circuit class below, but this fails since Inductor is not a subtype of CompType, which currently is Resistor!
II Type error! Inductor is not subtype of Resistor! class InductorMicroCircuit = GenMicroCircuit(redeclare type CompType
= Inductor);
The problem is that the constraining type of CompType is too restrictive, just using its current default value which is Resistor. Instead we would like to express that CompType can be any electrical component type with two pins, i.e., CompType should be a subtype of TwoPin. Here the second form of replaceable element declaration comes into play, which allows us to express the constraining type explicitly by adding extends TwoPin. The use of the keyword extends here has nothing to do with inheritance. class GenMicroCircuit replaceable type CompType = Resistor II No inheritance! replaceable CompType compl; end GenMicroCircuiti
extends TwoPin;
After this change, there is no problem to define a more specific circuit, e.g., using the component type Capacitor: class CapacitorMicroCircuit = GenMicroCircuit(redeclare type CompType
= Capacitor);
However, this capacitor circuit has no replaceable CompType declaration left since the original replaceable declaration was replaced. To keep CompType replaceable we need to perform a redeclaration with redeclare replaceable as in the class below. In this case we might want to set the constraining type to GenCapacitor in order to have a more specific constraint than TwoPin. class GenCapacitorMicroCircuit = GenMicroCircuit( redeclare replaceable type CompType = Capacitor extends GenCapacitor);
Further redeclaration is now possible, e.g., using a temperature-dependent capacitor: class TempCapacitorMicroCircuit = GenCapacitorMicroCircuit(redeclare type CompType = TempCapacitor);
There is also a subtyping condition for the constraining type optionally provided in a replaceable redeclaration: •
The constraining type of a replaceable redeclaration must be a subtype of the constraining type of the declaration it redeclares.
This condition is fulfilled for GenCapacitorMicroCircuit above since the constraining type GenCapac i tor is a subtype of TwoPin. The following rule applies to modifications of replaceable elements with constraining types: •
In an element modification of a replaceable element the modifications are applied to the actual type and also to the constraining type provided the modified attribute exists in the constraining type.
Thus the modifier R=20 in the definition of MicroCircuit3 is propagated to both the declaration and the constraining type, which is apparent in the class MicroCircuit3expanded. class MicroCircuit2 replaceable TempResistor Rl end MicroCircuit2;
extends Resistor;
class MicroCircuit3 = MicroCircuit2(Rl(R=20»i
Chapter 4 Inheritance, Modifications, and Generics 131 class MicroCircuit3expanded replaceable TempResistor Rl(R=20) extends Resistor(R=20)i end MicroCircuit3expanded;
There is one additional rule concerning propagation of modifiers for the case of modifiers in the constraining type: •
In an element redeclaration of a replaceable element the modifiers of the replaced constraining type are merged both to the new declaration and to the new constraining type, using the normal rules where the most recent "outermost" modifiers override earlier modifiers (see Section 4.2.7).
The modifier R=30 for the MicroCircui tSexpanded below.
constraining
class MicroCircuit4 replaceable TempResistor Rl
type
Resistor
is
merged
into
Rl,
see
extends Resistor(R=30)i
end MicroCircuit4; class MicroCircuitS = MicroCircuit4( redeclare replaceable TempResistor2 Rl
extends Resistor2);
class MicroCircuitSexpanded replaceable TempResistor2 Rl(R=30) extends Resistor2(R=30)i end MicroCircuitSexpanded;
4.3.6 Summary of Restrictions on Redeclarations The following is a summary of the constraints that apply to redeclarations apart from the restrictions related to constraining types and redeclarations described in the previous section. Several constraints are stated explicitly for clarity even though they follow autornatically from the subtyping constraint, given the general definition of type described in Chapter 3, page 100. •
•
Only classes and variables declared as replaceable can be redeclared with a different type, which must be a subtype of the constraining type of the original declaration. To allow further redeclarations of the redeclared element one must use "redeclare replaceable. " Redeclaration of elements not declared as replaceable is allowed with the same type and the same or more restrictive variability and array dimension sizes. A replaceable class used in an extends clause, e.g., the ResistorModel below, must contain only public elements. If the replaceable class were to contain protected elements, e.g. the protected variables of the replaceable default class, it cannot be guaranteed that those variables would be kept after redeclaration. class GenResistor replaceable class ResistorModel=Resistor; extenda ResistorModel; end GenResistori
• •
• • •
An element declared as constant or final cannot be redeclared. The variability of a declared element must be kept the same or decrease at redeclaration, e.g., parameter may change to parameter or constant; discrete may change to discrete, parameter, or constant; continuous-time may change to continuous-time, discrete, parameter,orconstant. A function can only be redeclared as a function. The f low properties of an element cannot be changed at redeclaration. The access properties of an element, i.e., public or protected, cannot be changed at redeclaration.
132 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
4.3.7 Redeclarations of Annotation Choices Apart from textual Modelica programming, redeclarations may also be specified through a graphical user interface (GUI) of a Modelica modeling tool, e.g., via menu choices. The user interface can suggest reasonable redeclarations, where the string comment in the choice declaration can be used as a textual explanation of a choice. Based on the interactions with the user, the GUI then generates the appropriate Modelica code. The annotationcan also be used as a hint to the user doing textual Modelica programming. In order to support this mode of operation, an annotation (see Section 11.3.6, page 368) called choices containing choice elements is predefined to be recognized with certain semantics in Modelica, including recognition of redeclaration statements in the annotation. For example, consider the following replaceable model with a choices annotation: replaceable model MyResistor=Resistor annotation (choices ( choice (redeclare MyResistor=lib2.Resistor(a={2}) "~"), choice(redeclare MyResistor=lib2.Resistor2 "~")));
If the user would choose the first alternative, the following code might be produced if MyResistor is part of the class MyCircui t and the chosen name of the instantiated component is x: MyCircuit x(redeclare MyResistor=lib2.Resistor(a={2}))
Additional examples of replaceable class declarations with redeclaration choices are shown below: replaceable Resistor Load(R=2) extends TwoPin annotation (choices ( choice(redeclare lib2.Resistor Load(a={2}) "~"), choice(redeclare Capacitor Load(L=3) "..."»)); replaceable FrictionFunction a(func=exp) extends Friction annotation (choices ( choice(redeclare ConstantFriction a(c=l) "~"), choice(redeclare TableFriction a(table=" ...") "..."), choice (redeclare FunctionFriction a (f unceexp) "..."»)
i
The choices annotation is not restricted to replaceable elements. It is also applicable to nonreplaceable elements, simple variables, and types used for enumerations. For example, consider the following Integer type called KindOfController used to represent a choice of controller in the modeling process out of the following enumeration of three recommended alternatives: type KindOfController = Integer(min annotation (choices ( choice 1 "P", choice = 2 "PI", choice = 3 "PIon));
=
1,max =
3)
Assume that KindOfController is used in a model A as below: model A KindOfController end A;
Xi
An interactive choice of the third alternative from a menu containing the alternatives {If pi'," PI"," PlD" } would result in the default value 3 for the instantiated variable x in the following code for an instance a2 of the model A: A
a2(x=3 "PID");
Chapter4 Inheritance, Modifications, and Generics 133
4.4 Parameterized Generic Classes In many situations it is advantageous to be able to express generic patterns for models or programs. Instead of writing many similar pieces of code with essentially the same structure, a substantial amount of coding and software maintenance can be avoided by directly expressing the general structure of the problem and providing the specific information as parameters. Such generic constructs are available in several programming languages, e.g., templates in C++, generics in Ada, functions and packages with type parameters in functional languages such as Haskell or Standard ML. Similar capability is provided in Modelica. In fact, the Modelica class concept is sufficiently general to handle both generic programming and object-oriented modeling within a single construct. There are essentially two main cases of generic class parameterization in Modelica: 1. Instance formal parameters, for which variable declarations are supplied as actual arguments. 2. Type formal parameters, for which classes are supplied as actual arguments. Interface parameterization of a class is a natural consequence where the class formal parameters are connector classes or connector variables belonging to the class. Note that by class parameterization in this context we do not mean simulation parameter variables prefixed by the keyword parameter, even though such variables can also be class formal parameters. Instead we mean formal parameters to the class. Such formal parameters are prefixed by the keyword replaceable. The special case of replaceable local functions is roughly equivalent to vinual methods in some object-oriented programming languages.
4.4.1 Class Parameterization Using Replaceable and Redeclare Modelica classes and packages can be parameterized in a general way, corresponding to generic classes or packages. Both classes and variables which are members of some class can be used as a kind of formal class parameter by attaching the prefix replaceable in front of their declarations. As we have seen in the previous Section 4.3 about redeclaration on page 125 in this chapter, a declared variable can be replaced by a variable of a different type that must be a subtype of the constraining type of the replaced variable. Additionally, a locally declared type can be replaced by another type. The replaceable prefix must be put in front of declared elements that can be replaced. To summarize: • •
Formal class parameters are replaceable variable or type declarations within the class (usually) marked with the prefix replaceable. Actual arguments to classes are modifiers, which when containing whole variable declarations or types are preceded by the prefix redeclare.
In Section 2.5, page 30, we gave two examples of parameterized classes: in the first case the formal parameters were colored objects, i.e., class parameters being components or variables. In the second example, the color type itself was the class parameter. Here we use the simple ResistorCircuit of three resistors connected at one node, (see Figure 4-3), as an example of a class that can be converted into different variants of generic classes. More details about the connections semantics of this class is available in Section 5.4.3, page 155.
R1
R2
R3 Figure 4-3. Schematic picture of the ResistorCircuit.
134 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica model ResistorCircuit II Circuit of 3 resistors connected at one node Resistor Rl(R=lOO)i Resistor R2(R=200)i Resistor R3(R=300); equation connect (Rl.p, R2.p); connect (Rl.p, R3.p); end ResistorCircuiti
In the next two sections the two main kinds of class parameterization are discussed, using the resistor circuit as the primary example.
4.4.2 Class Parameters Being Components First we present the case when class parameters are components, i.e., instances or objects, also called variables. Also compare to the color class example in Section 4.1 on page 112. The class ResistorCircuit has been converted into a parameterized generic class GenericResistorCircuit in the example below with three formal class parameters Rl, R2, R3 marked by the keyword replaceable. These class parameters are declared as having the default type Resistor. model GenericResistorCircuit II The resistor circuit made generic replaceable Resistor Rl(R=lOO)i replaceable Resistor R2(R=200) i replaceable Resistor R3(R=300) i equation connect (Rl.p, R2.p)i connect (Rl.p, R3.p)i end GenericResistorCircuit;
Subsequently a more specialized class TemperatureDependentResistorCircuit is created by changing the types of Rl and R2 to TempResistor, which is a subtype of Resistor, by supplying TempResistor declarations of Rl and R2 as actual arguments when creating a modified class out of GenericResistorCircuit. The keyword redeclare must precede a whole. declaration actual argument to a formal class parameter: model TemperatureDependentResistorCircuit = GenericResistorCircuit( redeclare TempResistor Rl, redeclare TempResistor R2 ) ;
We also add a temperature variable Temp for the temperature of the resistor circuit, and modifiers for the component Rl, which now is a TempResistor, to set the temperature-dependent resistance parameter RT to O.1 and the resistor temperature Temp to the circuit temperature Temp. The standard class syntax is used rather than the previous short class definition. model TemperatureDependentResistorCircuit Real Tempi extends GenericResistorCircuit( redeclare TempResistor Rl(RT=O.l, Temp=Temp), redeclare TempResistor R2 ) i
end TemperatureDependentResistorCircuit;
This class is equivalent to the class below. The prefix replaceable has been lost for Rl and R2, since we did not use redeclare replaceable. model TempDepResistorCircuitlnherited Real Temp; TempResistor Rl(R=100, RT=O.l, Temp=Temp)i
Chapter 4 Inheritance, Modifications, and Generics 135
TempResistor R2(R=200) i replaceable Resistor R3(R=300); equation connect (Rl.p, R2.p) i connect (Rl.p, R3.p) j end TempDepResistorCircuitlnherited;
4.4.3 Generalizing Constraining Types of Class Parameters Sometimes it can be useful to allow a more general constraining type of a class parameter, e.g., TwoPin instead of Resistor for the formal class parameters and components compl and comp2 below. This allows replacement by another kind of electrical component than a resistor in the circuit.
model GeneralResistorCircuit replaceable Resistor compl(R=IOO) extends TwoPini replaceable Resistor comp2(R=200) extends TwoPinj replaceable Resistor R3(R=300); equation connect (Rl.p, R2.p) i conn.ct(Rl.p, R3.p) j end GeneralResistorCircuit Here, the resistors Rl and R2 can be replaced by any electrical component which is a subtype of model TwoPin, as in the following redeclaration. The generalized parameterization properties of GeneralResistorCircuit are used below when replacing the circuit components compl and comp2 with components of the types Capacitor and Inductor that are subtypes OfTwoPin.
model RefinedResistorCircuit extends GeneralResistorCircuit(radeclare Capacitor compl(C=O.003), redeclare Inductor comp2(L=O.0002) ) i end RefinedResistorCircuit;
4.4.4 Class Parameters Being Types A formal class parameter can also be a type, which is useful for changing the type of many objects. For example, by providing a type parameter ResistorModel in the generic class below it is easy to change the resistor type of all objects of type ResistorModel, e.g., from the default type Resistor to the temperature-dependent type TempResistor. The class GenericResistorCircuit2 is denoted as generic since it is valid for many possible values of the class parameter ResistorModel. Also compare to the ColoredClass class parameter example in Section 2.5.2 on page 31.
model GenericResistorCircuit2 II A generic resistor circuit replaceable model ResistorModel = Resistor; ResistorModel Rl(R=lOO); ResistorModel R2(R=200): ResistorModel R3(R=300) j equation connect (Rl.p, R2.p); connect (Rl.p, R3.p); end GenericResistorCircuit2; A more specialized temperature-dependent circuit RefinedResistorCircuit2 (which is not generic) can be created where the resistor type TempResistor is supplied as an actual argument value for the formal class parameter ResistorModel:
136 Peter Fritzson Principles of Object-OrientedModeling and Simulation with Modelica model RefinedResistorCircuit2 = GenericResistorCircuit2(redeclare model ResistorModel
TempResistor);
This class is equivalent to the following "expanded" class: model RefinedResistorCircuit2expanded TempResistor Rl(R=100); TempResistor R2(R=200)i TempResistor R3(R=300); equation connect(Rl.p, R2.p); connect(Rl.p, R3.p); end RefinedResistorCircuit2expanded;
II A generic resistor circuit
4.4.5 Parameterization and Extension of Interfaces External interfaces to component classes are defined primarily through the use of connectors. The topic of connectors and connections is primarily dealt with in Chapter 5, but here we describe parameterization and extensions of such interfaces. For example, assume that we have a definition of a Tank model in a model library. The Tank model is depicted in Figure 4-4 and as the class Tank declared below. The model has an external interface in terms of the connectors inlet and outlet, as well as a formal class parameter TankStream, which is a connector class with its default class value being the Stream connector class.
Figure 4-4. A tank with connectors inlet and outlet.
model Tank parameter Real Area=1; replaceable connector TankStream = Stream; II Class parameterization TankStream inlet, outlet; II The connectors Real level; equation II Mass balance inlet.volumeFlowRate + outlet.volumeFlowRatei Area*der (level) inlet.pressure; outlet.pressure end Tank; connector Stream II Connector class Real pressure; flow Real volumeFlowRate; end Stream;
We would like to extend the Tank model to include temperature-dependent effects, analogous to how we extended a resistor to a temperature-dependent resistor. This involves extension both of the connectorbased external interface of the class Tank and of its model equations. The result is the temperaturedependent Tank model called HeatTank. A new connector class HeatStream is defined as an extension of the previous connector class Stream, and provided as an actual argument, i.e., redeclaration, when defining the class HeatTank.
Chapter 4 Inheritance, Modifications, and Generics 137
model HeatTank extends Tank(redeclare connector TankStream HeatStream); Real temp; equation II Energy balance for temperature effects Area*level*der(temp) = inlet.volumeFlowRate*inlet.temp + outlet.volumeFlowRate*outlet.tempi outlet.temp = temp; II Perfect mixing assumed. end HeatTanki connector HeatStream extends Stream; Real tempi end HeatStreami The definition of HeatTank is equivalent to the following class definition: model HeatTankExpanded parameter Real Area=l; TankStream inlet, outlet; Real level; Real temp; connector TankStream Real pressure; flow Real volumeFlowRatei Real tempi end TankStreami equation II Mass balance: Area*der(level) = inlet.volumeFlowRate + outlet.volumeFlowRatei outlet.pressure = inlet.pressure; II Energy balance: Area*level*der(temp) inlet.volumeFlowRate * inlet.temp + outlet.volumeFlowRate * outlet.tempi outlet.temp = tempi end HeatTankExpandedi
4.5 Designing a Class to Be Extended At this stage, it should be apparent to the reader that a class needs to be carefully designed to be extended. Otherwise, it will often be misused by derived classes, or may not be possible to extend at all. One example is our by now well-known Resistor class, also shown below. It has a lot in common with the TempResistor class, also shown below. Unfortunately, Resistor cannot be inherited by TempResistor since the constitutive resistor equation v=i *R would still be kept together with the new temperature-dependent Resistor equation if we try to inherit from Resistor, giving conflicts between the two equations and an overdetermined system of equations. The conclusion is that the Resistor class should be designed for extending only its data declarations since the behavior in terms of equation(s) creates problems, or otherwise be designed to allow replacement also of the behavior. Thus there are at least two design goals when designing a class to be extended: • •
Reuse of data, i.e., variable declarations. Reuse of behavior, i.e., equations.
We will explore both of these possibilities. Another aspect to consider is that any non-f inal class, i.e., any class not declared final, has two interfaces. The public interface is for code referring to the class, e.g., through its connectors or other public elements. The protected interface is for code inheriting the class since protected declarations are
138 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica inherited. Both interfaces are real contracts between the class designer and user, and should be designed carefully. If a class can be extended we should also design its protected parts carefully and especially consider whether protected elements really are necessary. The result might be to have no protected elements in the superclass, if it does not need any special access.
4.5.1 Reuse of Variable Declarations from Partial Base Classes One way of getting around the problems of inheriting and specializing behavior, exemplified with the Resistor class below, is to create incomplete, i.e., partial, base classes that can be inherited. model Resistor "Electrical resistor" extends TwoPini II TwoPin, see Section 2.9, page 39. parameter Real R(unit="Ohm") "Resistance"; equation v = i*R; end Resistor; model Te~pResistor "Temperature dependent electrical resistor" extends TwoPini II TwoPin, see Section 2.9, page 39. parameter Real R(unit="Ohm n ) "Resistance at reference Temp."i parameter Real RT(unit="Ohm/degCn)=O "Temp. dependent Resistance."i parameter Real Tref(unit="degC")=20 "Reference temperature."; Real Temp=20 "Actual temperature"; equation v = i*(R + RT*(Temp-Tref))j end TempResistorj
Such partial base classes can be made to contain only the data declarations that can be reused. partial model BaseResistor "Electrical resistor" Pin p, nj "positive and negative pins"i Voltage Vi Current i; parameter Real R(unit="Ohm") "Resistance";
end BaseResistor;
This is a partial class since it does not contain enough equations to completely specify its physical behavior, and is therefore prefixed by the keyword partial. The keyword is optional when items referred to by the class are available. Partial classes are usually known as abstract classes in other object-oriented languages. Using the BaseResistor partial class the two classes Resistor2 and TempResistor2, equivalent to the Resistor and TempResistor above, can be defined to reuse all common variable declarations in the base class. model Resistor2 "Electrical resistor" extends BaseResistorj equation v = i*R; end Resistor2; model TempResistor2 "Temperature dependent electrical resistor" extends BaseResistori parameter Real RT(unit="Ohm/degCn)=O "Temp. dependent Resistance."i parameter Real Tref(unit="degC")=20 "Reference temperature."; Real Temp=20 "Actual temperature"; equation V = i*(R + RT*(Temp-Tref»)i end TempResistor;
Chapter 4 Inheritance, Modifications, and Generics 139
The drawback of this approach is that we have essentially given up on reuse and inheritance of behavior when part of the behavior needs to be redefined. In the next section we examine a way to get around that problem.
4.5.2 Extending and Redefining Behavior Redefining behavior when classes are extended is not a problem in standard object-oriented languages such as Java and C++ since behavior is contained in named methods. One named method of a class can be replaced by another method with the same name in the extended class. This solution is not possible in Modelica since behavior is primarily represented by unnamed equations. There is no general simple mechanism to name equations in Modelica, but fortunately there are two ways to indirectly associate a name with equation(s): • •
A declaration equation named by its variable. A group of equations stored in a named replaceable local class.
The first possibility is to use the fact that a declaration equation is implicitly named by the variable that is declared in the declaration. However, such equations are seldom useful for general representation and specialization of behavior since they are closely tied to the declaration of the variable that is declared, e.g., the variable might be declared in an inherited class but the equation may refer to variables in the current class. The second method is to put the class's equation(s) that might need replacement into a replaceable local class that is inherited into the class itself. The local class ResistorEquation within the class Resistor3 below is an example of this technique. Resistor3 has the same variables and behavior as Resistor, but allows redeclaration of its equations since they are defined in the replaceable class ResistorEquation. model Resistor3 "Electrical resistor" Pin P, n; "positive and negative pins"; parameter Real R(unit="Ohm") "Resistance"; replaceable class ResistorEquation Voltage Vi Current ii equation v = i*R;
end ResistorEquation; extends ResistorEquation; end Resistor3;
The temperature-dependent resistor class TempResistor3, essentially equivalent to the previous TempResistor, can inherit Resister3 by declaring its temperature-dependent equation in a redeclaration class ResistorEquation that replaces the original local class Resif3torEquation. Note that in this case we have supplied a whole new class declaration within the redeclaration model TempResistor3 "Temperature dependent electrical resistor" extends Resistor3( redeclare class ResistorEquation Voltage Vi Current i; equation v = i*(R + RT*(Temp-Tref)); end ResistorEquation; ) ;
parameter Real RT(unit="Ohm/degC")=O parameter Real Tref(unit="degC")=20 Real Temp=20 end TempResistor3;
"Temp. dependent Resistance."; "Reference temperature."; "Actual temperature";
140 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica The described method of redefining behavior at inheritance by collecting equations into replaceable local classes works, but is somewhat clumsy. It is possible to allow further redefinition of the behavior of a derived class such as TempResistor3 by using redeclare replaceable in the redeclaration instead of just redeclare.
4.6 Summary In this chapter we presented the Modelica version of one of the major benefits of object orientation: the ability to inherit behavior and properties from an existing class. The presentation started by reorganizing the previous moon landing example to use inheritance, and thereby achieving a certain degree of reuse. We continued by presenting the concepts of modification and redeclaration in Modelica, which provide particularly concise and elegant ways of expressing inheritance in many situations. We concluded by describing how to define and use generic classes in Modelica, as well as designing a class to be extended.
4.7 Literature The primary reference documents for this chapter are the Modelica language specification (Modelica Association 2003) and tutorial (Modelica Association 2000). Modelica inheritance is quite similar to Java inheritance, e.g. as described in (Arnold and Gosling 1999). Diamond inheritance is mentioned, e.g. in (Szyperski 1997). Inheritance in conjunction with the idea of a contract between a software designer and user is discussed in for example (Booch 1994; Meyer 1997).
4.8 Exercises Exercise 4-1:
Inheritance: class Animal Boolean isAlive = true; Boolean talks = false; end Animal;
Define a class, Bird, that inherits from the class Animal. Give the variables values.
Question: What value has the variable talks in the class Bird? Exercise 4-2:
Create Subclasses and Superclasses: In this exercise you should create a partial class Vehicle with the variable speed. You should also create four classes; Car, Boat, Train, and Bicycle, which inherit from Vehicle. Remember the variables for each subclass, which you can see in the figure below.
nrOfCarriages
Chapter 4 Inheritance, Modifications, and Generics 141 Let's write an instance of Train! Exercise 4-3:
Using Inheritance and Access Control: Write a class, Person, with the variables name, weight, and 10, where ID should be protected. The next class Employed should inherit from Person and have a protected variable, salary. The last class, Progranuner, contains the variables favProgLang (favorite programming language) and drinksJoltCola. Question: Which protected variable(s) does the class Employed have? Use the same class Person, but use this changed class Employed below: class Employed2 protected
extends Person; protected
Real salary; end Employed2;
Now which protected variable(s) does the class Employed have? Exercise 4-4:
Question: What does a modifier do? Easy Modifying Example: Modify • • •
the start value to 3, the min value to -22 and the fixed value to true
of the variable test in the class Test below. class Test parameter Integer test; end Test;
Exercise 4-5:
Modifiers for Array Values: In this exercise you should modify different values of the following variables: • • • • •
Set fixed to true in AI. Set the start value to false in truthvalues. Set unit to "kv" in the position: first row and second column of A2. Set the start value on the first row in A3 to the values 3, 5, and 8. In the second row of the matrix the values should be set to 3, 10, and 22. Set the matrix elements to "p i pp L" in A4.
class ModArray Integer AI[S];
Boolean truthvalues[2]; Real A2[2,2]; Integer A3[2,3]; Real A4[2,2]; end ModArraYi
Tip: Remember that each attribute has the same dimensionality as the array itself. Read more about predefined types/classes in Section 3.9. Read more about array construction in Chapter 7. Exercise 4-6:
Modification and Access Control: The class Mod, below, contains five variables. Are you allowed to modify all of them? Why or why not?
142 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica class Mod parameter parameter parameter protected parameter parameter end Mod;
Real Xi Real Yi Real Zi Real w; Real s;
Exercise 4-7: Inheritance Through Modification: Declare a Real variable temp with the unit "deqc" in the class Temperature. class Temperature end Temperature;
Use short class definition and create a new class Temp20 that modifies the variable temp in Temperature to be equal to 20. Do the same thing as in Temp20, but this time Temp20 should inherit from Temperature. Tip: The variable temp must be a parameter so it can be modified in the short class definition. Exercise 4-8: Applying Hierarchical Modification: Today you are going on a lunch date! To help you, several classes are created below.
The first class is DayName, contains the parameter nameOfDay, a certain day written as a String. The second class, LunchAppointment, contains the variables lunchTime (what time you are going to lunch) and lunchDate (whom you are going to lunch with). And finally, the class Date, with parameters dayName (where you can set the variable in the class DayName; for fun it is now Funday) as well as date, month, and year. class DayName parameter String nameOfDaYi end DayName; class LunchAppointment parameter Integer lunchTime; parameter String lunchDate; end LunchAppointment; class Date DayName dayName(nameOfDay parameter Integer date; parameter String month; parameter Integer year; end Date;
"Funday");
Now create a class, Today, in which you can modify the values in the class Date as well as in the class LunchAppointment. First, write the class using nested notation. Now write the class, Tomorrow, going with another date, using dot notation. Exercise 4-9: Using Replaceable and Redeclare on Class Point: Point is a built-in type in Modelica. class Point parameter Real X; parameter Real y;
Chapter 4 Inheritance, Modifications, and Generics 143 parameter Real z; end Point;
Create a class Redeclaration, containing a Point
P
as a variable. You should set the values of x, y,
and z as well. In the class below you should redeclare P as the type myPoint, which is a subtype of Point (you can write myPoint further below). class PointRed end PointRed;
You can declare the class myPoint.
Tip:The variable P must be declared replaceable in class Redeclaration.
Question: If you instead had a class MyPoint with z as an Integer, would that work? Glass MyPoint parameter Real X; parameter Real y; parameter Integer z end MyPoint;
4;
Exercise 4-10:
Using the Extends Clause in Redeclarations: The next exercise will test if you know how to use an extends clause when redeclaring.
First write a class A with a Real parameter salt. We also need a class Asub , extending A and having two Real parameters: pepper and basil. The parameter salt shall be set to 20. Then we need a class Alnst, containing a variable a, which is an instance of A, in which you should set salt to 100. Write a class Alred, extending Alnst. Also, change the type of the component a to AIsub and set the pepper parameter to 200. Write a similar class AIred2 that instead of extending Alnst, declares a component of type AInst. As above, the type of component a should be changed to AIsub. Exercise 4-11:
More on Redeclaration: Write a class MoreRed that declares two variables vI and v2 being vectors and one variable x being an Integer. Set x to a value. Use the class above to redeclare the dimension sizes of v 1 and v2 and the type of x.
Tip: In the redeclaration-statement of the variables, you have to include the term "parameter" so that they, as parameters, can be modified. Exercise 4-12:
Prefix Final: We have a type Banana. Imagine you want to make two instances of this banana, lightBanana and swedishBanana. type Banana = Real(unit = "kg",final fixed = false);
Is this allowed? Why or why not? class Bananas Banana lightBanana(unit = "hg n ) ; Banana swedishBanana(fixed = true); end Bananas;
Tip: String is declared final.
144 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica Exercise 4-13:
Question: What is a generic parameterizedclass? Why is that good?
145
Chapter 5 Components, Connectors, and Connections
For a long time software developers have looked with envy on hardware system builders, regarding the apparent ease with which reusable hardware components are used to construct complicated systems. With software there seems too often to be a need or tendency to develop from scratch instead of reusing components. Early attempts at software components include procedure libraries, which unfortunately have too limited applicability and low flexibility. The advent of object-oriented programming has stimulated the development of software componentframeworks such as CORBA, the Microsoft COMIDCOM component object model, and JavaBeans. These component models have considerable success in certain application areas, but there is still a long way to go to reach the level of reuse and component standardization found in hardware industry.
5.1 Software Component Models What have software component models to do with Modelica? In fact, as we already stated in Section 2.8, Modelica offers quite a powerful software component model that is on par with hardware component systems in flexibility and potential for reuse. The key to this increased flexibility is the fact that Modelica classes are based on equations. What is a software component model? It should include the following three items: • • •
Components. A connection mechanism. A component framework.
Components are connected via the connection mechanism realized by the Modelica system, which can be visualized in connection diagrams. The component framework realizes components and connections, and ensures that communication works over the connections. For systems composed of acausal components the direction of data flow, i.e., the causality, is initially unspecified for connections between those components. Instead the causality is automatically deduced by the compiler when needed. Components have well-defined interfaces consisting of ports, also known as connectors, to the external world. These concepts are illustrated in Figure 5-1.
146 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Interface
\
\
!
Component
I
Connection
Component
Figure 5-1. Connecting two components within a component framework. Modelica uses a slightly different terminology compared to most literature on software component systems: connector and connection, rather than port and connector respectively in software component literature.
5.1.1 Components In the context of Modelica class libraries software components are Modelica classes. However, when building particular models, components are instances of those Modelica classes. Classes should have welldefined communication interfaces, sometimes called ports, in Modelica called connectors, for communication between a component and the outside world. A component class should be defined independently of the environment where it is used, which is essential for its reusability. This means that in the definition of the component including its equations, only local variables and connector variables can be used. No means of communication between a component and the rest of the system, apart from going via a connector, is allowed. A component may internally consist of other connected components, i.e., hierarchical modeling.
5.1.2 Connection Diagrams Complex systems usually consist of large numbers of connected components, of which many components can be hierarchically decomposed into other components through several levels. To grasp this complexity a pictorial representation of components and connections is quite important Such graphic representation is available as connection diagrams, of which a schematic example is shown in Figure 5-2. We have already (e.g., on page 37 in Chapter 2) seen connection diagrams of simple electrical circuits and as well as a few models from other domains.
Figure 5-2. Schematic picture of a connection diagram for components.
5.2 Connectors and Connector Classes Modelica connectors are instances of connector classes, i.e., classes with the keyword connector or classes with the class keyword that fulfil the constraints of connector restricted classes. See Figure 5-3 to Figure 5-5. Such connectors declare variables that are part of the communication interface of a
Chapter 5 Components, Connectors, and Connections 147 component defined by the connectors of that component. Thus, connectors specify the interface for
interaction between a component and its surroundings. f - - - - - - - - - - - - - -.
+
v
I I
I I
:
----~mpin - .
I
i
~-------------~
,
Figure 5-3. A component with an electrical pin connector. For example, the by now well-known class Pin is a connector class that can be used to specify the external interface for electrical components that have pins as interaction points. connector Pin Voltage V; flow Current i; end Pin; II From Modelica.Electrical.Analog.lnterfaces Pin
II
pin;
An instance pin of class Pin
Since Modelica is a multidomain language, connector classes can be formulated for a number of different application domains. The Flange connector class below, analogous to Pin, is used to describe interfaces for one-dimensional interaction in the mechanical domain by specifying the position s and force f at a point of interaction.
,---- --- - -- -- --,
,
s
I
I I
,
,
- - - - - ( j J flange
: I
I
Figure 5-4. A component with a mechanical flange connector. connector Flange Position s; flow Force f; end Flange; II From Modelica.Mechanical.Translational.lnterfaces Flange flange;
II An instance flange of class Flange
Most examples of connector classes previously presented in this book are aimed at acausal modeling. Causal connections usually arise when there is a signal flowing in a specified direction. For example, the connector class Real Input when instantiated as u is a signal input port that can be connected to receive signals.
:------------, I
----~u
PI :
I
: I I
-------------,
Figure 5-5. A component with an u input connector for signals. connector Reallnput = input RealSignal; II RealSignal is subtype of Real II From Modelica.Blocks.lnterfaces Reallnput
Ui
II An instance u with one signal
Connector classes often use special types for standard physical quantities represented by Real values, e.g., Voltage, etc., used above. The types Voltage, Current, Position, Force and Distance shown below and used in this chapter are just five of the classes available in the Modelica standard library Modelica. SIunits. This library contains approximately 450 predefined types comprising the complete set of ISO standard units. type Voltage type Current
Real(final quantity="ElectricPotential", final unit="V n ) = Real(final quantity=="ElectricCurrent" , final unit= "A") i
i
148 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
type position type Force type Distance
Real(final quantity="Length", final unit="m")i Real(final quantity="Force", final unit="N")i Position(min=O)i
5.3 Connections There are two general kinds of connections that can be represented in Modelica:
•
Explicit connections between pairs of connectors that are represented by lines in connection diagrams and connect equations (see Section 5.3.2) in Modelica code. Implicit connections between a declared element in an object and corresponding elements in components of the object. This is useful in cases when too many explicit connections would be needed, e.g., when modeling implicit interaction between bodies and a force field, or access of common shared object properties.
•
In the following sections, when we speak about connections we just refer to explicit connections, until Section 5.8, page 173, where implicit connections are introduced. Explicit connections between components can be established only between connectors of equivalent type. Relying on our definition of Modelica type from Chapter 3 the typing constraints for allowing connections can be formulated approximately as follows: . The names must be identical and corresponding types of declared variable members in the classes of the connected connectors must be equivalent, but the ordering between the member declarations in the connector classes need not be the same.
•
The typing constraints are actually slightly more relaxed than the above when connecting connectors containing arrays, but are stricter concerning array subscripts (see the section on connection constraints on page 166 in this chapter). It is important to note that explicit connections can be established only between connectors, i.e., instances of connector classes or ·classes with the prefix class fulfilling all constraints of a connector class. Instances of the restricted classes record, block, model, function, and package are not allowed in connections.
5.3.1 The flow Prefix and Kirchhoff's Current Law As we have already noted in the above example, there are basically two kinds of variables in connectors:
• •
Nonflow variables representing some kind of potential or energy level, e.g., voltage, pressure, or position. Flow variables prefixed by the keyword f low that represent some kind of flow, e.g., electrical current, force, or fluid flow.
Two different types of coupling are established by connections depending on whether the variables in the connected connectors are non-f low (default) usually representing some kind of potential, or flow variables declared using the f low prefix:
• •
Equality coupling, for nonflow (i.e., potential or effort) variables. Sum-to-zero coupling, for flow variables, according to Kirchhoff's current law.
Similar laws apply to flows in piping networks and to forces and torques in mechanical systems. In order to ensure that sum-to-zero coupling always works for flow variables we need a rule for consistent assignment of flow direction or sign to flow variables in a connector:
Chapter5 Components, Connectors, and Connections 149
•
The value of a flow variable is positive when the currentor the flow is into the component to which the connector belongs.
One might question the exact meaning of the term "flow into a component" for flow variables. This is fairly obvious for charge, mass, or energy flow. However. what does "flow into" mean for forces and torques? In such cases the connector should contain variables that represent forces and torques applied to the component and not reaction forces and torques.
5.3.2 connect Equations Connections between connectors are realized as equations in Modelica. These equations are specified by connect equations, and are stated in an equation section of a class as for other kinds of equations. Note that connect equations are regarded as equations despite the fact that the syntax is different from normal equations. The reason is that connect equations are eventually expanded into normal equations. The general form of a connect equation is as follows: connect (connector} , connectorl)
The two arguments connector1 and connector2 of the connect equation must be references to connectors, and must have one of the following two forms: •
Structured (nested) connector references el.C2•••••cn, where CI is a connector of the class containing the connect equation, n>=1 and Ci+l is a connector element of Ci for i=l:(n-l). For example, if cl contains the connector c2 which contains the connector c3, we may use a connector reference such as cl. c2. c3. The simplest and most common case is when there is just a simple unstructured connector, e.g. connectorl, immediately within the class instance.
•
Local element connectors, m , d, where m is a non-connector element instance within the class and d is a connector element of m.
There may optionally be array subscripts on any of the components; the array subscripts shall be parameter expressions. The arguments connector] and connector2 can be arrays of connectors, see Section 5.7.4, page 167.
Figure 5-6. Different forms of allowed connectors of a class instance. A direct connectorl, a local element m containing a connector dl, referred to as m.dl, and a connector c3 within a connector c2 within a connector c I, referred to as c1.c2.c3.
5.3.3 Electrical Connections In Figure 5-7 there is an example of two connected electrical pins pinl and pin2. The connectors pinl and pin2 are instances of the connector class Pin.
150 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
,.--------, :
I
•
:
I
+
-.,
pln1 li~--
:.-
~ - - - - - - - -'
r--------.
+ I, · 2 ----I~~~' pin V
V
i
i
I
:'
,
~--------'
Figure 5-7. Connecting two electrical pins. The connected voltages are equal, and the sum of the currents is zero. The connection equation:
connect (pinl,pin2) connects the two pins so that they form one node. This produces two equations, namely:
pinl.v = pin2.v pinl.i + pin2.i
=0
The first equation says that the voltages at the connected wire ends are the same, i.e., equality coupling. The second equation corresponds to Kirchhoff's current law saying that the currents sum to zero at a node (assuming positive value while flowing into the component), i.e., sum-to-zero coupling, since the keyword flow is used for the variable i of type Current in the Pin connector class. Since connectors are instances of connector classes they can be declared anywhere a declaration is allowed, e.g., as above. However, connectors define the interfaces of components and are therefore usually declared inside those components. This has consequences for the naming of the connectors, but does not change anything else. Instead of pin! and pin2 as above, we would, for example, have El. pin and E2. pin as names for two connectors of type Pin in the electrical components El and E2, when referring to those components from the outside.
5.3.4 Mechanical Connections Connecting mechanical components, as in Figure 5-8 below, is quite similar to the previous examples with electrical components. The filled and nonfilled squares on a mechanical component represent identical mechanical flanges. The only difference is the sign of the flange variables in relation to the current coordinate system (see Section 5.4.2 on page 153), analogous to positive and negative electrical pins for electrical components. Drawing a line between such squares means that the corresponding flanges are rigidly attached to each other. The instances of classes in the Modelica mechanical translational library used here as examples (from Modelica.. Mechanical. Translational) can usually be connected together in an arbitrary way.
,---------,
:
: I
flange1
,1---:
s
I~
~--------..!
f
,---------,
S
I I
---Q flange2 f~I
~
I I
: 1I
Figure 5-8. Connecting two mechanical flanges. The positions at the connection point are identical, and the sum of the forces is zero. Given instances flangel and flange2 of the connector class Flange:
Flange flangel; Flange flange2i We connect these flanges using a connect equation so that they form one node:
connect (flangel, flange2) This produces two equations, namely:
flangel.s flange2.s flangel.f + flange2.f
=0
II Identical positions II Sum of forces is zero
Chapter 5 Components, Connectors, and Connections 151 These equations are analogous to the corresponding equations for the electrical pins apart from the fact that they deal with positions (8) and forces (f).
5.3.5 Acausal, Causal, and Composite Connections There are actually two basic and one composite kind of connection in Modelica:
• •
•
Acausal connections, for which the data flow in the connection is not explicitly specified. Causal connections, also called signal connections, where the direction of data flow is specified using the prefixes input or output in the declaration of at least one of the connectors in the connection. Composite connections, also called structured connections, composed of basic or composite connections.
Most examples of connections so far in this book have been acausal. Causal connections usually arise when there is a signal flowing in a specified direction. For example, the connector class RealOutput below when instantiated in a signal generator connected to an electrical circuit as in the DCMotorCircui t example in Section 5.6, page 162, creates a causal connection since the signal flows from the signal generator into the circuit. connector RealOutput
=
output RealSignal; II From Modelica.Blocks.lnterfaces
The third kind of connection is the composite connection, where composite connectors, also called structured connectors, composed of several subconnectors are connected. Such a structured connection can consist of several basic connections, both acausal and causal.
5.4 Connectors, Components, and Coordinate Systems Many components have a kind of internal coordinate system to which the connectors of the components need to relate. This is very apparent for mechanical components, but is also present in components from other domains like the electrical domain. The coordinate direction is by convention defined from "left" to "right" for simple two-connector components like resistors and compressed springs as shown in Figure 5-9. A positive flow, e.g., current i or force IfI, is propagated from left to right through the component. The flow leaves the component from the right connector. The compressed spring exerts a force with absolute value IfI from its right "driven" flange to some other component that is placed at its right side.
--~~
~--~---
resislor1
I
~'
~
spring1
~--~Iij-Ifl
~
I
1'1 .\
Figure 5-9. Positive values of current flow i and force flow f means propagation from left to tight through the resistor and the compressed spring respectively. Solid arrows indicate the direction of actual flow transmitted through the component; dashed arrows positive direction into the component but opposite to the transmitted flow.
The positive direction of the flow variables directly belonging to the resistor and spring is indicated by the arrow from left to right under each component. Regarding connectors, we have earlier stated that positive flow direction of connectors is always into the component where they belong, which is indicated by the
152 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica arrows into the connectors. Since positive flow direction for the right-hand side connectors is in the opposite direction, i.e., from right to left, the values of the right-hand side connector flow variables are negative, e.g., -i and -leI· However, as we shall soon see, the conventions for flow direction of mechanical components are somewhat different from the electrical counterparts.
5.4.1 Coordinate Direction for Basic Electrical Components In the electrical domain several idealized electrical components extend the base class TwoPin, which has two connectors p and n for positive and negative pins respectively (Figure 5-10). The "coordinate system" or coordinate direction here is that the positive direction of current flow i for a component is defined to be from p to n, with i=p. i .
p.v
.- -------------,-6..!.
J..-'+
f4tp
TwoPin
n
----. •
..
I
~------------_.!
pJ
n.v
.---
n.i
Figure 5-10. Twopin base class for simpleelectricalcomponents with two pins. Solid arrows indicate the direction of actualcurrent flow;dashedarrows positivedirectioninto the componentbut opposite to the flow through the component. The connector classes Posi tivePin and NegativePin are identical to Pin and can be used in electrical components to help distinguish positive and negative pins.
II From Modelica.Electrical.Analog.lnterfaces connector PositivePin = Pin; II Current p.i flowing into positive pin connector NegativePin = Pin; II Current n.i flowing into negative pin The partial base class TwoPin, known from Chapter 2, is stated below in a form that uses the connector classes Posi tivePin and NegativePin: partial model TwoPin
"Component with two electrical pins p and n and current i from p to nil Voltage v "Voltage drop between the two pins (= p.v - n.v)"; Current i "Current flowing from pin p to pin n"; PositivePin Pi NegativePin n; equation
v
p.v - n.v; p.i + n.i; i = p.i; end TwoPini II Same as OnePort in Modelica.Electrical.Analog.lnterfaces
o
=
The familiar idealized resistor class is depicted in Figure 5-11. The "coordinate system", Le., the direction of current flow in the resistor, is from p to n as inherited from Twopin. Four equations are present in the resistor model. The first three originate from the inherited TwoPin class, whereas the last is the constitutive equation for ideal resistors v=R*i, which is specific for the resistor class. v
~_;
n_-~
R )
Figure 5-11. Resistorcomponent includingthe resistorequation v=R* i.
Chapter 5 Components, Connectors, and Connections 153
model Resistor extends TwoPini parameter Real R(unit="Ohm") "Resistance"; equation v = R*i; II Resistor equation end Resistor;
5.4.2 Mechanical Translational Coordinate Systems and Components Each mechanical component has an associated coordinate system, called frame. This is true also for components in a simple domain like the ID mechanical translational domain. Even the flanges in the ID mechanical translational domain have their own coordinate systems. The connector classes Flange_a and Flange_b used for flanges in the ID translational mechanical domain are identical but have slightly different roles, somewhat analogous to the roles of PositivePin and NegativePin in the electrical domain. A flange_a connector is used at the "left" side of a component represented by the filled square in Figure 5-12, whereas a flange_b connector is used at the "right" side of the component, represented by the empty square. Each flange has an internal coordinate system characterized by the unit vector n from left to right, depicted by a small arrow above each flange in Figure 5-12. Internal vectors such as position and forces are interpreted in the positive direction along the unit vector.
II From Modelica.Mechanical.Translational.lnterfaces connector Flange_a = Flange; connector Flange_b ::: Flange;
II "left" flange class II "right" flange class
The partial base class Compliant depicted below is extended by classes for compliant flexible mechanical components with two flanges, e.g., springs and dampers. It can be regarded as a ID mechanical analogue of the TwoPin base class from the electrical domain. However, Compliant is not the only base class for two-flange components--there is also, for example, the partial class Rigid for rigid mechanical components. The internal coordinate system of components instantiated from classes extended from Compliant is characterized by the unit vector N from left to right shown in Figure 5-12 and Figure 5-14. The flange coordinate systems are oriented in the same direction left-to-right as the component coordinate system.
flange_a.s
n
s rei ------=-----. ,-I ---Compliant -------- --- -,1 n
-+rb
----"lIange_a
flange_b
~------.
flange_aJ
flange_b.s
1:-+ 0'-----
I"
!.. - - - - - - - - - - - - - - - ~
flange_b.f
N, f Figure 5-12. Compliant is a base class for simple compliant (flexible) 10 mechanical components with two flanges. The vector N with the arrow indicates positive direction in the component coordinate system or frame. The vectors n with small arrows indicate positive direction in the flange coordinate systems. Solid arrows for forces f indicate positive value in the associated coordinate system; dashed arrow negative values. The relative distance between the flanges is represented by s_rel. Note that the arrows for the force variables point out of the flange connectors rather than into the connectors as previously for the, Twopin class and its derived electrical components. This is seemingly in contradiction to the rule that positive flow direction is always into the component. However, the choice of flow variable is in some sense somewhat arbitrary. If we instead would choose -f as our force variable, the arrows would change direction and the rule of positive flow direction into the component would be satisfied.
154 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica The designers of the 1D mechanical translational library have adopted the convention that the force variable f of components derived from Compliant is equal to the force in the right flange, i.e., f = flange_b. f. This is different from the convention of the electric library, where the current i of the component is equal to the current into its left connector, i.e., i=p. i. However, as long as this new convention is used consistently for mechanical components it works fine since the original rule for connectors can always be fulfilled by multiplying forces by -1 when forming' the connection equations. The base class Compliant for flexible ID two-flange mechanical components is availablebelow. partial model Compliant "Compliant coupling of 2 translational 10 flanges" Flange a flange a "(left) driving flange"; Flange-b flange-b "(right) driven flange"; Distan~e s reI - "relative distance between flange a and flange b"; flow Force - f "force between flanges, positive in-direction of-NIt; equation s_rel = flange_b.s - flange_a.s; o = flange_b.f + flange_a.f; f = flange b.f; end Compliant; 7/ from Modelica.Mechanics.lnterfaces
Springs are one kind of compliant component with two flanges. Figure 5-13 shows a spring in three different configurations: compressed (a), neutral (b), and stretched (c). In the compressed configuration a force f applied at the left "driving" flange called flange_a in Figure 5-14 propagates through the spring, and leaves the spring at the right "driven" flange, called flange_b.
s rei ----=-------.
IfI
(a)
-lfJ s relO -----=--------. r;J ....
~
/\
~
(b)
~V~
~-----
-'fl
i~
IfI
-+-----
(c)
Figure 5-13. Compressed (a), neutral (b), and stretched (c) spring. The flange arrows indicate the actual direction of forces applied to flanges. Solidarrows represent positive values in thecomponent coordinate system; dashed arrows negative values.
For the compressed spring the external force applied at the left flange, flange_a. f = Ifl, has positive sign since it is directed from left to right in the same direction as the normal vector of the coordinate system, whereasthe force exertedon the right flange, flange_b. f = -le], has negativesign since it points in the opposite direction, as indicated by the dashed arrow. s- rei
N Figure 5-14. Linear ID translational spring.
.
Chapter 5 Components, Connectors, and Connections 155 When the spring is stretched its actual length s _ re 1 becomes greater than s _ re 10, which is its length in the neutral state when the applied forces are zero. In the stretched state the force direction is reversed compared to the compressed state. The force variable f = c* (s_rel-s_relO) is positive, and since flange_b. f = f , the right flange is dragged by the component attached at the right side in the positive coordinate direction to the right. The external force applied at the left flange, flange_a. f = - f, is negative since it drags the left flange in the opposite compared to the normal vector n. The Spring class below inherits all equations apart from the constitutive spring equation from its base class Compliant. model Spring "Linear ID translational spring" extends Compliant; parameter Distance s reID o "unstretched spring length"; parameter Real c(unit:"N/m n ) 1 "spring constant"; equation f
=
II spring equation
c*{s reI - s_reID);
end spring-;
5.4.3 Multiple Connections to a Single Connector In almost all previous examples we connected only two connectors. In fact, there is in general no limitation to the number of connections that can be made to a single connector, apart from connector classes that very specifically limit the cardinality of the connections, as we shall see in Section 5.7.6 on page 173. Two examples of multiple connections to the same node are shown below, where three components are being connected. The first example is a resistor circuit, and the second consists of three mechanical springs connected together. 5.4.3.1
ResistorCircuit
The class ResistorCircuit connects three resistors at one node using two connect equations (Figure 5-15). n
R1
ı___.---11',;:1
V3
R2
p
p
n
R3 --..-----b
n
Figure 5-15. Schematic picture of the ResistorCircui t containing three resistors connected at one node. The connection laws on voltages v and currents i at that node give vl=v2=v3 and il+i2+i3=O.
model ResistorCircuit
Resistor Rl(R:lOO)i Resistor R2(R:20D); Resistor R3(R:30D); equation connect(Rl.p, R2.p); connect(Rl.p, R3.p); end ResistorCircuit;
As usual, the special operator connect produces equations by taking into account what kind of variables, flow or non-flow, are involved. The generated equations, based on equal potentials at a connection point and Kirchhoff's current law, are as follows for this particular example: Rl.p.v Rl.p.v Rl.p.i
+
R2.p.v; R3.p.v; R2.p.i + R3.p.i
0;
156 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica 5.4.3.2
TripleSprings
The TripleSprings model connects three springs at one node using two connect equations (Figure 5-16). This model is quite similar in structure to the ResistorCircuit model presented in the previous section.
spring1
spring2 spring3
Figure 5-16. Schematic picture of the mechanical connection of three springs.
model TripleSprings "Three connected springs" Spring springl(c=l, s_relO=O.l); Spring spring2(c=1, s_relO=O.l)i Spring spring3(c=1, s_relO=O.l)i equation connect(springl.flange_a, spring2.flange a)i connect(springl.flange_a, spring3.flange=a); end TripleSprings; Also the equations generated from the two connect equations in the TripleSprings model are analogous to the corresponding equations from the ResistorCircuit model. We have the connector flange_a instead of the connector p, position s instead of voltage v, and force f instead of current i. Identical positions of the connected flanges of the three springs give the first two equations. The last equation is force equilibrium where the sum all forces applied at the connection node is zero.
springl.flange_a.s spring2.flange_a.s; springl.flange_a.s spring3.flange_a.s; springl.flange_a.f + spring2.flange_a.f + spring3.flange_a.f
0;
5.4.4 An Oscillating Mass Connected to a Spring The following model is a somewhat more interesting example from the ID mechanical domain since it gives rise to some dynamic movement when simulated. A mass is hanging in a spring, which is connected to a fixed housing. Those objects are instances of the classes Mass, Spring, and Fixed respectively, which are declared farther down. The mass massl is subject to the gravitational force -mg and the force from the spring. It is given an initial position s=-O. 5, which is offset from the equilibrium position and therefore starts an oscillating movement up-and-down.
model Oscillator Mass massl(L=l, s(start=-O.5»; Spring springl(s_relO=2, c=10000); Fixed fixedl(sO=1.0); equation connect(springl.flange_b, fixedl.flange_b); connect (massl.flange_b, springl.flange_a); end Oscillator; The model with its three components massI, springl, and fixed! is depicted in Figure 5-17, including certain absolute and relative positions and the gravitational force -mg. The positive coordinate direction is upward in the figure, which appHes to both positions and forces,
Chapter5 Components, Connectors, and Connections 157 fixedl ~~~-----------
sO
sreiO
mass 1
sret
Figure 5-17. The oscillator model contains a mass hanging in an ideal spring which is fixed at a housing. The mass which is subject to the gravitational force -mg performs an oscillating movement up and down. Positive coordinate direction is upward. The absolute position of the center of mass for the massl component is represented by the variable massl. s, which is plotted in Figure 5-18. The model is idealized since there is no damping, causing the amplitude of the oscillations to remain the same instead of the gradual decrease that would occur in a more realistic model.
.5
t
Figure 5-18. Plot of the absolute position mass 1 . s
(t)
of the center of the hanging mass.
The velocity massl . v of the hanging mass is plotted in Figure 5-19. It is the same as the derivative of s. Both s and v are declared in the class Mass below. 100 50 t
-t---f-'-.....-.--f'--''i--'-...-........t-'--~I-''---'If--f"'''---4-~---''-I-~~~
0.5 -50 -100
Figure 5-19. Plot of the absolute velocity massl . v
(t)
of the hanging mass.
158 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica In addition to the previous declarations of Spring, Oscillator, etc., the following three classes are needed to simulate the Oscillator model. The class Mass is a specialization of the class Rigid, which is a base class for rigid objects of fixed length L. The class Fixed represents a housing with a fixed position and a flange where other objects can be attached. model Mass "Hanging mass object" extends Rigid; parameter Real m =1 "mass of the hanging mass"; constant Real g =9.81 "gravitational acceleration"; Real v "absolute velocity of component"; Real a "absolute acceleration of component"; equation v = der(s); a = der(v); flange_b.f = m*a - m*g; end Mass; partial model Rigid "Rigid connection of two translational ID flanges" Real s "absolute position s of center of component (s = flange_a.s + L/2 = flange_b.s - L/2)"; parameter Real L=O "length L of component from left to right flange (L= flange_b.s - flange_a.s)"; Flange_a flange_a; Flange_b flange_b; equation flange a.s = s - L/2i flange-b.s = s + L/2; end Rigid; II From Modelica.Mechanics.Translational.lnterfaces model Fixed "Fixed flange at a housing" parameter Real sO = 0 "fixed offset position of housing"; Flange flange_bi equation flange b.s = sO; end Fixed; II From Modelica.Mechanics.Translational
5.5 Design Guidelines for Connector Classes So far, the above-mentioned connector classes have always consisted of a pair of one potential variable and one flow variable, apart from the RealOutput class briefly mentioned in the context of causal connections. One might ask whether this is a coincidence or a general pattern for connector class design. We shall soon see that this is no coincidence; but on the other hand there exist many connector classes that do not follow this pattern for various reasons. More important is to identify the basic requirements behind the design of component interfaces, i.e., connector classes, that influence their structure. These requirements can be briefly stated as follows: 1. It should be easy and natural to connect components provided this is possible for .the corresponding physical components. 2. Component interfaces should facilitate reuse of existing model components in class libraries. Fulfilling these requires careful design of connector classes. The number of connector classes should be kept small in order to avoid unnecessary mismatches between connectors due to different names and types of variables in the connectors. Experience shows that it is surprisingly difficult to design connector classes that satisfy these requirements. There is a tendency for extraneous details that are created during software (model) development for various computational needs to creep into the interfaces, thereby making them harder to
Chapter 5 Components,Connectors,and Connections 159 use and preventing component reuse. Therefore one should keep the connector classes as simple as possible, and try to avoid introducing variables that are not really necessary. A good rule of thumb when designing connector classes for models of physical components is to identify the characteristics of (acausal) interaction in the physical real world between these components. The interaction characteristics should be simplified and abstracted to an appropriate level and reflected in the design of the connector classes. For nonphysical components, e.g., signal blocks and software components in general, one has to work hard on finding the appropriate level of abstraction in the interfaces and trying these in practice for feedback on ease-of-use and reusability. The Modelica standard library contains a large number of well-designed connector classes which can serve as inspiration when designing new interfaces. There are basically three different kinds of connector classes, reflecting three design situations: 1. If there is some kind of interaction between two physical components involving energy flow, a combination of potential and flow variables in the appropriate domain should be used for the connector class. 2. If information or signals are exchanged between components, input/output signal variables should be used in the connector class. 3. For complex interactions between components, involving several interactions of type (1) and (2) above, a hierarchically structured composite connector class is designed that includes one or more connectors of the appropriate type (1), (2), or (3). When all the connectors of a component have been designed according to the three principles above, the formulation of the rest of the component class follows partly from the constraints implied by these connectors. However, these guidelines should not be followed blindly. There are several examples of domains with special conditions that deviate slightly from the above rules. In the next three sections we will discuss the basic design situations for connector classes in more detail.
5.5.1 Physical Connector Classes Based on Energy Flow The first design situation with interaction between physical components based on some kind of generalized energy flow leads to the following generic structure of a connector class: connector "Physical connector class" Real <e> "potential variable"; flow Real "flow variable"; end ;
This structure corresponds to the physical connectors presented so far, e.g., the Pin connector class for the electrical domain from the library Modelica. Electrical. Analog. Interfaces with the voltage variable v as the potential variable and the current i as the flow variable, or the Flange_a connector class from the library Mode 1 ica . Mechanics. Trans lational. Interfaces for the translational mechanical domain with the position s as the potential variable, and the force f as the flow variable. We talk about this design method being based on energy or energy flow. Energy flow is the change of energy per time unit, i.e., power p=e*f, the product of the potential or effort variable e and the flow variable f In electrical systems the power p=v*i. In translational mechanical systems the energy E=s*f. These correspond to our choices of variables in the previously presented connector classes. Another choice of potential variable in translational mechanical systems is the velocity v, which, however, can be easily obtained by differentiating s. The kind of potential variable must always be chosen in such a way that at energy flow connection points all potential variables of connected components are equal. Energy is always transported using some carrier, which in the case of electrical current is charged particles, and in the case of translational or rotational mechanical systems is linear or angular momentum respectively.
160 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica When energy flows together at a certain point, without storing energy at that point, the sum of all energy flows into that point is zero. This is the explanation for the sum-to-zero rule for flow variables at connection points, which thus is based on the principle of conservation ofenergy. In the electrical domain this corresponds to Kirchhoff's current law, and in the mechanical domain Newton's law that the sum of all forces acting at a specific point is zero. Table 5-1 describes possible choices for potential, flow, and energy carrier for some common physical domains, as well as the names of certain ·corresponding. Modelica libraries, which should be prefixed by the name Modelica: Table 5-1. Common physical domains with appropriate connector quantities. (See also Table 14-1) Domain Type Electrical Translational
Potential Voltage Position
Flow Current Force
Rotational
Angle
Torque
Magnetic
Magnetic potential
Hydraulic Heat Chemical
Pressure Temperature Chemical potential
Magnetic flux rate Volume flow rate Heat flow rate Particle flow rate
Carrier Charge Linear momentum Angular momentum Magnetic flux
Modelica Library Electrical Mechanical. Translational Mechanical. Rotational
Volume Heat Particles
HyLib Thermal (ThermoFluid)
Connectors for these domains are available in the Interfaces part of the corresponding Modelica library. There are also libraries for additional domains, e.g., the MBS (multibody systems) library described in Section 15.10, page 587, for mechanical bodies in three dimensions. Regarding the mechanical rotational domain it should be mentioned that in addition to the previously presented translational Flange_a there is also a rotational Flange_a connector class, shown renamed below, from the library called Modelica.Mechanics .Rotational. Interfaces for one-dimensional rotational mechanical systems (drive trains). This class has the rotation angle phi as a potential variable and the torque tau as a flow variable. To avoid confusion with the translational Flange_a connector class we have renamed it RotFlange_a in this text.
connector RotFlange_a "lD rotational flange" "Absolute rotation angle"; Angle phi flow Torque tau; end rotFlange_a; type Angle type Torque
Real(final quantity="Angle", final unit="rad", displayUnit=ltdeg lt ) ; Real (final quantity=lfTorque", final unit="N.mlf)i
Returning to the question posed at the beginning of this section whether all physical connector classes consist of the same number of potential and flow variables, the answer is no, there are exceptions to this rule. For example, the following three situations make it necessary to have different. numbers of potential and flow variables: •
•
The same energy carrier for several domains. For example, the energy flow of a one-dimensional compressible fluid, P = dE/dt = m'(h+ 0.S*v2) , where m' is the mass flow being the same energy carrier, h the enthalpy, and v the fluid velocity. Here m' is the flow variable whereas h and v are potential variables. Singularities of variable sets, e.g., rotation matrices. For example, the orientation of a 3D mechanical connector can be described by a 3 x 3 rotation matrix, which causes singularities at certain orientations based on transformations using three separate rotations. This problem can be solved, e.g., by introducing 4 X 4 transformation matrices through Euler parameters or
Chapter 5 Components, Connectors, and Connections 161
•
Quaternions (see Section 14.8), but this ados at least one extra potential variable in the connector class. Singularities caused by connections, e.g., in so-called higher index systems (see Chapter 18). In some cases the connection of components leads to higher index systems that cannot be transformed to solvable (state space) form using only algebraic transformations. For example, in 3D mechanical systems almost all connections lead to higher index systems. The solution is to differentiate the equations, causing differentiated variables to be added as extra variables. Sometimes it is practical to store some of these extra variables in the connectors, thereby increasing the number of potential variables. Examples of such connector classes, e.g., the one presented below, can be found in the Modelica MBS library.
The connector class Frame_b below from the old version (ModelicaAdditions) of the Modelica multibody systems (MBS) library is an example of a connector class of the kind that contains extra potential variables to get around problems caused by connections that cause higher index systems. Several extra potential variables, e.g., velocity and acceleration, are derivatives of the basic potential variables. The are six potential variables; rO, S, v, w, a, and z, whereas there are only two flow variables; f and t. connector Frame b "Frame b of a 3D mechanical element, old version" import Modelica.SIunits; output SIunits.Position rO(3] "Frame origin in inertial system"; Real S [3,3] "Transformation matrix" ; SIunits.Velocity v[3] "Absolute velocity of frame origin"; SIunits.AngularVelocity w[3] "Absolute angular velocity of frame a"; SIunits.Acceleration a[3] "Absolute acceleration of frame origin"; SIunits.AngularAcceleration z[3] "Absolute angular acceleration"; flow SIunits.Force f[3]; flow SIunits.Torque t[3]; end Frame_b; II From ModelicaAdditions.MultiBody.lnterfaces
5.5.2 Signal-based Connector Classes Signal-based connector classes are very simple. All that is needed is a vector of input signals or output signals. Most application models where signal connectors are needed can be satisfied with the connector classes Reallnput and RealOutput below, both from the library Modelica. Blocks. Interfaces. connector Reallnput input RealSignal; connector RealOutput = output RealSignal; connector RealSignal replaceable type SignalType extends Real; end RealSignal;
=
Real;
The Reallnput and RealOutput connector classes can be specialized to different numbers of signals when instantiated, as in the class MISO below. This is a partial block that captures the generic features of multiple-input-single-output continuous control blocks (Figure 5-20).
,------------I I
~u :
-------
I I
yP I
1
Figure 5-20. A MISO block with an inputsignaltype Real Input and an output signal RealOutput. partial block MISO "Multiple Input Single Output continuous control block" parameter Integer nin=! "Number of inputs"; input Reallnput u[nin] "Connector of Real input signals";
162 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
output RealOutput y "Connector of Real output signal"; end MISO; II From Modelica.Blocks.Interfaces Signal connector types for other basic types are available in Modelica. Blocks. Interfaces:
connector connector connector connector
BooleanInput BooleanOutput IntegerInput IntegerOutput
connector BooleanSignal connector IntegerSignal
input output input output
BooleanSignal; BooleanSignal; IntegerSignal; IntegerSignal;
Boolean; Integer;
5.5.3 Composite Connector Classes A composite connector class is an aggregation of one or more connectors, not just variables as in simple connectors. Such connector classes can represent more complex interactions by combinations of a number of simple connectors. Here it is especially important to choose an appropriate level of abstraction. For example, consider the interface between the mechanical body of an aircraft and the aircraft engine. This might be represented as a composite connector class containing a connector for the rigid coupling between the aircraft body and the engine, a hydraulic connector for the fuel flow between the aircraft tank and the engine, and a signal connector for controlling the engine from the cockpit.
5.6 Connecting Components from Multiple Domains So far most of the presented models have been of the single domain type being constructed of components from a single application domain. However, one of the main advantages with Modelica is the ease of constructing multidomain models simply by connecting components from different domains. A DC (direct current) motor as depicted in Figure 5-21 is one of the simplest examples illustrating this capability.
,I -I resistor~
inductor1
signalVoltage1 step1
ground1
Figure 5-21. A multidomain DCMotorCircui t model with mechanical, electrical, and signal block
components. This particular model contains components from the three domains discussed previously in this chapter: mechanical components such as inertial, the electrical components resistorl, inductorl, signalVoltagel, and groundl, as well as pure signal components such as stepl. The DCMotorCircuit model together with several of the needed Modelica classes are presented in detail in Chapter IS, page 523, together with a simulation of the model.
5.7 Detailed Connection Semantics At the beginning of this chapter we introduced the concepts of connector class,connector, and connection, primarily by means of examples from the electrical and mechanical domains. However, some details regarding the meaning of connections, generation of connection equations, and certain special situations
Chapter 5 Components, Connectors, and Connections 163 have not yet been specified. The rest of this chapter fills this gap and gives a complete and somewhat more formal description of connection semantics.
5.7.1 Hierarchically Structured Components with Inside and Outside Connectors Complex systems are naturally described as hierarchical structures of components which internally consist of components, etc., often many levels deep. Components that have an internal structure of other components are called structured components. Those are natural for modeling large reusable components. Let us return to the DCMotorCircuit example. We would like to create a structured library component class that captures most of the essentials of the DC motor circuit and allows us to connect different signal generators and different loads when instantiating a real DC motor. This library class is shown in Figure 5-22 and as the declaration of the class PartialDCMotor. It is of course incomplete (partial) and nonphysicalsince no real motor is without inertia. PartialDCMotor p
resistor1 u
u
inductor1 emU
signalVoltage1
p
ground1
Figure 5-22. A partial DC motor packaged as a structured component class with the outside connectors u and rotFlange_b. (Note that in the Modelica standard library the rotational flange class is called Rotational. Flange_b and the connector is named flange_b, which we here call rotFlarlge_b to avoid confusion with other kinds of flanges.) partial model PartialDCMotor Real Input Ui II Outside signal connector RotFlange_b rotFlange_b; II Outside rotational flange connector Inductor inductor!; Resistor resistorl; Ground ground1; EMF emfl; SignalVoltage signalVoltagel; equation connect(u, signalVoltagel.voltage)i connect (signalVoltagel.n, resistorl.p)i connect(resistorl.n, inductorl.p)i connect(signalVoltagel.p, groundl.p); connect(groundl.p, emfl.n); connect(inductorl.n, emfl.p); connect(em~l.rotFlange_b, rotFlange_b); end PartialDCMotor;
The class PartialDCMotor has the internal components inductorl, resistorl, groundl, emfl, and signalVoltagel. Connectors belonging to the internal components are called inside connectors, whereas connectors that constitute the external interface of a structured component class are called outside connectors.
164 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica •
An inside connector is a connector belonging to an internal component of a structured component class. It may not be a member of an outside connector of a class. An outside connector is a connector that is part of the external interface of a structured component class, is declared directly within that class, and is not a member of some internal component of that class.
•
Regarding the class PartialDCMotor, its outside connectors are u and rotFlange_b, whereas its inside connectors are signalVol tagel . vol tage, emfl . rot Flange_b, signalVoltagel. n, resistorl.p,resistorl.n,inductorl.p,e~.
Using this class it is trivial to construct a full DC motor circuit called DCMotorCi rcui t2 as in Figure 5-23, e.g., by connecting a step signal generator block stepl and an inertia called inertial.
Ilr} step1
·1
partialOCMotor1
hct inertia1
Figure 5-23. Connecting the structured component partialDCMotorl to a signal generator called stepl and an inertial load called inertial to form the complete DCMotorCircuit2 model.
model DCMotorCircuit2 Step step!; PartialDCMotor partialDCMotorli Inertia inertial; equation connect (stepl.y, partialDCMotorl.u)i connect(partialDCMotorl.rotFlange b, inertial.rotFlange_a)i end DCMotorCircuit2i -
5.7.2 Connection Restrictions on Input and Output Connectors The introduction of structured components with inside and outside connectors introduces some additional complexity in the rules for connecting connectors with input or output causality, i.e., connectors declared with the input or output type prefix. Examples are instances of the connector classes Reallnput and RealOutput. Normally the following rules apply: • • •
Two acausal connectors can be connected to each other. An input connector can be connected to an output connector or vice versa. An input or output connector can be connected to an acausal connector, i.e., a connector without input/output prefixes.
However, it is not possible to connect an input to an input or an output to an output, except when outside connectors are involved. The reason is data-flow consistency. A variable with an input prefix on one side of an equation will eventually be on the receiving side of an assignment statement (or receive a value as a result of solving an equation system) when causality analysis has been performed on the total system of equations. Therefore, connecting an input to an input is not possible since then only one of the two input connectors would be on the receiving side in the data flow. The situation is somewhat different with outside connectors since they play different roles in outside and inside connections. This is especially apparent for outside connectors that have input or output causality, for which the following rules apply for internal use inside a structured component: • •
An outside input connector behaves approximately like an output connector internally. An outside output connector behaves approximately like an input connector internally.
Chapter 5 Components, Connectors, and Connections 165
This might at first glance appear rather strange, but is easy to understand when examining the simple example in Figure 5-24.
Figure 5-24. Two essentially equivalent example circuits of four connected components with connectors of input or output causality, in the figure labeled input and output, but in most signal connectors named u and y. Within the lower circuit two components have been embedded in the structured component MI.
The figure shows two almost-identical circuits of four connected components CI, C2, C3, and C4, which are instances of the class c declared below. The signal connectors, usually named u and y but in the figure marked input and output, are instances of Reallnput and RealOutput which have input and output causality respectively. connector Reallnput connector RealOutput class C Reallnput Ui RealOutput Yi end C;
II II
input RealSignali output RealSignali
II II
input connector output connector
class CInst C CI, C2, C3, C4i equation connect(Cl.y, C2.u); connect(C2.y, C3.u): connect(C3.y, C4.U)i end CInsti
II
Instances of C
class M
"Structured class Mil Reallnput Ui II Outside input connector RealOutput Yi II Outside output connector C C2; C C3;
end Mi
class Mlnst M Ml; equation
II
Instance of M
connect(Cl.y, Ml.u); II Normal connection of y to u connect(Ml.u, C2.U)i II Outside u connected to inside u connect(C2.y, C3.U)i II Inside y connected to inside u connect(C3.y, Ml.y)i II Inside y connected to outside y connect(Ml.y, C4.u); II Normal connection of y to u end Mlnst;
subtype of input Real; subtype of output Reali
166 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Data flow is from left to right in both circuits. In fact, the only difference in the lower circuit compared to the upper is that the middle components C2 and C3 have been placed inside a structured component Ml to which two outside connectors Ml.U and Ml.y have been attached. The "input" connection from Cl into C2 in the upper circuit: connect (Cl.y, C2.u)
is therefore equivalent to: connect(Cl.y, Ml.u)
II Normal connection of y to u connect(Ml.u, C2.u)
II Outside u connected to inside u Analogous rules apply to "output" connections.The connection out of C3 to C4 in the upper circuit: connect(C3.y, C4.u)
is equivalent to: connect(C3.y, Ml.y) II Inside y to outside y connect(Ml.y, C4.u)
II Normal connection of y to u We are now ready to formulate the connection constraints for input and output connectors. The first two rules state the special circumstances when an input can be connected to an input and an output can be connected to an output: • •
The only case when it is allowed to connect an input connector to an input connector is when one of them is an inside connector and the other is an outside connector. The only case when it is allowed to connect an output connector to an output connector is when one of them is an inside connector and the other is an outside connector.
The data-flow consistency constraint that a connector with input causality can be on the receiving side in at most one connection, mentioned at the beginning of this section, can be formulated as the following two rules: • •
An input connector can occur as an inside connector in at most one connect equation. An output connector can occur as an outside connector in at most one connect equation.
5.7.3 Connection Constraints regarding Arrays, Subscripts, and Constants As stated earlier in this chapter in the first section on connections, the main constraint between connected connectors is that they should have equivalent type. This rule is somewhat relaxed concerning arrays that are members of connectors, as described in the next section. 5.7.3.1
Array Dimensionality Matching
The type-checking rules for connected connectors with array members are less strict than the usual typechecking rules for equations: •
If matching arrays in connected connectors have the same number of elements but different dimensionality, the dimensionality of the array with the lowest number of dimensions is increased by adding one-sized dimensions to the left until both arrays have the same dimensionality.
The reason for this rule is to increase the reusability of connector classes with array members, e.g., for connection between connectors with array members to almost-identical connectors with corresponding scalar members. For example, consider the connectors op of class TestRealOutput and ip of class TestRealInput below:
Chapter 5 Components, Connectors, and Connections 167
connector TestRealOutput output Real signal; end TestRealOutput;
"Scalar Real output connector"
connector TestReallnput "Vector Integer input connector" parameter Integer n = Ii input Real signal[n]; end TestReallnput; class ConnectArrayMembers TestRealOutput 0Pi TestRealInput ip; equation connect (ip, op) ; end ConnectArrayMembersi These connectors do not have the same dimensionality, but the connect equation connect (ip, op); is still correct. This works since the dimensionality of op , signal is increased by one to become op . signal [1] before the connect equation is expanded to conventional equations. One-sized dimensions are added to the left in the list of dimensions, e.g., an array x[2,3] could be converted to x[1,1,2,3 ].
5.7.3.2
Constant or Parameter Subscript Constraint
In order to simplify the analysis of connections and make the generation of connection equations possible at compile time, the following constraint applies:
•
Subscripts in a connector reference must be constant or parameter expressions.
For example: class ConnectTest Pin
Pin
x [3] i y[3];
Integer i=2; equation connect(x[2],y[2]) ; connect (x[i] ,y[2]); end ConnectTest;
II Ok! Constant subscripts. II Error! Non-constant subscript.
5.7.4 Connecting Arrays of Connectors As mentioned in Section 5.7.3, page 166, connections between scalar connectors are automatically vectori zed , which for example is quite useful when using components from the Modelica. Blocks library, which can be used in both scalar and vector contexts. The connect construct can be used to directly connect arrays of connectors. For such array connections the following holds: • •
The array dimensions of the connected arrays of connectors must match. Each corresponding pair of elements is connected as a pair of scalar connectors.
We demonstrate this functionality in the ArrayConnects class below, for which the connections are graphically depicted in Figure 5-25.
~:inSOUrCe[4~~_ _~U
gain44
Y~
~u
gain42
Figure 5-25. Example of connections between arrays of connectors.
yr~====:21
168 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica The s inSource signal generator produces a vector of 4 sinusoidal signals, which are connected to the input vector gain44 . u of the gain44 block. This gain block multiplies the signal by its gain factor, here 5, which is present in the diagonal elements of the matrix gain44 . A.
5 000 o 5 0 0 gain44.A: o 0 5 0 000 5
gain42.A:
G:
(5-1)
Moreover, we connect the output vector gain44 . y of length four to the input vector gain42. u of the gain42 block. This block transforms its input signals into the two output signals gain42. v, which we finally connect to the vector x [2] . The corresponding Modelica code follows: connector Reallnput connector RealOutput
input Real; Real;
= output
block MatrixGain parameter Real A[:, :J=[l); input Reallnput u[size(A,l)]; output RealOutput y[size(A,2)] equation y=A*u; end MatrixGain; model ArrayConnects import Modelica.Math.sin; sin sinSource[4] ; MatrixGain gain44(A=S*identity(4»; II 4x4 identity matrix * 7 MatrixGain gain42(A=ones(4,2»; II 4x2 matrix of ones RealOutput x{2] ; II 2-vector equation connect (sinSource.y, gain44.u); connect (gain44.y, gain42.u)i connect (gain42.y, X)i end ArrayConnectsi
Quite often when instantiating models with arrays of connectors there is a need to modify a common attribute of each array element to a single value. The iterative array element modification construct with the each keyword, described in Section 4.2.3.1, page 120, has been designed with such applications in mind. We show an example below with the frequency attribute of the source vector elements being modified to the common value 50 in the ConnectUseEach model. model ConnectUseEach import Modelica.Blocks.Sources.Sinei Sine base[3]; Sine source [3] (each frequency=50, phase={O,2,-2})i CrossProduct a; block CrossProduct import Modelica.Blocks.lnterfaces.MI2MO; extends MI2MO(final n=3)i II Two multiple input to multiple output block equation y = cross(ul,u2); end CrossProducti equation connect (source.y, a.ul)i connect (base.y, a.u2)i end ConnectUseEachi
Chapter 5 Components, Connectors, and Connections 169
5.7.5 Generation of Connection Equations By generating connection equations we mean the conversion of connect equations to the two different forms of normal equations to be used for nonflow and flow variables respectively, even though the connect equation itself is a kind of equation. This was described to some extent in Section 5.3 on page 148 but is presented in more detail here. The process of converting connect equations can be divided into two steps: • •
Building connections sets from connect equations. Generating connection equations for the complete model.
5.7.5.1
Connection Sets
Connections sets are needed to generate the connection equations of a model. We initially focus on sets of connectors, i.e., connector connection sets, and continue with sets of variables of built-in type in expanded connector types, so-called primitive connection sets. •
A connector connection set of a model is the set of connectors reachable within a graph where each connector is a node and each connection is represented by an arch between its two connected connectors. AU connectors in such a set have equivalent type modulo possible minor array dimensionality conversion by adding one-sized dimensions.
A practical way to generate these sets is to first create a small connection set from each connect equation consisting of its two arguments. If any of these connector arguments are members of other connection sets, the corresponding connection sets are merged. For example, the connector connection sets corresponding to the connect equations in the ResistorCircuit model in Figure 5-26 are: {Rl . P , R2. P } ,
{R2.p, R3.p}
These two sets are merged into the following connector connection set: {Rl.p, R2.p, R3.p}
The three connectors in the set are reachable in the graph defined by the three connector nodes and the two connection equations connect (Rl.p, R2 .p) and connect (R2 .p, R3 .p) given in the model. n
R1
p 1·;/..._--1.···.:;·:1 p
R2
n
p
R3
n
Figure 5-26. Schematic picture of ResistorCircuit, also in Figure 5-15. model ResistorCircuit Resistor Rl,R2,R3i equation connect(Rl.p,R2.p)i connect(R2.p,R3.p)i end ResistorCircuiti
The situation is somewhat different regarding the ECircui t model in Figure 5-27 since it contains a structured component El that contains both inside and outside connectors.
170 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica
Figure 5-27. The ECircuit model. class E Resistor R2; Resistor R3; equation connect (El.p, R2.p); connect(R2.n, R3.p); connect(R3.n, El.n); end E; model ECircuit; Resistor Rl; Resistor R4; E Eli equation connect(Rl.n,El.p)i connect(El.n,R4.p)i end ECircuiti The ECircuit model contains three components m, sa, and R4 at the outermost level of the model. The two connections at that level of the model give rise to the following two connector connection sets: {Rl.n, El.p},
{El.n, R4.p}
On the other hand, the structured component El internally has the following three connector connection sets that also include the outside connectors El . P and El . n: {El.p, El.R2.p},
{El.R2.n, El.R3.p},
{El.R3.n, El.n}
Remember that all connectors in a connector connection set have equivalent connector class type, e.g., have members that are variables with the same names and types. •
•
•
If there are variables having structured connector types, assume that those variables are expanded into their primitive components until all variables have primitive built-in Modelica types. Each such "primitive" variable gives rise to a group of primitive connection sets of variables: A primitive connection set of a model is a set of variables having the same simple name (excluding prefixes) and the same primitive built-in Modelica type (including array dimensions). Each primitive member in the expanded connector class gives rise to such a primitive connection set. Each connector in a connector connection set of a model has a corresponding variable in each primitive connection set corresponding to that connector connection set. A primitive connection set contains either only flow variables or only nonflow variables.
For example, since all connectors in the connector connection sets of ECircuit have the type Pin with the two members; v of type Voltage, and i which is a flow variable of type Current, we obtain the following two groups of primitive connection sets from the model ECircui t, the first group for nonflow variables and the second for flow variables: {Rl.n.v, El.p.v},{El.p.v, El.R2.p.v},{El.R2.n.v, El.R3.p.v}, {El.R3.n.v, El.n.v},{El.n.v, R4.p.v} {Rl.n.i, El.p.i},{EI.p.i, El.R2.p.i},{El.R2.n.i, El.R3.p.i}, {El.R3.n.i, El.n.i}, {EI.n.i, R4.p.i} The ResistorCircuit model gives rise to the following two primitive connection sets, for non-flow and flow variables respectively:
Chapter 5 Components, Connectors, and Connections 171
{Rl.p.v, R2.p.v, R3.p.v} {Rl.p.i, R2.p.i, R3.p.i}
5.7.5.2 Connection Equations for Nonflow Variables Each primitive connection set of nonflow variables (ai) is used to generate equations of the form:
There are five primitive connection sets of nonflow variables from the model ECircuit, generating the following equations: Rl.n.v = El.p.v; El.R2.n.v = El.R3.p.v; El.R3.n.v = El.n.v;
El.p.v
El.R2.p.v;
El.n.v
R4.p.v;
Regarding the ResistorCircuit model, the connection equations for nonflow variables become: Rl.p.v = R2.p.v = R3.p.v
5.7.5.3
Connection Equations for Flow Variables
Each primitive connection set of flow variables (Zi) is used to generate sum-to-zero equations of the form: In order to generate equations for flow variables, the sign used for the connector variable z, above is +1 for inside connectors and -I for outside connectors, e.g., Zk in the above equation. For each flow variable Zj in a connector that is not connected as an inside connector in any element instance belonging to the model, the following zero-equation is generated: Zj
=
0;
The bold-face 0 represents a scalar zero or a zero-valued array of appropriate dimensions (i.e., the same dimensionality and size as Zj). Regarding the model ECi:Lcuit, the following sum-to-zero equations with flow variables are generated: Rl.n.i + El.p.i = 0; El.R2.n.i + El.R3.p.i = 0; El.R3.n.i + El.n.i = 0;
(-El.p.i) + El.R2.p.i
0;
(-El.n.i) + R4.p.i
The reason that a negative sign is used for outside connector variables such as El . P . i and El . n , i is rather apparent when looking at Figure 5-27 of the ECircui t model. The positive flow into the El component via the connector El . P continues in the same direction out of El . P when used internally as an outside connector in El. Since the positive flow direction is into a component and the actual flow is in the opposite direction out of E . p, a negative sign has to be used. If we expand the structured component El into its parts, i.e., effectively remove its component boundary, this will eliminate the outside connectors. Such a transformation corresponds to merging equations, e.g., adding the first two flow equations above: Rl.n.i + El.p.i
+
(-El.p.i) + El.R2.p.i = 0;
This equation is easily simplified using the negative sign of the flow variable from the outside connector. The resulting merged equation below closely corresponds to a situation where the resistors Rl and R2 would be directly connected to each other without the existence of the structured component sr: Rl.n.i + El.R2.p.i
=
0;
Returning to the matter of zero-equations, there are two connectors Rl . P and R4 . n in ECi rcui t that are not connected anywhere. The following zero-equations are generated for the flow variables in those connectors (another example of this rule is presented in Section 15.2.5.4, page 544):
172 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica Rl.p.i = 0; R4.n.i = 0;
This also means that it is not possible to have additional equations (would be too many equations!) that define unconnected flow variables like Rl . P . i and R4. n . i since they are already equal to zero. Returning to the ResistorCircuit model once more, the connection equation and the zero-equations for the flow variables become: Rl.p.i + R2.p.i + R3.p.i Rl.n.i = 0; R2.n.i = 0;
5.7.5.4
0;
R3.n.i =
OJ
Connection Equations for Constants and Parameters
Constants and parameters sometimes occur in connectors, e.g., the parameter n declared in the connector classes Reallnput and RealOutput. It does not make much sense to generate constant equations to be solved by an equation solver. On the other hand, it must be guaranteed that corresponding constants or parameters have the same value. This can be done through assert statements instead of connection equations: •
Constants or parameters in connected connectors produce assert statements instead of connection equations.
For example, the following class has the connectors ip and op, which both contain the parameter n: class ConnectedParameter "Example class with parameter connectors" RealOutput 0Pi II connector with parameter n Reallnput ipi II connector with parameter n equation connect (op, ip) i
end ConnectedParameter;
For convenience, the connector classes Reallnput and RealOutput have been replicated from Section 5.5.2 on page 161: connector Reallnput = connector RealOutput
input RealSignali
=
output RealSignal; II RealSignal is essentially Real
The equation connect (op, ip) generates the usual connection equation for the nonflow variable called signal: op.signal=ip.signal;
However, regarding the parameter n the following assert statement is produced: assert(op.n=ip.n, "");
5.7.5.5
inner/outer Connector Matching
Certain connectors might have been declared with one of the prefixes inner and outer, which are described in Section 5.8, page 173, and in the section on reference lookup using inner and outer (Section 3.13.3, page 99). A connector declared as outer is essentially just a reference to a corresponding connector declared as inner higher up in the instance hierarchy. However, recall the locality constraint on connected connectors, described in Section 5.3.2, page 149. This locality constraint has implications for the interpretation of connect equations where one or more of the arguments are connectors with the outer prefix. Since a connector declared as outer is just a reference to a corresponding inner connector declared higher up in the instance hierarchy, the connect equation has to be conceptually moved up in the instance hierarchy until the locality constraint is fulfilled, i.e., until both connector arguments are hierarchically contained within the class of the current instance. This has to be done before generating the connection equations.
Chapter 5 Components, Connectors, andConnections 173
5.7.6 Cardinality-dependent Connection Equations In certaincases there is a need to let the behavior of a model be dependent on the number of connections to certain connectors of the model. This can be achieved by using a built-in function cardinality that returns the number of connections that have been made to a connector. This is an example of a selfinspecting (reflecting)languageconstruct. •
The function cardinality(c) with formal parameter c returns the total number of (internal and external)occurrences of the connector c in connect equationsin the total model.
For example, a model library might be built with the assumption that only one connectioncan be made to each connector. Another example is to specify connection-dependent equations in a model, e.g., as in the model CardinalityResistor below, where each case with no connections to a connector or a group of connectors is treated in a special way. model CardinalityResistor
extends TwoPini parameter Real R(unit="Ohm")
"Resistance";
equation
II Handle cases if pins are not connected
if cardinality(p) == 0 and cardinality(n) p.v = 0; n.v = 0; ela8if cardinality(p) 0 then p.i = 0; elseif cardinality(n) 0 then n.i = 0; end if;
0 then
II Resistor equation v
=
R*i;
end CardinalityResistor;
5.7.7 The Direction of a Connection It is possible to get information about the direction of a connection by using the built-in function direction (c) on a connector c, provided that cardinal i ty (c) = 1, i.e., the connector c is involved in exactly one connection. Given a connection of the fo!lowing form: connect(cl,c2) ;
calls passing the two connector argumentsgive the following results: direction(cl) returns direction (c2) returns
-1 1
The cardinality and direction operators are useful when building certain kinds of libraries, e.g., librariesof bond graph components or components for modeling discreteevent systems.
5.8 Implicit Connections with the inner/outer Construct So far in we have focused on explicit connectionsbetween connectors where each connection is explicitly represented by a connect equation and a corresponding line in a connection diagram. However, when modeling certain kinds of large models with many interacting components this approach becomes father clumsybecause of the large number of potential connections--a connectionmight be needed between each pair of components. This is especially true for system models involving force fields, which lead to a
174 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica maximum of n x n connections between the n components influenced by the force field or 1 x n connections between a central object and n components if intercomponent interaction is neglected. For the case of 1x n connections, instead of using a large number of explicit connections, Modelica provides a convenient mechanism for implicit connections between an object and n of its components through the inner and outer declaration prefixes. These language constructs force lookup for implicit connections through the instance hierarchy instead of the usual nested lookup in the class hierarchy, as described briefly in the next section and more formally in Section 3.13.3, page 99. Another difference compared to explicit connections is that the inner/outer mechanism can be applied to any declared element in a class, not only to connectors.
5.8.1 Access of Shared Environment Variables A rather common kind of implicit interaction is where a shared attribute of a single environment object is accessed by a number of components within that environment. For example, we might have an environment including house components, each accessing a shared environment temperature, or a circuit board environment with electronic components accessing the board temperature. A Modelica environment-component example model along these lines is shown below, where a shared environment temperature variable TO is declared as a definition declaration marked by the keyword inner. This declaration is implicitly accessed by the reference declarations of TO marked by the prefix outer in the components compt and comp2. model Environment import Modelica.Math.sin; inner Real TO; II Definition of actual environment temperature TO Component compl, comp2; II Lookup match makes compl.TO = comp2.TO = TO parameter Real k=l; equation TO = sin(k*time); end Environment; model Component
outer Real TO; II Reference to temperature TO defined in the environments Real T; equation T = TO; end Component; model Environmentlnstances Environment envl(k=l); Environment env2{k=4); end Environmentlnstances
The instance hierarchy lookup is from an outer reference declaration to a matching inner definition declaration with the same name. The search is upward in the instance hierarchy starting from the current instance. In this example, the search starts at the components compl or comp2 upward to the Environment instances envl or env2 where the matching inner definition declaration of TO is found, as depicted in Figure 5-28. Note that there exists only one actual instance of TO in each environment, marked by the prefix inner. All outer reference declarations of TO within the components of an environment are just references to this single instance.
Chapter 5 Components, Connectors, and Connections 175 envl:
env2:
inner Real TO=sin(time)
comp!:
\"'~,,, .
compl:
Chapter 6 Literals, Operators, and Expressions 185
S-ESCAPE
,,\' " "\a n
,,\"" "\b lt
"\1" "\f"
"\\" "\n"
"\r"
I
"\t"
I
"\v"
6.3.2 Names A name is an identifier with a certain interpretation or meaning. For example, a name may denote an Integer variable, a Real variable, a function, a type, etc. A name may have different meanings in different parts of the code, i.e., different scopes. The interpretation of identifiers as names is described in more detail in Chapter 3, page 75. Package names are described in more detail in Chapter 10.
6.3.3 Modelica Keywords The following Modelica keywords are reserved words and may not be used as identifiers: algorithm break der encapsulated extends for input outer protected return while
and class discrete end external function loop output public then within
annotation connect else enumeration false if model package record true
assert connector elseif equation final in not parameter redeclare type
block constant elsewhen expandable flow inner or partial replaceable when
6.4 Predefined Types The predefmed built-in types of Modelica are Real, Integer, Boolean, and String, which are presented in more detail in Section 3.9 of Chapter 3, page 84. These types have some of the properties ofa class, e.g, can be inherited, modified, etc., but on the other hand have a number of restrictions and somewhat different properties compared to normal classes. At type checking, variables of these types are treated similarly to variables with nonclass scalar types in other programming languages. Only the value attribute can be changed at run-time, and is accessed through the variable name itself, and not through dot notation, e.g. use x and not x. value to access the value of the variable x. The machine representations of the values of these predefined types typically have the following properties: Real Integer Boolean String enumeration
lEe 60559: t 989 (ANSI/IEEE 754-1985) double format, at least 64-bit precision. typically two's-complement 32-bit integer. true or false. string of 8-bit characters. Enumeration values represented internally as integers.
Note that for argument passing of values when calling external functions in C from Modelica, Real corresponds to double and Integer corresponds to into
186 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
6.5 Literal Constants Literal constants are unnamed constants that have different forms depending on their type. Each of the predefined types in Modelica has a way of expressing unnamed constants of the corresponding type, which is presented in the ensuing subsections. Additionally, array literals and record literals can be expressed.
6.5.1 Floating Point Numbers A floating point number is expressed as a decimal number in the form of an optional sign (+ or -), a sequence of decimal digits optionally followed by a decimal point, optionally followed by an exponent. At least one digit must be present. The exponent is indicated by an E or e, followed by an optional sign (+ or -) and one or more decimal digits. The range is that of IEEE double precision floating point numbers, for which the largest representable positive number is 1.7976931348623157E+308 and the smallest positive number is 2.22507385850720 14E-308. For example, the following are floating point number literal constants: 22.5,
3.141592653589793, 1.2E-35, -56.08
The same floating point number can be represented by different literals. For example, all of the following literals denote the same number: 13 . ,
13EO ,
1 . 3e 1 ,
. 13 E2
6.5.2 Integers Literals of type Integer are sequences of decimal digits, e.g. as in the integer numbers 33, 0, 100, 30030044, or negative numbers such as -998. The range depends on the C compiler implementation of integers (Modelica compiles to C), but typically is from -2,147,483,648 to +2,147,483,647 for a two'scomplement 32-bit integer implementation.
6.5.3 Booleans The two Boolean literal values are true and false.
6.5.4 Strings String literals appear between double quotes as in "between ". Any character in the Modelica language character set apart from double quote (,,) and backslash (\), but including nonprintable characters like new-line, backspace, null, etc., can be directly included in a string without using an escape code. Certain characters in string literals are represented using escape codes, i.e., the character is preceded by a backslash (\) within the string. Those characters are:
\, \" \?
\\ \a \b \f
single quote-may also appear without backslash in string constants. double quote question-mark-may also appear without backslash in string constants. backslash itself alert (bell, code 7, ctrl-G) backspace (code 8, ctrl-H) form feed (code 12, ctrl-L)
Chapter 6 Literals, Operators, and Expressions 187
\n \r \t \v
new-line (code 10, ctrl-J) return (code 13, ctrl-M) horizontal tab (code 9, ctrl-I) vertical tab (code 11, ctrl-K)
For example, a string literal containing a tab, the words: Thi sis, double quote, space, the word: between, double quote, space, the word: us, and new-line, would appear as follows:
"\tThis is\" between\" us\n" Concatenation of string literals in certain situations (see the Modelica grammar) is denoted by the + operator in Modelica, e.g. "a" + "b" becomes "ab". This is useful for expressing long string literals that need to be written on several lines .
6.5.5 Enumeration Literals Enumeration literals are introduced by declaration of an enumeration type, e.g.: type Color = enumeration (red, blue, green); This makes the enumeration literal values Color. red, Color. blue, and Color. green available for use.
6.5.6 Array Literals Array literals can be expressed using the array constructor { } or the array concatenation operator [ ]. For example, the following are one-dimensional array constants, i.e., vector literals: {1,2,3},
{3.14, 58E-6}
Two-dimensional array constants, i.e., matrix literals, may appear, e.g. as below where the same constant matrix is expressed in two ways:
{{I , 2.} , {3 , 4} }
or
[1,2; 3,4]
More information concerning arrays and array literals is available in Section 7.2, page 210, and in Section 7.11.1 concerning empty array literals.
6.5.7 Record Literals Record literals can be expressed using the record constructor functions automatically defined as a consequence of record declarations (Section 3.14.2, page 102). Below is an example record literal of a complex number based on the record Complex: Complex(1.3, 4.56) Complex(); II Use argument default values of the constructor function
6.6 Operator Precedence and Associativity Operator precedence determines the order of evaluation of operators in an expression. An operator with higher precedence is evaluated before an operator with lower precedence in the same expression. For example, relational operators have higher precedence than logical operators, e.g.:
188 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Xwithin := x>35.3 and x=O, otherwise an error occurs. Result and argument have type Real.
div(x,y)
Returns the algebraic quotient x/y with any fractional part discarded (also known as truncation toward zero). Result and arguments have type Real or Integer. IT
200 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica any of the arguments have type Real, the result is a Real, otherwise an Integer. Examples: div(10,2)=S, div(10,3)=3, div(-2,3)=0, div(-4,3)=-1, div(10.2,3)=3.0, div(-7.1,2)=-3.0 Returns the integer modulus of x/y, i.e., mod(x,y)=x-floor(x1y)*y. Result and arguments shall have type Real or Integer. If either of the arguments has type Real, the result is a Real, otherwise an Integer. Events can be triggered.
mod(x,y)
rem(x,y)
Examples: mod(7,5) =2, mod (13, 5) =3, mod (10,5) = 0, mod(-7,S) = -7-(-2)*5 = 3, mod (7 , - 5 ) = 7 - ( - 2) * (- 5 ) = - 3, mod(2,0.9)=0.2, mod(-2,0.9)=0.7, mod(2,-0.9)=-0.7 Returns the integer remainder of x/y, such that di v (x, y) * y + rem (x, y) = x. Result and arguments shall have type Real or Integer. If either of the arguments have type Real, the result is a Real, otherwise an Integer. Events can be triggered. Examples: rem{lO,2)=O, rem(11,2)=1, rem(2,O.8) = 0.4, rem(2,-0.8) = -0.4.
ceil (x)
Returns the smallest integer not less than x as a floating point number, i.e., the closest integer above x. Result and argument have type Real. Events can be triggered. Examples:ceil(3)=3.0, ceil{3.5)=4.0, ceil(-1.7)=-1.O
floor (x)
Returns the largest integer not greater than x as a floating point number, i.e., the closest integer below x. Result and argument have type Real. Events can be triggered. Examples: floor(3)=3.0, floor(3.5)=3.0, floor(-1.7)=-2.0
Returns the largest integer not greater than x as an integer, i.e., the closest integer below x, The argument has type Real. The result has type Integer. Events can be integer (x) triggered. Examples: integer(3.5)=3, integer(-1.7)=2 The following are the continuous built-in common mathematical functions: sin(u) cos(u) tan(u) asin(u)
sine cosine tangent (u shall not be: ..., -1l/2, n /2, 31l/2, ...) inverse sine (-1 SuS 1)
acos(u)
inverse cosine (-1 SuS 1)
atan(u) atan2(ul,u2) sinh(u) cosh(u) tanh(u) exp(u) 10g(u)
inverse tangent four quadrant inverse tangent hyperbolic sine hyperbolic cosine hyperbolic tangent exponential, base e natural (base e) logarithm (u > 0)
Chapter 6 Literals, Operators, and Expressions 201 11 09 1 0 (U)
Ibase to logarithm (u > 0)
6.14 Built-in Special Operators and Functions The following built-in special operators in Modelica have the same syntax as a function call. However, they do not behave as mathematical functions since the result depends not only on the input arguments but also on the status of the simulation. The following operators are supported:
der(x)
The time derivative of x. The argument x must be a variable and not a general expression. The variable x must have a type which is a subtype of Real, and cannot have discrete-time variability, i.e., it must have continuous-time variability . If x is an array, the operator is applied to all elements of the array. For a Real argument x with parameter or constant variability, the result is a zero-valued scalar or array of the same size as x. Returns the most appropriate analysis type for the simulation context in which the model is used. The analysis type is returned as a string. The following return values are predefined:
analysisType()
• •
•
"dynamic": Solve initial value problem. "static": Solve "static" problem where all derivatives
are constant and time is fixed (e.g. trimming, equilibrium analysis). " 1 Lne ar ": Transform the continuous part of the model in a linear system.
initial()
An ini t ial () call returns true at the beginning of the simulation (when time is equal to time. start) during the initialization phase, and returns false otherwise.
terminal ()
Returns true at the end of a successful simulation.
noEvent (expr)
By' placing noEvent around expr, no events are generated from expr. Relational expressions involving real variables or function cails within expr are evaluated exactly as stated, i.e., no events are triggered at possible discontinuities of expr or its derivatives, thus avoiding generating events and event iteration. See the section on event iteration below, and Chapter 13 for more detailed information regarding this subject.
smooth (p, expr)
By placing a call to smooth around expr, we state that expr is continuous and its derivatives up to order p are continuous. This information can be used by the Modelica environment to avoid event generation and thus increase performance. However, smooth does not prohibit event generation from expr. If p>=O, then smooth (p, expr) returns expr, and declares that expr is p times continuously differentiable, i.e., expr is continuous in all real variables appearing in the expression and
202 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica all partial derivatives with respect to all appearing real variables
exist and are continuous up to order p. The only allowed types for expr in smooth are Real expressions, arrays of allowed expressions, and records only containing components of allowed expressions. See also Section 13.2.5.6, page 417. Returns true and triggers time events at time instants "s tart + i * interval" ( i =0 , 1, ... ) . During a numerical solution of the continuous part of the equation system, i.e., between the sample (start, interval) time events, the operator always returns false. The starting time start and the sample interval interval need to be parameter expressions and need to have types which are subtypes of Real or Integer. pre
pre(y)
Returns the "left limit" y(t ) of variable y(t) at a time instant t. pre At an event instant, y(t ) is the value of yafter the most recent event iteration at time instant t. The value pre (y) can be thought of as the "predecessor value" of y. The argument y must be a variable and not a general expression. Regarding event iteration see the section below or Chapter 13 for more detailed information. The pre operator can only be applied if the following three conditions are fulfilled simultaneously: (a) the variable y has a type which is a subtype of Boolean, Integer, Real, or String, or an array type of one of those subtypes.(b) the variable y is a discrete-time variable, (c) the operator is not used within a function. At the initial time pre (y) = y. start, i.e. the left limit of y is identical to the start value. See Chapter 13 for more information regarding pre, event iteration and events.
edge (b)
The expression edge (b) is expanded into (b and not pre (b) for the Boolean variable b. The same three restrictions as for the pre () operator apply. The argument b must be a Boolean variable and not a general expression.
change (v)
The expression change (v) is expanded into (v« spre (v) ) • The same three restrictions as for the pre () operator apply. The argument v must be a variable and not a general expression.
reinit (x, expr)
Reinitializes the state variable x with expr at an event instant, i.e. a kind of assignment, but not quite the same since it simultaneously removes any existing defining equation or assignment to x. The argument x must be a state variable that is a dynamic variable, which implies that (a) the type of x is a subtype of Real, and (b) the der-operator need to be applied to it somewhere in the model. The second argument expr must be an Integer or Real expression. The reinit operator can only be applied once for the same variable x, i.e, single assignment. The re ini t operator does
Chapter 6 Literals, Operators, and Expressions 203 not break the single assignment rule for equations since reinit (x, expr) makes the previously known state variable x unknown and has the same effect as introducing a new state variable x with the equation x = expr. For a simple example of the use of re ini t , see the bouncing ball example in Chapter 2 page 52. Regarding the use of reinit among equations, see Section 8.3.6 on page 249, and within algorithms, see Section 9.2.10.lon page 296. Returns the value of expr at the time (time-delayTime) for time > time. start + delayTime and the value of expr at the time time.start for time
Result: (atan2(a,d), atan2(b,e), atan2(c,f)}
All function arguments need not be generalized to arrays, only those that are actually applied to arrays of higher dimension than the declared types of the corresponding formal function parameters. Consider the function atan2Add(w,x,y) = w+atan2(x,y) that adds a value w to each application of atan2, e.g.: atan2Add(2,{a,b},{d,e})
II
Result: {2+atan2(a,d), 2+atan2(b,e)}
Formal function parameters that are generalized to higher dimension arrays need not necessarily be scalars. For example, the function atan2SumVec (vl, v2) =atan2 (sum (vl) , sum (vz) used below has two formal parameters vi and v2 of type Real [:] , computing atan2 on the sums of the argument vectors. Applying this function on a matrix which is a vector of vectors gives a result which is a vector. Calling this function with two matrices Ml and M2 as arguments givesthe following result: Real[3] vl,v2,v3,v4; Real[2,3] Ml = {vl,v2}; Real[2,3] M2 = {v3,v4}; atan2SumVec(Ml,M2)
II II
is: atan2SumVec({vl,v2},{v3,v4}l is: (atan2(sum(vl),sum(v2», atan2(sum(v3),sum(v4»}
atan2SumVec({{l,2},{3,4}}, {{6,7},{8,9}}) II which is: {atan2(sum({l,2}),sum({3,4}», atan2(sum({6,7}),sum({8,9}»} II which is: {atan2(3,7), atan2(13,l?) }
7.10.1 General Formulation of Element-wise Function Application Consider the expression f (argl, ....argn) . Then an application of the function f to the arguments argl, ..., argn is defined as follows. For each passed argument, the type of the argument is checked against the type of the corresponding formal parameter of the function. 1. If the types match, nothing is done. 2.
If the types do not match, and a type conversion can be applied, it is applied and then continued with step 1.
3.
If the types do not match, and no type conversion is applicable, the passed argument type is checked to see if it is an array of the formal parameter type. If it is not, the function call is invalid. If it is, we call this a foreach argument.
4.
For all foreach arguments, the number and sizes of dimensions must match. If they do not match, the function call is invalid. If no foreach argument exists, the function is applied in the normal fashion, and the result has the type specified by the function definition.
5.
The result of the function call expression is a multidimensional array with the same dimension sizes as the foreach arguments, i.e., arguments generalized to arrays. Each element eit..J is the result of applying f to arguments constructed from the original arguments in the following way. •
If the argument is not a foreach argument, it is used as-is.
Chapter 7 Arrays 231
•
If the argument is a foreach argument, the element at index [i,...,j] is used.
7.11 Empty Arrays It might appear ridiculous to have empty arrays, i.e., arrays that do not contain any elements. However, there is actually some use for such strange creatures. They can function as a kind of null element for certain general operations, such as, for example, concatenation operations or general formulations of certain kinds of equation systems. It makes sense to have empty arrays when representing sets as arrays in order to represent the empty set. An empty array cannot at the time of this writing be constructed in Modelica by {} or [] since in those cases the type of the array would be unknown, e.g. it would not be known whether the empty array is an array of integers, of real numbers, or of some other type. One idea would to automatically infer the type from the surrounding context, which however has not yet been formally accepted in the Modelica language standard. Instead, an empty array is created using some other array constructor, e.g. f i 11, from which the type can be deduced, or explicitly declared as a variable. For example:
II
fill{l., 0) Real x[O) i
II
An empty vector of type Real[O] since 1. is Real An empty vector variable x of type Real [0]
ReallO,3) Ai Real B [5, OJ, C [0, 0]
i
II II
An empty matrix variable A
Empty matrices Band C
Array variables of unspecified size can be set equal to or assigned empty array values, e.g.: Real A{:,:] Boolean B[:,:,:]
= =
fill(O.O, 0, 1) fill(false, 0, 1, 0)
II A Real 0 x 1 matrix
II
A Boolean 0 x 1 x 0 array
It is not possible to perform an indexing operation, e.g. A [i , j J, on an empty array since it does not contain any elements that can be accessed and returned by the indexing operation. Many array operations require certain constraints to be fulfilled by their operands. Built-in array operators such as elementwise addition (+), subtraction (-), equality (=), and assignment (:=) require that the operands have the same dimensionality and size of dimensions. Matrix multiplication (*) requires that the size of the second dimension of the first operand is equal to the size of the first dimension of the second operand. These size and dimensionality constraints also apply to array operands which are empty arrays. For example: Real[3,0] A, B; Real[O,O] Ci A + B A + C
II II
Fine, the result is an empty matrix of type Real[3,OJ Error, incompatible types Real[3,O] and Real[O,OJ
Concerning matrix multiplication, the above-mentioned constraints on operands together with the size and dimensionality of the result can be expressed as follows: •
Matrix[n,m]*Matrix[m,p] giving a result matrix of size and dimension Matrix[n,p]
For the case of empty arrays this definition gives the following result: •
Matrix[n,O] *Matrix [0,p] giving a result matrix of size and dimension Matrix[n,p]
What is remarkable here is that matrix multiplication of two empty arrays sometimes gives rise to a nonempty array filled with zero values, which is somewhat counterintuitive but according to a general definition of matrix multiplication. The behavior of matrix multiplication of empty matrices and vectors is summarized in the following table. Table 7-1. Matrix multiplication of empty arrays.
I Type of argl
I Type of arg2
I Type of argl*arg2 I Value
232 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Real[O] Real[n] Real[O,m] Real[m,O] Real[O,m] Real[m,O] Real[m,O]
Real[O,m] Real[n,O] Real[m] Real [0] Real[m,n] ReallO,n] Real[O,n]
Real[m] Real[O] Real [0] Real[m] Real[O,n] Real[m,O] Real[m,n]
zeros(m) empty vector empty vector zeros(m) empty matrix empty matrix zeros{m,n)
One might ask why such a general and somewhat nonintuitive definition of matrix multiplication should be allowed. Is there some practical usage for this feature? Surprisingly, the answer is yes. Consider the following linear ordinary differential equation system model formulated in A-B-C-D matrix form with a state vector x, an input vector u, and an output vector y: model ABCDsystem
Real u[p], x[n], y[q] i Real A[n,n], B[n,p], C[q,n], D[q,p]; equation der(x)
= A*x + B*Ui C*x + D*Ui end ABCDsystemi Y
=
Assume that n=O, i.e., the state vector is empty, the input vector u is nonempty with size p>O, and the output vector y is empty with size q>O. Using the definitions in the above table, the first equation will disappear since x is empty, causing der (x) to be an empty vector with type Real [0], with A*x and B*u also being empty vectors with type Real [0]. In the second equation the term C*x becomes a vector zeros (m) of type Real [m] containing m zero-valued elements. Since zero-valued elements can be eliminated in addition operations the second equation simplifies to: y
= D*u
7.11.1 Empty Array Literals As mentioned in the previous section, empty array literals can be constructed by the f i 11 array constructor function: The call fil1(constelem, nl, n2, n3, ...) returns an empty array literal of dimension nl x n2 x n3 x etc., provided at least one of the dimensions ni is zero, with element type being the type of constelem, which can be of any Modelica type expressible as a constant literal.
•
For example: fill(O.O, 0, 1) II A Real 0 x 1 matrix fill(false, 0, 1, 0) II A Boolean 0 x 1 x 0 array fill (Person("Jane" , 54.5, 170), I, 0) II A Person 1 x 0 array Two other possibilities, which however are not part of the Modelica language standard at the time of this writing (but might be included later), would be:
°
{}-denoting an empty array of dimension size 0, where the element type is inferred from the context. As a consequence, {{ } } would be an x 1 matrix of inferred element type. [] -denoting an empty array identical to {{ }}, i.e. an 0 x 1 matrix of inferred element type. This is natural since [xl is the same as {{x} } which has dimensions 1 x 1.
• •
Such a notation would be somewhat more concise and readable compared to using fill, e.g.: Person x [ : ] equation x
= {}i
i
Chapter7 Arrays 233
7.12 Summary This chapter has presented most aspects of arrays in Modelica, starting with the declaration of arrays and array types, arrays sizes, and type checking for arrays. We continued by presenting the general array construction operator, the special array constructor for range vector construction, array constructors with iterators, and the Matlab compatible combined array concatenation and construction operator. We also presented array indexing with different kinds of arguments, as well as accessing and constructing array slices. One section gave special advise for users with Matlab background regarding the use of array concatenation and slices, including the construction of block matrices. We presented the four common arithmetic operators and their interpretation when used on arrays as well as on combinations of arrays and scalars. A set of built-in array functions were described, including four array reduction operators that can have iterator arguments. The chapter was concluded by presenting how scalar functions are automatically promoted to work for arrays, and how empty arrays can be declared and array literals created.
7.13 Literature The description of arrays given here is based on the MOOeHca Language Specification (Modelica Association 2003), including most examples. The array design of Modelica has primarily been influenced by MATLAB (MathWorks 2002), Fortran90 (Adams, Brainerd, Martin, Smith, and Wagener 1992), C (Harbison and Steele 1991), and Mathematica (Wolfram 1997). Array constructors with iterators in Modelica are analogous to array comprehensions in several functional languages, e.g. Haskell (Hudak 1989), Standard ML (Myers, Clack, and Poon 1993), or the Table array constructor in Mathematica (Wolfram 1997).
7.14 Exercises Exercise 7-1:
Constructing Arrays: Create a record containing several vectors and matrices. It is your choice what types and values the variables should have: • • • • •
a vector with seven values, a matrix of four rows and two columns, a matrix of one row and five columns, two unspecified matrices, and an empty matrix.
Exercise 7-2:
Expanded Type: Consider the classes Student, Class and GraduateClass below. Which is the expanded type of GraduateClass? class Student constant Real legs = 2; constant Real arms = 2; parameter Real nrOfBooks; parameter String name = "Dummy"; end Stlldent; type Class
=
Student [35) ;
class GraduateClass Class[42] c; end GraduateClass;
234 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Exercise 7-3: Question: What is a range vector? Give an example of a range vector with 5 Integers with increasing by 5 for each additional element. Exercise 7-4: Considering Array Ranges: Which result do the v1, v2, v3, v4 and vs have below? class RangeVectors Integer vl[6] = 3 : 8; Integer v2[10] = -20 -11; Real v3[5] = 11.3 : 15.3; Integer v4{0]; Real v5 [3] = 1.1 : 3.1; end RangeVectors;
Wider Ranges: How can you construct the range vectors below? {lS.O, 18.0, 21.0, 24.0, 27.0}, {-6.S, -8.5, -IO.S}
and an empty Integer vector. Exercise 7-5: Question: Which are the type rules for concatenation? Considering Array Concatenation: What will be the result of the arrays below? class ArrayConcatenation Real [2, 3] array1 cat (2, Real[2, 3] array2 cat(2, Real[2, 2] array3 cat(l, Real[3, 2] array4 cat(l, Real[3, 2] arrayS cat(l, Real[4, 2] array6 cat(l, Real[2, 4] array7 cat(2, end ArrayConcatenation;
[22, 34; 66, 78], [15; S2]); {{22, 34}, {66, 78}}, {{IS}, (52}}); {{II, 12}}, {{13, 14}}); {{7, 2}, {s, 42}}, ({24, 74}}); [7, 2; 5, 42], [24, 74]); {{I, 2}, {II, 12}}, {{13, 14}, {3, 4}}); {{I, 2}, {72, 51}}, {{3S, 73}, (12, 23}});
Using cat: Now it is your tum to concatenate arrays using cat: • • • •
Concatenate two lx2-arrays along the first dimension. Concatenate the arrays you just concatenated, but along the second dimension. Concatenate one 2x3-array with a 2xl-array along the second dimension. Concatenate two 2x2-arrays along the first dimension.
What are the results of the array concatenations? class MyArrayConcat end MyArrayConcat;
Exercise '-6: More Dimensions: The final thing you should do now is concatenate three arrays with higher dimension. So, the arrays you should concatenate are of size lx2xl, lx2x2 and lx2x3 and they should be concatenated along the first dimension. Do the concatenation in the class MoreConcat below. What is the result after the concatenations? class MoreConcat
end MoreConcat;
Chapter 7 Arrays 235 Exercise7-7:
Array Indexing: In the class Arraylndexing below, you should first define a 2x3-array and set values to every position in the array. Also define a second array while you're at it, with the same size but with different values. The final thing you should do is to change a few values in each array. Then you're done! Oh, one more thing; what are the results after changing the values? class Arraylndexing end Arraylndexing;
Tip: When you set the values in the arrays you can use the fill function to fill a whole array with a value fill (value, nrOfRows, nrOfColumns). Indexing with Scalar Expressions: In the class Arraylndexing2 below you should first define a 2x2array and set values to every position in the array. Then define a second 2x4-array with different values. This time you should change a whole row in each array.
What are the results after changing the values? class Arraylndexing2 end Arraylndexing2; Accessing Array Slices with Index Vectors.' What is the result of the vectors vl , v2, v3, v4, v5, v6, v7, v8 and v9 below? class Slice Real [3, 3] V = {{ 2 2, 14, 71}, { 33, 41, 1 7 }, {4 4, 11 , 77}}; Real [3, 2 J w = {{ 12, 13}, { 2 3, 88}, { 9 9, 4 3 }} ; Rea 1 [5] Y = {23 , 24, 2 5 , 26 , 27 } ; Real Real Real Real
v l, [3]
V[:, 1];
v2[3] v3[1] v4[3]
V[3, V[3,
:]; {2}];
W[:,
2];
Real v5[2] Real v6[2] Real v7[2] Real v8[2] Real v9[3] end Slice;
Y[{l, 2}l; W[3, V[3,
{i , 2}]; 1 :2] ;
Y [3 :4] ; Y[l:2:5] ;
Exercise7-8: Concatenate.· Complete the class, Concatenate, like this:
(i) Create a new variable VI in which you append 60 to A. (ii) Append 50 to VI. (iii) If you didn't use the cat-operator before, use this to append 60 to A. (iv) Append the set of 60 to B. (v) If you didn't use the cat-operator before, use this to append 60 to B. (vi) Append the set of 18 to v, using the cat-operator.
class Concatenate Real [1, 2] [50, 32]; Rea 1 [2, 1 ] [3; 7]; Real [5] = {4, 9, 7, 5, 2}; end Concatenate;
236 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica Question: Which are the results of your newly created variables? Exercise 7-9:
Question: Is this allowed? If not, why not? ITit is, what is the result? class Add1 Real Al[2] end Add1;
=
{2, 3} + 1;
Is this allowed? If not, why not? If it is, what is the result? class SubS Real A5[3] end SubS;
=
{3, 45, 6} - 5;
Is this allowed? If not, why not? If it is, what is the result? class Mult2 Real A2[3] end Mult2;
= {II,
14, 12} * 2;
Exercise 7-10:
Matrix Multiplication: Write a class that multiplies two matrices using the multiplication operator for
matrices. Exercise 7-11:
Question: Is this allowed? ITnot, why not? If it is, what is the result? class MultMany Real muI t 1 = { 1 , 1 , I, I} * {I, 1, I, 1 } ; Real muI t2 [2] = {{ 2, 2}, {2, 2}} * {2, 2}; Real muLt 3 [2, 2] = {{ 1 ,I}, {I, I}} * {{ 2, 2}, {2, 2}}; Real muLt4 (1] = {I, 3, 5 7} * {{ 1 } 3 l . {S l . { 7 } } ; end MultMany; I
I
{
Is this allowed? If it is, what is the result?
class Div4 Real A4[S] = {16, 14, 10, 18, 12} / 4; end Div4;
Is this allowed? If it is, what is the result? class Div7 Real A4(S] end Div?;
= 7 / {16, 14, 10, 18, 12};
How would you write { {1, 3}, {4, 5 } } 2 in Modelica? Write the expression in a class. What is the result? A
237
Chapter 8 Equations
Equations are the foundation of Modelica. This should be rather apparent for the reader at this stage, with equations and equation-based class examples appearing in each of the previous chapters. As already has been emphasized, equations are more flexible than traditional programming constructs like assignment statements since they do not prescribe a certain data-flow direction. This is the key to the physical modeling capabilities and increased reuse potential of Modelica classes. The goal of this chapter is to give an overview in one place of all kinds of equations that can occur in Modelica models. Certain kinds of equations are primarily described here, whereas other equation types are treated in more detail in other parts of this book. For example, declaration equations and modification equations are described extensively in Chapter 3 and Chapter 4 respectively, whereas the topic of connection equations occupies a large part of Chapter 5. Conditional equations like if-equations and whenequations are only briefly covered here but are presented in more detail in Chapter 13.
8.1 General Equation Properties Equations are different in many ways compared to traditional programming constructs like assignment statements and control structures. Equations are used in several different ways and are rather expressive. There are also certain necessary conditions for the total system of equations to be solvable, like having the same number of variables and equations. Some of these aspects are discussed briefly below.
8.1.1 Equation Categories and Uses Thinking in equations is a bit unusual for most programmers. The reason is that equations express relations and constraints in a declarative way, rather than forcing the programmer to handle control flow and data flow more or less explicitly as in conventional imperative and object-oriented languages. In Modelica equations are used for many tasks: • • •
Assignment statements in conventional languages are usually represented as equations in Modelica. Attribute assignments are represented as equations. Connections between objects generate equations.
Equations in Modelica can informally be classified into three different categories depending on the syntactic context in which they occur:
238 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica
•
Normal equations occurring in equation sections, including connect equations and other equation types of special syntactic form. Declaration equations, which are part of variable, parameter, or constant declarations. Modification equations, which are commonly used to modify attributes of classes. Initial equations, which are used to express equations for solving initialization problems.
• • •
Each of these equation types will be covered in separate sections in this chapter. Equations are declarative and express relations between expressions. Therefore they are not allowed in algorithm sections and functions which contain only algorithmic imperative code, i.e., sequences of statements that are "commands." Conversely, assignment operations (:=) are allowed in algorithm sections and in functions, but not in equation sections.
8.1.2 Expressivity of Equations Equations are more expressible than assignment statements. For example, consider the well-known resistor equation once more, where the resistance R multiplied by the current i is equal to the voltage v: = Vi
R*i
This equation can be used in three ways corresponding to three possible assignment statements: computing the current from the voltage and the resistance, computing the voltage from the resistance and the current, or computing the resistance from the voltage and the current. This is expressed in the following three assignment statements: i v R
.- viR;
.-
R*i;
.- vii;
8.1.3 Single-assignment Rule for Equations All of the equations of a Modelica model to be simulated form a total system of equations. These equations usually come from a number of classes that comprise the total system model, and only in very simple cases from a single class. It is essential that this system of equations can be solved; otherwise, the model cannot be simulated. One important prerequisite for solution is that the system is neither underdetermined nor overdetermined, i.e., the number of equations is equal to the number of unknowns. This can be formulated as the single-assignment rule for equations, which can be understood as having one equation assigned to each unknown:
•
Single-assignment rule for equations: the total number of "equations" is identical to the total number of "unknown" variables to be solved for.
By counting "equations" according to this rule we mean counting both equations and assignment statements, including assignments within when-equations and when-statements. Multiple assignments to a variable within the same algorithm section is counted as a single assignment. Assignment statements within function bodies are not counted. If the equations in the system are "unique", i.e., not trivial combinations of each other, the system is not underdetermined and there are usually good chances for solution. This rule also prevents a variable from being defined by two equations, which would give rise to conflicts or nondeterministic behavior. The single-assignment rule is valid for all Modelica models of systems to be simulated, including hybrid models that contain conditional equations, where certain equations are typically activated or deactivated dynamically during simulation. Modelica imposes certain constraints on the form of such conditional equations in order to guarantee that this rule is always obeyed. This is discussed briefly here and in more detail in Chapter 13 on hybrid and discrete event modeling. Note that the single-assignment
Chapter 8 Equations 239
rule need not apply to single classes, since these might require combination with other classes to form a model thatcanbe simulated.
8.1.4 Synchronous Data-flow Principle for Modelica The single-assignment rule is a necessary but not sufficient condition for the solvability of a system of equations. Another principle, called the synchronous data-j1ow principle, is the basis for the design of the hybrid part of the Modelica language, i.e., the handling of events and interaction between the continuous and the discrete parts of a model during simulation. This principle together with the single-assignment rule makes it possible for the Modelica compiler to perform compile-time consistency checks that, for example, usually can prevent deadlocks caused by cyclic dependencies from occurring during a Modelica simulation. The drawback is that certain "asynchronous" models cannot be expressed. The synchronous data-flow principle can be expressed in the following way for Modelica: •
•
•
All variables keep their actual values until these values are explicitly changed. Variable values can be accessed at any point in time during "continuous integration" (Le., numerical solution of the continuous part of the system of equations), and at event instants. At every point in time, during "continuous integration" and at event instants, the active equations express relations between variables which have to be fulfilled concurrently. Equations are not active if the corresponding if-branch or when-equation in which the equation is present is not active because the corresponding branch condition currently evaluates to false. Computation and communication at an event instant does not take time. (If computation or communication time has to be simulated, this property has to be explicitly modeled).
It is useful to keep this principle in mind when understanding hybrid models containing conditional equations, as, for example, in the sections on conditional equations with if-equations and when-equations below. The principle is just stated here as background information, and is explained in more detail in Section 13.2.3 on page 410 in Chapter 13 on discrete-event and hybrid modeling.
8.2 Equations in Declarations There are two kinds of equations that occur as parts of declarations: declaration equations and modifier equations, where redeclaration equations are classified as a kind of modifier equations. As already mentioned, declaration equations are covered in more detail in Chapter 3 and modifier equations in Chapter 4.
8.2.1 Declaration Equations Declaration equations are usually given as part of declarations of constants or parameters, for example: constant Integer one = 1; parameter Real mass = 22.5;
Such equations are actually required for constants, but are optional for parameters. An equation always holds, which means that the mass in the above example never changes value during simulation. It is also possible to specify a declaration equation for a normal variable, e.g.: Real speed
= 72.4;
240 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica However, this does not make much sense since it will constrain the variable to have the same value throughout the computation, effectively behaving as a kind of constant. Therefore a declaration equation is quite different from a variable initializer in other programming languages.
8.2.2 Modifier Equations Modifier equations occur, for example, in a variable declaration when there is a need to modify the default value of an attribute of the variable. A modifier equation replaces the declaration equation, if present, for an .attribute of the type in question. A common usage is modifier equations for the start attribute of variables, e.g.: Real speed(start=72.4)i
Modifier equations also occur in type definitions, e.g. as below: type Voltage = Real(unit="V", min=-220.0, max=220.0)i
8.3 Equations in Equation Sections As stated previously, normal equations appear in equation sections started by the keyword equation and terminated by one of the keywords or keyword combinations end, equation, algorithm, protected, public, or ini tial equation. Thus, the general structure of an equation section appears as follows: equation
equations some other allowed keyword The following kinds of equations can be present in equation sections: • • • • • •
Simple equality equations. Repetiti ve equation structures with for-equations. Connect-equations. Conditional equations with if-equations. Conditional equations with when-equations. assert and terminate.
Simple equality equations containing an equal sign (=) are the most basic and common kinds of equations in Modelica models, and the only ones known from mathematics. In fact, the other syntactic forms of equations (except for the last) are transformed by the Modelica compiler to this basic kind of simple equation often combined with some event-handling code.
8.3.1 Simple Equality Equations Simple equality equations are the traditional kinds of equations known from mathematics that express an equality relation between two expressions. There are two syntactic forms of such equations in Modelica. The first form below is equality equations between two expressions, whereas the second form is used when calling a function with several results. • •
exprl = expr2; (outl, out2, out3, ... )
function_name (inexprl, inexpr2, ... ) i
Chapter 8 Equations 241 The second form is equivalent to several simple equations setting the variables outl , out2, out3, etc. in the parenthesized list equal to the results of the function call in that order. No expressions are allowed in the parenthesized list on the left-hand side, only variables. For example, the first equation in the class EqualityEquations below involving the function £ with two inputs and three results is correct, whereas the second equation is illegal since there are expressions in the left-hand side: class EqualityEquations
Real X,y,Zi equation (x , y, z ) (x+l, 3.0, z/y)
£(1.0, 2.0) i £(1.0, 2.0) i
II Correct! II Illegal!
Not a list of variables
lion the left-hand side end EqualityEquationsi
Type equivalence is required between the expressions on the left-hand side and the right-hand side of equations (see page 84 in Chapter 3). Variability can be different on the two sides. However, for equations where both the left-hand side and the right-hand side are of subtypes of Integer, Boolean, or String, the variability of both sides cannot be higher than discrete-time (see also the section on variability in Chapter 6, page 192). For equations involving record or array expressions, this rule is applied to corresponding parts of these data structures broken down to elements of built-in types.
8.3.2 Repetitive Equation Structures with for-Equations Repetitive equation structures can be expressed rather compactly with the special syntactic form of equation called a for-equation. Such a structured equation can be expanded to a sometimes large number of simple equations. The syntactic form of a for-equation with a single iterator is as follows: for iteration-variable in range-expression loop
equation)
equations. end for
The iteration-variable ranges over the set of values in the range-expression which must be a vector expression with parameter or constant variability, and has the same type as the elements in the rangeexpression. This expression is evaluated once in each for-equation, and is evaluated in the scope immediately enclosing the for-equation. Such a scope can typically be the scope of an enclosing class definition or the scope of an enclosing for-equation. The iteration-variable is defined within the scope of the for-equation itself. One copy of the equations in the body of the for-equation is effectively generated for each value of the iteration variable. Consider the following simple class example with a for-equation: class FiveEquations
Real [5]
Xi
equation for i in 1:5 loop x [il = i+l i end for; end FiveEquationsi
That class is equivalent in behavior to the class below, where the for-equation has been unrolled into five simple equations: class FiveEquationsUnrolled
Real [5]
Xi
242 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica equation xlI] x[2] x[3] x (4]
2; 3; 4; 5;
x[5] 6; end FiveEquationsUnrolled; Nested for-equations can instead be represented by a single for-equation with multiple iterators: for iteration-variable) in range-expression), iteration-variable- in range-expressions, ... loop end for
Two more sophisticated examples of how we can write for-equation range expressions are shown in the for-equation headers below for r in 1.0 : 1.5 : 5.5 loop for i in {1,3,6,7} loop
II II
r takes the values 1.0, 2.5, 4.0, 5.5
i takes the values 1, 3, 6, 7
The range expression can be an Integer or Real vector, a vector of enumeration values of some enumeration type, or a Boolean vector. In the case of a vector of enumeration or Boolean values, the type name (e.g. Boolean or Sizes in the example below) can be used to denote the range expression, meaning the full range from the lowest to the highest value of the type in question. For example: type Sizes
= enumeration (small,
medium, large);
for e in Sizes loop II e takes values Sizes.small, Sizes.medium, Sizes.large for e in Sizes.small : Sizes.large loop II Same sizes, as above for e in Boolean loop II e takes the values false, true
Since the scope of the iteration variable is the enclosing for-equation, it may hide other variables with the same name, e.g. the constant k declared in the class HideVariable. Note that the k used in the iteration expression 1: k+l is the constant k declared in the class, whereas the k used in the equations inside the forequation is the iteration variable k, One should avoid this style of modeling even if it is legal since it is confusing and hard to read such code. class HideVariable constant Integer k=4;
Real x[k+1] ; equation for k in 1:k+1 loop x[k]=k;
II II
The iteration variable k gets values 1,2,3,4,5 Uses of the iteration variable k
end for; end HideVariable;
8.3.2.1
Implicit Iteration Ranges
The iteration range of a loop variable may sometimes be inferred from its use as an array index, e.g. as in the example below. See Section 9.2.5.1, page 289, for more information on iteration range inference. Real x[n],y[n]; for i loop x I i l = 2*y[i]; end loop;
8.3.2.2
II
for i in l:size(a,l) loop
Polynomial 'Equations Using for-Equations
Consider a polynomial equation: n+1 i t
Y= Lc;x ;=1
Same as:
Chapter 8 Equations 243 This equation can be used to obtain the value of a polynomial, given a set of coefficients Ci in a vector c of length n+ 1, where c[i] = Cit The powers of x are stored in a vector xpowers, where xpowers[i]= xi-I. xpowers:
The contents of the vector xpowers is defined by the following set of equations: xpowers[l] xpowers[2] xpowers[3]
xpowers[l]*x; xpowers[2]*x;
xpowers [n+l]
xpowers[n]*x;
1;
This can be expressed more compactly as a simple equation together with a for-equation: xpowers[l] = 1; for i in l:n loop xpowers[i+l] = xpowers[i]*x; end for;
Finally the polynomial equation can be expressed using a scalar product between the vectors: y
=c
* xpowers;
Everything is packaged into the class PolynomialEvaluator below. This can be a restricted class of the block kind since both public variables have specified causality input or output. block PolynomialEvaluator parameter Real c[:l;
input output protected
Real Xi Real y;
parameter Integer n Real xpowers[n+l];
size(c,l)-l;
equation
xpowers[l] = 1; in l:n loop xpowers[i+l] = xpowers[i]*x; end for; y = c * xpowerSi end PolynomialEvaluator; for i
We can, for example, use this class to evaluate a simple polynomial in terms of the built-in variable time, by instantiating the class with the coefficient vector c= {1 , 2, 3 , 4 }: class PolyEvaluatel Real p;
PolynomialEvaluator polyeval(c
(1,2,3,4})
i
equation
polyeval.x = time; p = polyeval·Yi end PolyEvaluatel;
An alternative way is to bind the inputs and the outputs using modifier equations in the declaration of the polyeval instance of PolynomialEvaluator: class PolyEvaluate2
Real Pi PolynomialEvaluator polyeval(c ={1,2,3,4}, x=time, y=p)i end PolyEvaluate2;
244 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica 8.3.2.3
Variable-length Vector Step Signals Using for-Equations
The following is the general version of the class Step as it appears in Modelica. Blocks. Sources. A similar version of Step that also inherits so is used in Chapter 15, page 523. block Step "Generate step signals of type Real" parameter Real height=l "Heights of steps"; parameter Real offset=O "Offsets of output signals"; parameter SIunits.Time startTime=O "Output = offset for time < startTime"i extends Interfaces.SO; equation y = offset + (if time < startTime then 0 else height); end Step;
8.3.3 Connect Equations In Modelica we use connect equations to establish connections between components via connectors. The general form of a connect equation is as follows: connect (connector) , connector2) The following constraints apply to the two arguments connector} and connector2 of a connect equation: •
The two arguments of a connect equation must be references to connectors, each of which either has to be declared directly within the same class where the connect equation occurs, or has to be a member of one of the declared variables in that class.
This implies a locality constraint on connections: it is not possible within a class to connect connectors declared outside a class to connectors within the class. This is natural since the connectors of a class should be the external interface of that class, implying that external connections should be via that interface. The ResistorCircuit class example below (also in Figure 5-15 on page 155 in Chapter 5) connects connectors called p belonging to components Rl, R2, and R3. This fulfills the locality constraint mentioned above. model ResistorCircuit
Resistor Rl(R=lOO)i Resistor R2(R=200); Resistor R3(R=300)i equation connect(Rl.p, R2.p)i connect(Rl.p, R3.p); end ResistorCircuit;
Connect equations are described in more detail in Chapter 5. See also Section 8.5, page 258 regarding equation operators for overconstrained connections.
8.3.3.1
Repetitive Connection Structures
We can also use connect equations together with the for-equation construct described previously to establish repetitive connection structures consisting of a number of connections between connectors belonging to array elements. This is a very important use of for-equations in combination with connect equations. For example, in the class RegComponents below there is an array called components in which each element outlet has been connected to an inlet from its neighbor element, apart from the outlet of the nth element, which is still free for external connections: class RegComponent Component components[n]; equation
Chapter 8 Equations 245 for i in 1:n-1 loop connect(components[i] .Outlet, components [i+l] .Inlet); end for; end RegComponent;
8.3.4 Conditional Equations with if-Equations Modelica can be used for expressing hybrid models, i.e., models with mixed continuous and discrete parts. One can use two kinds of equation constructs for such models: conditional equations with if-equations and conditional equations with when-equations. How can we know which one to use in different hybrid modeling situations? The following guidelines are useful:
•
•
If-equations (see also Section 13.2.6, page 421) or if-expressions (see Section 6.12.2, page 197) are used for conditional models with different behavior in different operating regions. The conditional equations may contain continuous-time expressions. When-equations are used to express instantaneous equations that are valid (become active) only at events, e.g. at discontinuities or when certain conditions become true. The conditional equations automatically contain only discrete-time expressions since they become active only at event instants.
The general form of the if-equation is specified belo\\·. The elseif-part is optional and can occur zero or more times. The else-part is also optional and can occur at most once. if then <equations>
elseif then < equations>
else <equations>
end if;
For example, the if-equation below specifies different equations for the variable y in three different operating regions, limiting values of y such that: uMin elsewhen then < equations> end when;
For example, the two equations in the when-equation below become active at the event instant when the Boolean expression x > 2 becomes true. when x > 2 then yl = sin(x); y3 = 2*x + yl+y2; end when;
Chapter 8 Equations 247
If we instead use a Boo 1ean vector expression containing three elements as the conditions, then the two equations will be activated at eventinstants when eitherof the threeconditions: x > 2, sample (0 2), or I
x < 5 becomes true. Typically each condition in the vector gives rise to its own event instants. when {x
>
2, sample(O,2), x
yl = sin (x) ; y3 = 2*x + yl+y2;
2 then when yl > 3 then y2 = sin(x); end when; end when; end ErrorNestedWhen;
8.3.5.2
II
Error! when-equations cannot be nested
Application of the Single-Assignment Rule on when-Equations
Two when-equations may not define the same variable. Without this rule that may actually happen for the erroneous model DoubleWhenConflict below, since there are two equations (close = true; close = false;) defining the same variable close. A conflict between the equations will occur if both conditions would become true at the same time instant.
model DoubleWhenConflict Boolean close; II Erroneous model: close defined by two equations! equation when conditionl then close = true; end when; when condition2 then
close = false; end when; end DoubleWhenConflict One way to resolve the conflict would be to give one of the two when-equations higher priority. This is possible by rewriting the when-equation using elsewhen, as in the WhenPriority model below or using the algorithmic version of the when-construct shown in Chapter 9, Section 9.2.9, page 293. The when-equation involving an elsewhen-part resolves the conflict since the first of the two event handlers is given higher priority:
model WhenPriority Boolean close; equation
II
Correct model: close defined by two equations!
Chapter 8 Equations 249
when conditionl then close
=
true;
eIs.when condition2 then close = false; end when; end WhenPriority;
Here it is well defined what happens if both conditions become true at the same time instant since condition1 with associated conditional equations has a higher priority than condition2.
8.3.6 reinit The following is a rather special form of equation (also available as an operator or statement, see Table 6-1 on page 188 in Chapter 6, and as a statement in Chapter 13, Section 13.2.5.11 on page 420) that can be used in when-equations to define new values for continuous-time state variables that are dynamic (der ( ) is applied to those variables, having a subtype of Real) of a model at an event: rein! t istatevariable, valueexpressioni
This "equation" effectively "removes" (deactivates) the previous equation defining statevariable and "adds" a new instantaneous equation statevariable = valueexpression that gives a new defmition to statevariable, which is valid at the current event and is used to reinitialize the variable. Neither the number of variables nor the number of equations is changed. The single-assignment rule is therefore not violated. If instead of reini t we would have used an algorithm section containing the assignment statement "v : = -c*v" there would have been an error message of too many equations since the previous equation was not removed. The BouncingBall example already seen in Figure 2-25 on page 52 in Chapter 2 illustrates the use of rein it: model BouncingBall "The bouncing ball model" parameter Real g=9.81; II gravitational acceleration parameter Real c=O.90; II elasticity constant of ball Real height (start=O) ; II height above ground Real v(start=10); II velocity equation der(height) = Vi der(v) -g; when height= lowlimit and x The following holds for an initial equation section: • •
Any kind of equation is allowed inside an initial equation section, except for when-equations. In the equations inside an initial equation section der (x) and pre (v) are treated as variables with unknown values in the initialization system of equations.
However, certain when-equations outside an initial equation section can contribute to the initialization system of equations (see Section 8.4.1.3 below.)
Chapter 8 Equations 253 We can use an initial equation section to specify the initialization constraint for a derivative: initial equation der(x) = 0; This is useful when we want to investigate and initialize a system in steady state, i.e., variables do not change with time (their derivatives are zero) if the system inputs do not change. For example: model ContinuousController "Continuous Proportional Controller" Real y(fixed false) i II fixed=false is redundant since it is default equation der(y)
=
a*y + b*u;
initial equation der(y) = 0; end ContinuousController The start value gives no additional constraint since fixed=false. The extracted equations for the initialization problem are as follows: der(y) = a*y + b*u; der(y) = 0;
This system has the following solution for initialization: der (y) y
8.4.1.3
0;
= -b/a *
U;
Using when-Equations During Initialization
During the initialization phase, the equations inside a when-equation are included in the initialization system of equations only if they fulfill the following condition: The equations inside a when-equation are included in the initialization equation system if they are explicitly enabled with the initial () operator.
•
if and only
Thus, even if a when-equation is active during simulation at an initial t.Lme e O, its equations are not included if the initial () operator is not used among the predicates of the when-equation. The initialization phase is actually executed before simulation starts at time=O. For example, the following when-equation from the ProcessControl2 model below explicitly enables its equations for initialization by its use of the initial () operator: when {initial(), sample(O,Ts)} then xd = pre(xd) + Ts/T*(xref-x)i u = k*(xd + xref - x); end when
Note that this when-equation is also active during the simulation phase at the initial time=O by its use of sample (0, Ts), which generates its first sample at time=O. If the ini t ial () is removed from the when-equation predicate, its equations are not included in the initialization system of equations. Instead the two default equations related to the variables defined in the when-equation are used. These equations hold when the when-equation is not active: xd u
pre (xd) ; =
pre (u ) ;
8.4.1.4
Explicit and Implicit Specification of Parameter Values for Initialization
By far the most common way of specifying parameter values is through explicit definition equations where the right-hand sides are literal constants or parameter expressions, e.g. g, m, and L in the Pendulum model below: model Pendulum
254 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica import Modelica.Math.*1 parameter Real 9 9.81; parameter Real m = 1 "mass"; "Pendulum Length; parameter Real L = 1 Real phi "Angle"; , "Angular velocity"; Real w Real x,y "Point mass coordinates"; equation der(phi) = W; m*der(w) = -(m*g!L)*sin(phi)i x = L*sin(phi); y = -L*cos (phi) end Pendulum;
The pendulum is depicted in Figure 8-1.
_...
---",JfT
Figure 8-1. A simple planar pendulum.
The variables x and y are not independent since the pendulum point mass coordinates x and y are constrained to positions on a circular path, fulfilling the following Pythagorean condition: (8-1) Now consider that we would like to specify the initial position of the point mass, e.g. as follows: Real x(start = 0.3, fixed = true); Real y(start = 0.4, fixed = true);
The length L computed according to equation (8-1) becomes ~0.32 +0.4 2 =0.09+0.16=0.25 =0.5, which contradicts the specified initial value L= 1, which cannot be changed since its default attribute fixed=true according to the above model. However, if we let its attribute f Lxede f a Lae, the initial value of the length L is implicitly computed from the initial values of x and y in the following variant of the model: model PendulumlmplicitL import Modelica.Math.*; parameter Real 9 = 9.81; "mass"; parameter Real m = 1 parameter Real L(fixed=false); "Pendulum Length; "Angle"; , Real phi Real w "Angular velocity"; 0.3, fixed true); Real x(start 0.4, fixed = true); Real yCstart equation der(phi) = Wi m*der(w) = -(m*g/L)*sin(phi)i x = L*sin(phi); y = -L*cos(phi) end PendulumlmplicitL;
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _Chapter 8 Equations 255 Implicit specification of a parameter value may appear strange. However, recall the definition of a parameter variable in Modelica: a parameter is a variable that is constantduring simulation. Letting the parameter value depend on the initial values of time-dependent variables does not violate this definition. This feature is actually quite useful in certain modeling situations. For example, when modeling power systems it is common to specify initial conditions such as power dissipation levels, which then implicitly may specify parameter values such as resistance that are related to the power dissipation. Parameter values may also be specified by reading from a file, e.g. as in the readParameterData model below. model readParameterData parameter Real A(fixed=false) ; parameter Real w(fixed=false) ; Real Xi initial equation (A,w) = readSineData("init.txt"); equation der(x) = -A*sin(w*x)j end readParameterDataj
Single start attribute values can also be read directly from a file, e.g.: parameter Real A(start
8.4.1.5
= readAdata("initA.txt"»;
The Number of Equations Needed for Initialization
How many equations are needed to solve an initialization problem? In general, for the case of a pure ordinary differential equation (ODE) system with n state variables and m output variables, explained in more detail in Section 2.20.2, page 60, or in Section 12.6, page 398, we will have n+m unknowns in the simulation problem. The ODE initialization problem has n additional unknowns corresponding to the derivative variables. At initialization of an ODE we will need to find the values of 2n+m variables, in contrast to just n+m variables to be solved for during simulation. Consider the following simple equation system: der(xl) = fl(xl); der(x2) = f2(x2); y = xl+x2+u;
Here we have three variables with unknown values: two dynamic variables that also are state variables, xl and x2, i.e., n=2, one output variable y, i.e., m=l, and one input variable u with known value. A consistent solution of the initial value problem providing initial values for xl, x2, der (xl) , der (xz) , and y needs to be found. Two additional initial equations thus need to be provided to solve the initialization problem. Regarding differential algebraic equation systems (DAEs, see Section 12.7.3, page 400, and Section 17.1, page 653), the situation concerning the number of equations needed for initialization is more complex than for ODEs where exactly n additional equations are required for n state variables. Here we can assert only that at most n additional equations are needed to arrive at 2n+m equations in the initialization system. The reason is that in a so-called higher index DAE problem (see 18.2.3, page 675), the number of dynamic continuous-time state variables might be less than the number of state variables n. For complex models it might be hard for the user to know how many initial equations should be added. This is especially true since a Modelica tool usually performs index reduction (see Section 18.2.4, page 679) on the equations of high index problems, thereby producing additional equations. Fortunately the Modelica environment is usually able help the user to correct a mistake by giving helpful hints, or by automatically adjusting the number of active initial equations to the desired number.
256 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
8.4.2 System Initialization Examples-Oiscrete Controller Models It is quite instructive to apply the above rules to extract initialization systems of equations from a series of similar models. Here we use models of an extremely simple industrial process coupled to a discrete-time proportional-integrating (PI) controller in four variants. To find these examples useful for illustration of initialization you need not actually understand the concept of a PI-controller. However, if you would like to read about that topic before continuing, continuous PI controllers are discussed in detail in Section 12.2.3, page 387, whereas discrete PI controllers in a Hybrid Tank system are covered in Section 13.4.1, page 460. Simple periodic sampled systems like the process control models corresponding to Figure 8-2 are described in Section 13.3.1, page 429. u
Process state: x Controller xd,k,T,Ts
x
xref
Figure 8-2. An industrialprocess with state x coupled to a discretesamplingPI controller.
In the rust model variant called ProcessControl1, the initial values are given explicitly through start values with the fixed attribute being true, giving rise to explicit initialization equations. model ProcessControl1 "Initial values given Explicitly" parameter Real k = 10, T = 1 "PI controller parameters k, T, Ts"; parameter Real Ts = 0.01 "Sample time"; Real x( fixed=true, start=2) "Process state"; input Real xref "Reference inpu.t"; discrete Real xd(fixed=true, start=O) "Controller state"; discrete Real u (fixed=true, start=O) "Process input lt ; equation II Process model: der(x) = -x + Ui II Discrete PI controller: when sample(O,Ts) then xd = pre(xd) + Ts/T*(xref-x)i u = k*{xd + xref - x); end when; end ProcessControl1;
The equations inside the when-equation are not included the initialization since the enabling condition initial () is missing. Instead the two default equations that hold when the when-equation is not active are included: xd = pre(xd)i = pre (u) ;
u
Thus the initialization system of equations becomes the following, excluding the parameters k, T, and Ts: x pre (xd) pre(u) xd
u der(x)
x.start xd.start u.start pre (xd) pre(u) -x + u
II II II II II II
2 0 0 0 0 -2
The obtained solution of the initial variable values is indicated in the comments to the right. In the second model variant, ProcessControl2, the when-equation is enabled by the presence of the ini t ial () predicate. Initial values are still given explicitly through start values.
Chapter 8 Equations 257 model ProcessContro12 "Enabled when-equation and explicit start values" "PI controller parameters k, T, Ts"; parameter Real k = 10, T = 1 parameter Real Ts = 0.01 "Sample time"; Real x( fixed=true, start=2) "Process state"; Real xref input "Reference input"; discrete Real xd(fixed=true, start=O) "Controller state"; discrete Real u (fixed=true, start=O) "Process input"; equation II Process model: der(x) = -x + u; II Discrete PI controller: when {initial(), sample(O,Ts)} then II initial() added xd = pre(xd) + Ts/T*(xref-x); u = k*(xd + xref - x); end when; end ProcessControl2;
The extracted initialization system of equations becomes as follows, with solutions at the right: x pre (xd) pre(u) xd u der (x)
x.start II 2 xd.start II = 0 u.start II = 0 pre (xd) + Ts/T*(xref-x) k*(xd + xref - x) -x + u
II II
II
0+o.Ol/1*(xref-2) = O.01*(xref-2) lO*(O.01*(xref-2)+xref-2) -2 + u
The third process control model, ProcessContro13, is similar to the second, but uses two equations in an initial equation section to define the initial values of xd and u, instead of the start value definitions we used in the previous variants. model ProcessContro13 "Enabled when-equation and initial equation section" parameter Real k = 10, T = 1 "PI controller parameters k, T, Ts"; parameter Real Ts = 0.01 "Sample time"; Real x(fixed=true, start=2) "Process state"; input Real xref "Reference input"; discrete Real xd "Controller state"; discrete Real u "Process input"; equation II Process model: der(x)
II
=
-x + U;
Discrete PI controller: when (initial(), sample (O,Ts) } then xd = pre{xd) + Ts/T*(xref-x); u = k*(xd + xref - x); end when; initial equation pre (xd) = 0; pre(u) = 0; end ProcessContro13;
The system of initialization equations from the ProcessContro13 model is almost the same as in the second variant. The only difference is the presence of the two equations from the initial equation section. x pre (xd) pre(u) xd u der(x)
x.start II 2 0 II = 0 0 II = 0 pre (xd) + Ts/T*(xref-x) k*{xd + xref - x) -x + u
II II
II
0+0.01/1* (xref-2) = O.Ol*(xref-2) lO*(O.Ol*(xref-2)+xref-2) -2 + u
In the fourth model, ProcessContro14, we give intialization constraints using the following steady-state conditions within an initial equation section:
258 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica der(x) = 0 pre (xd) = xd
These conditions imply that the system should be in a state where the state variables x and xd do not change with time, i.e., steady-state. model ProcessControl4 "Enabled when-equation and steady state init" parameter Real k = 10, T = 1 "PI controller parameters k, T, Ts"; par~eter Real Ts = 0.01 "Sample time"; Real x(start=2) "Process state"; input Real xref "Reference input"; discrete Real xd "Controller state"; discrete Real u "Process input"; equation II Process model: der(x) = -x + U; II Discrete PI controller: when sample(O,Ts) then; xd = pre(xd) + TsjT*(xref-x); u = k*(xd + xref -x); end when initial equation der(x) = 0; II Steady state condition pre (xd) = xd; end ProcessContro14;
The obtained system of when-equations for initializationis as follows: der(x) pre (xd) xd u der(x)
0
xd pre (xd) + Ts/T*(xref-x) k*(xd + xref - x) -x + u
The stationary initialization system is a linear system of equations in the following unknowns: der(x), xd, pre (xd) , u,
and
x.
Simplifying by using
x
0 xref
xd pre (xd)
xref xref/k xd
der (x) u
der (x)
=0, pre (xd) =xd, and O=-X+U, we obtain:
By using the numerical values k=lO and the guess value x , start=2 we obtain xref=2, xd=2/10, which when substitutedgives a consistent stationarysolution of the initializationproblem: 0
der(x) x
2
u
2
xd pre (xd)
0.2 0.2
8.5 Partial Differential Equations14 Before reading this section you should be aware of that this presents Modelica design work in progress. There is a new Modelica construct mentioned in this section that is not part of standard Modelica. Consult the book web page for the current status, since this preliminarydesign of PDEs in Modelica may change. 14 This section describes a generalized in operator that at the time of this writing is not yet formally accepted in the Modelica language specification. See the book web page www .DrModelica.org for future updates.
Chapter 8 Equations 259 The kind of equations that can be directly represented in MOOeHca models in the current version of the language are hybrid differential algebraic equations, hybrid DAEs (see Chapter 17, page 653), containing algebraic relations and differential equations with time derivatives that might be conditionally active. The quantities in such models are just functions of time, and do not vary depending on spatial position. On the other hand, many physical phenomena are dependent on quantities that are physically distributed and therefore functions of spatial coordinates. Typical examples of such quantities are temperature distributions in a material, electromagnetic field strength, material density, tension, etc. In fact, the kind of variables that have no spatial variation are typically approximations of distributed real variables, e.g. by computing the mean value of the quantity over some region. Equations expressing relations involving variations of quantities over spatial coordinates, e.g. x and y, usually involve derivatives with respect to those coordinates, so-called partial derivatives. Systems of equations including both partial differential equations and hybrid DAEs can be denoted hybrid PDAEs or even HPDAEs. Partial derivatives of both space variables and time appear in the heat flow equation (8-2) below: (x,y)e
n
(8-2)
Here the quantity u, denoting the temperature at the position {x,y} in the material, is a dependent variable being a function of the time t and the independent 2D spatial coordinate variables x and y, i.e., u(t, x, y). Such a function defined over a certain region is called afield. The quantities c and f are constant model parameters in the following models but could also be functions of x and y. The derivatives occurring in the equation include a time derivative, dU Idt, and two 2 2 2 2 uI and u lay with respect to the independent space variables x second-order partial deri vatives and y of the field. By introducing the pder () partial differentiation operator as an ordinary user-defined function, partial derivatives can be represented in Modelica according to Table 6-1. Using this notation, equation (8-2) will appear as follows:
a ax
a
der(u)-c*(pder(u,D.x2)+pder(u,D.y2»
= f
au ax
Ideally, we would have liked a Modelica notation such as pder (u , x, 1) and pder (u , x, 2) for I 2 and ul iJx 2 , respectively. Since this is not possible in the current Modelica language, we instead use pder(u,D.x) and pder(u,D.x2) or pder(u,x=l) and pder(u,x=2), which come quite close in
a
terms of notation.
Table 8-1. Partial differentiation operators applied to the 20 field u up to the second degree. Since a notation such as pder (u, x, 2) cannot be realized in the current Modelica language, we use pder (u , D. xz ) or pder (u, x=2) instead. The first representation is used here, and the second in Section 8.5.4.
Operator au/ax a 2u / iJx 2 du/iJy 2 u l iJy 2
'-.
Modelica Representation 1
Modelica Representation2
pder(u,D.x)
pder(u,x=l)
pder{u,D.x2)
pder(u,x=2)
a
pder(u,D.y)
pder(u,y=l)
pder(u,D.y2)
pder(u,y=2)
iJ 2uldxiJy
pder(u,D.xy)
pder(u,x=l,y=l)
au/at
der(u) or pder(u,D.t)
der(u)
-
In the first pder () representation we use literal constants from D=enumeration (x, x2, y, y2, xy, t ) to indicate the order and variable for differentiation. In the second variant, used in Section 8.5.4, the function pder tfieldname, x, y) lets the two integer formal parameters x and y specify the differentiation order of the derivative with regards to the first and second independent space variable x and y of the field u. The formal parameters to pder () should have the same names as the independentspace variables of the field.
260 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Equation (8-2) holds on a region with some geometric shape. Such a region is called the domain of the PDE problem. In the 2-dimensional heat flow problem depicted in Figure 8-3 the domain has rectangular shape.
Figure 8-3. A PDE defined on the rectangular domain {l, i.e., a rectangular geometry for the region where the PDE is defined, with insulated boundaries at the top and bottom, a poorly insulated boundary to the left, and a conducting boundary to the right. The POE refers to the temperature field u(time,x,y) and c, q, h,f, and Text. which in this example are constant parameters, but in general could be functions of x and y. Heat flows from right to left since the external temperature Text is only 20°C, i.e., cooler than the right boundary. In Figure 8-3 we observe that certain equations, so called boundary conditions, apply at the four different boundary segments of the domain. The top and bottom boundaries are insulated, i.e., there is no heat flow through the boundaries, and OU /oy = The right boundary is conducting. It keeps a fixed temperature u =50°C at the boundary. The left boundary is poorly insulated and therefore allows some heat leakage through the boundary, since the external temperature Text has the lower value 20°C compared to the 50°C of the right boundary. We should also mention that equation (8-2) can be stated somewhat more compactly using the gradient ( V) and divergence ( V·) differential operators defined in (8-3) below:
o.
au at
in
--V·(cVu)=f
o
(8-3)
This equation can be represented in Modelica using the functions gradient () and divergence ( ) : der(u) - divergence(c*gradient(u») = f
in
Omega;
Here we have used the 20 vector definitions of the gradient and divergence differential operators:
v == (a/a a/dyx)
.
gradient
v· == (a/iJx iJ/iJy)
divergence
(8-4)
8.5.1 Structuring a POE Problem After the introductory example in the previous section we are now ready to define the structure of a POE problem in general. We have a result to be computed based certain problem elements: •
Compute afield-Le., a function of time and the independent (spatial) coordinates, returning a real number-a scalar field, or multiple real numbers--e.g. a vector field.
•
The field computation is based on the following POE problem elements: 1. A partial differential equation (POE).
Chapter 8 Equations 261
--------------------------------..;~-
2. A domain, i.e., the region on which interiorthe PDE is defined. 3. Boundary conditions, defined on the boundary of the domain. 4. Initial conditions. Our PDE heat diffusion problem on a rectangular domain, previously depicted in Figure 8-3, can be formulated as follows according to this structure:
•
Field: u(t, x, y) to be solved for.
•
PDE:
•
A domain
•
Boundary conditions:
2
2
dx
iJy 2
au _c(a u + au)=f 2
at
n, in this case the interior of a rectangle: dU
c dX = q + h(Text
left: right:
-
u)
u=50
au =0 ay au =0 ay
top: bottom:
•
(x, y) e
Initial condition: u(t,x, y) = 0
Qinterior
(0 < x < Lx' 0 < y < L y ) .
x=o x=Lx y=Ly y=o
t =0, (X,y)E Q
The obvious question is how such a problem could be expressed in Modelica. We will first show the boundary conditions: c*pder(u,D.x) u = 50;
pder(u,D.y) pder(u,D.y)
=q
+ h*(T_ext - u);
= 0;
= 0;
II II II II
left right top bottom
In the next section we tum to the problem of how to represent the geometry information of the domain as well as the field itself. We will include the boundaries in the full domain representation, since both boundaries and the interior then can be extracted by simple subset operations. The main PDE equation is however only applied at the interior of the domain as it should be.
8.5.1.1
Basic Definitions of Domain, Field, Boundary, and Interior
We recapitulate some definitions: • •
• •
Domain-region (with some geometry) on which the whole PDE problem is defined. Field-function of time (except for stationary problems) and independent spatial variables. This function is the desired solution to the POE problem. Boundary-subset of the domain (usually with one dimension less than the domain) on which the boundary conditions are defined. Interior-subset of the domain on which the "main PDE" is defined.
It is desirable to have a general approach for constructing domains, applicable to 1D, 2D, or 3D regions, with one, two, or three independent spatial variables respectively. A domain is a geometrical object that can be constructed in various ways. For example: •
Defining a domain from a mesh data structure, e.g. created by some external tool.
262 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica •
Defining a domain using a discrete grid (i.e., array) representation- where a set of points on the grid belong to the domain.
•
Defining a domain as the region enclosed by two points (the 10 case), by a parametric curve (the 2D case), or a parametric surface (the 3D case). If we want to specify both the interior points and the boundaries, a parametric function with 1, 2, or 3 arguments, for the ID, 2D, or 3D cases respectively, can be used to generate all points in the interior or on the boundary. The geometric shape of a domain often needs a composition of several parts or segments to be completely defined.
The first approach is typically used by finite-element method (FEM) tools that solve PDE problems on domains represented by meshes usually consisting of triangles (2D, see Figure 8-9, page 270) or pyramidal shapes (3D). The second approach is commonly used by tools and solution schemes based on finite difference POE solution methods, shown in several of the following examples. The third approach is often used when domains have simple shapes that are easy to describe mathematically, e.g. lines, rectangles, circles, cubes, spheres, etc., or regions consisting of a combination of those. It is also used when high-accuracy scalable (to arbitrary resolution) domain definitions are needed, e.g. in high resolution 3D graphics. Arbitrary scalable shapes can be described by parametric spline polynomials (called Nurbs in the OpenGL graphic standard). When needed, grids or meshes can be generated automatically based on parametric function domain definitions, and discretization parameters. We should emphasize that our final goal is to allow the definition of domains and fields in Modelica models to be completely independent of low level implementation details such as grids or meshes, even though this is only partially (or not at all) realized for the examples in the following.
•
8.5.1.2
The Method of Lines Approach to Spatial Discretization
In the so-called method of lines the PDE equations and boundary conditions are discretized on a grid over the independent spatial variables, but not over the independent time variable. Thus each remaining variable is a function of time only: •
All partial deri vates are expanded and approximated by sets of algebraic equations and differential equations at discrete points in space, yielding a set of DAEs that usually can be solved (for wellposed problems) using the current Modelica language.
See also the discretization example with a POE solution for pressure distribution in 1D ducts described in Section 15.9, page 584, as another example of using the method of lines. As an example, regard the boundary condition at the bottom of the rectangular region previously shown in Figure 8-3:
y=o
(8-5)
We would like to solve the PDE problem described in Section 8.5.1, e.g. by discretizing the domain and the equations on a grid as shown in Figure 8-4. The boundary condition (8-5) can be discretized along the bottom boundary, by expressing the condition at several discrete points (u is still time-dependent, but not shown in the formulas):
au(x=x.) =0
dy
,
(8-6)
Chapter 8 Equations 263
UI,1
x=Lx
top
x=O 0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
x=O
0
bottom nx=9
u...
Uax.1
Figure 8-4. DomainRectangle2D is a rectangular domain spanned by rect2Dfunc. We also show a grid discretization with nX=9, ny=7, on which a field containing zeroes is defined. The elements UH, U12, and Unx.l of the discretizedfield represented as a matrix are specially marked.The boundary elements of the grid are shown in grey color. The derivatives in (8-6) can for example be approximated using the following simple first order differences: U 22 -U21
f1y
=0
u1U.2 -unx,l ,
=0
(8-7)
f!.y
where for example U l 2 - u) 1 is the field value difference between the two vertically adjacent elements at the lower left comer, and 6.y is the difference in y-coordinate between those elements. The resulting variables U 11' U)2 , ••• in equation (8-7) are all functions of time, as is it should be using the method of lines. One should be aware of the fact that numerical stability problems can occur for certain combinations of PDEs, boundary conditions, step sizes, and numerical approximation method. Consult the literature concerning relevant results for the method-of-lines. However, lD PDEs have already been used successfully in Modelica libraries sinee several years, e.g. in the ThermoFluid library (Section 16.11, page 646), using method-of-lines approximations similar in style to the example in Section 15.9, page 584. The ID problem formulations shown here look much nicer, but expands to the same kind of discretized equations.
8.5.1.3
Range and Domain Geometry Types and Generalized in Operator
We will need range types that are used in the following models to represent parameter ranges of arguments to shape functions that define the boundary (and interior) points of a domain. type RangelD Real [2] type Range2D = Real[2,2]
"Defines ID ranges {{Xl,x2}}"j "Defines 2D ranges {{xl,x2},{yl,y2}}"i type Range3D = Real[3,21 "Defines 3D ranges {{xl,x2},{yl,y2},{zl,z2}}"i
The following unspecified types represent the data structures used for discretized domains (e.g. meshes or grids) in I, 2, and 3 dimensions respectively. type DomainGelD type DomainGe2D type DomainGe3D
"Domain Geometry representation for ID domains"; "Domain Geometry representation for 2D domains"; "Domain Geometry representation for 3D domains";
We also need a generalized in operator to express that an equation holds on a domain or on a subset of a domain. For example, the equation below holds on omega. interior which is a subset of omega: der(u)
= pder(u,D.x2)+
pdBr(u,D.y2)
in omega.interior;
264 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica 8.5.1.4
Summary of Operators and Types Needed for POEs in Modelica
We have in the preceeding sections introduced several operators and types needed for POE representation in ModeIica, and demonstrated their application to a 2D heat diffusion problem on a rectangular domain. It can be useful to summarize the needed features (Table 8-2): Table 8-2. Operators and data structures,their usage and realization for PDEs in Modelica.
Operators and Data structures
Usage
Modelica Realization
pder ()
Partial den vatives.
User defined Modelica function with inline semantics.
Generalized in operator
Mathematical styIe syntax for expressing on which domain or part of a domain a PDE or boundary condition applies to.
Language extension needed.
Grid functions
Grid or mesh dependent alternative to the in operator for expressing on which domain or part of a domain a PDE or boundary condition applies to.
User defined Modelica functions with inline semantics.
Domain data structures
Geometry of region or boundaries on which a PDE problem is defined.
Record or array data structure.
Field data structure
Representation of the solution to the POE problem as a "function" of independent spatial variables and time.
Record or array data structure.
Shape functions
Define the geometry of a domain with boundaries in a way that is independent of low-level grid or mesh approximations.
User defined Modelica functions.
Note that inline semantics is needed for the pder () function and the grid functions. This means that the functions compute results in exactly the same way as any Modelica function, but is expanded inline, i.e., the function call is replaced by the returned expression. This makes it possible to put calls to such a function at places where function calls are usually not allowed. Some Modelica environments support inline semantics for functions where the function body is a single assignment with the inlined expression as its right hand side.
8.5.2 Modelica POE Examples of Domains, Fields, and Models in 10, 20, and 3D In the following four subsections we will show partial examples of PDE problem definitions in Modelica for 20, 10, 20, and 3D problems respectively. We start with our familiar heat diffusion problem on a rectangular domain.
8.5.2.1
Modelica Heat Diffusion Madelon a Rectangular Domain
We are now ready to formulate a Modelica model of the heat diffusion POE problem described in Section 8.5.1, page260, and in Figure 8-3. The model instantiates a domain omega and a field u defined on this domain. The domain and field have the types DomainRectangle2D and FieldRectangle20, respectively. model HeatRectangle2D
Chapter8 Equations 265 import SI= Modelica.SIunits; replaceable package DifferentialOperators DifferentialOperators2D; import DifferentialOperators.pder; parameter Integer nx = 50, ny = 50; parameter Real Lx = 2, Ly = 1; parameter DomainRectangle2D omega (nx=nx, ny=ny, Lx=Lx, Ly=Ly, FieldValueType=SI.Temperature) : parameter Real C Ii parameter Real q 1; parameter Real h 1; parameter Real Text = 20 "External temperature"; FieldRectangle2D u(domain=omega) ; equation der(u) = pder(u,D.x2)+ pder(u,D.y2) in omega. interior; in omega. left; c*pder(u,D.x) = q + h*(T_ext-u); in omega.right; u = 50; pder(u,D.y} = 0; in omega. top; in omega.bottom; pder(u,D.y) = 0; end HeatRectangle2D; The model is still incomplete since the package DifferentialOperators2D is not yet available, (one operator is however shown in Section 8.5.4.1, page 273), and the record GeomRect for shape parameters is not declared. The domain type DomainRectangle2D for rectangular geometries can be defined as a record: record DomainRectangle~D parameter Integer nx = 50, ny = 50; parameter Real Lx = 2, Ly = 1; replaceable function shapeFunc = rect2Dfunc; replaceable record Ge = GeomRect "Record with rect geometry information"; DomainGe2D bottom(shape=shapeFunc,range={{O,Lx},{O,O}}, geom=Ge(nx,ny,Lx,Ly» ; DomainGe2D right( shape=shapeFunc, range={{Lx,Lx},{O,Ly}}, geom=Ge(nx,ny,Lx,Ly»; DomainGe2D top( shape=shapeFunc, range={{O,Lx},{Ly,Ly}}, geom=Ge(nx,ny,Lx,Ly») ; DomainGe2D left( shape=shapeFunc, range={{O,O},{O,Ly}}, geom=Ge(nx,ny,Lx,Ly) ; DomainGe2D interior (shape=shapeFunc, range={{O,Lx},{O,Ly}}, geom=Ge(nx,ny,Lx,Ly}); end DomainRectangle2D; The boundaries as well as the interior are represented by instances of the DomainGe2D data structure. The parametric shape function returning {x, y} can generate all points in the domain or in subsets of the domain such as the interior and the boundary segments bottom, right, top, and left, by letting the inputs vary over the specified ranges for the function arguments v I and v2. In this case the shape function is the trivial identity function rect2Dfunc, but in other cases the mapping can be nontrivial. function rect2Dfunc "2D Identity function to span rectangular region" input Real v1, v2; output Real x .- vI; output Real y .- v2: algorithm end rect2Dfunc; Finally we define the field type FieldRectangle2D used for the field u in the above HeatRectangle2D model. The actual field values, being subtypes of Real, are stored in the val attribute, here a matrix. The field is initially zero over the whole domain. record FieldRectangle2D parameter DomainRectangle2D domain;
266 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica replaceable type FieldValueType = Real; replaceable type FieldType = FieldValueType[domain.nx,domain.ny]; parameter FieldType start = zeros(domain.nx,domain.ny); FieldType val; II Actual field values end FieldRectangle2D;
In the following three sections we will show simple examples of a heat diffusion models with temperature fields defined on ID, 2D, and 3D domains respectively. We also assume that the following import statement is present for these models.: import SI = Modelica.S1units;
For simplicity we use grid representations of the domains in these examples. However, other data structures could be used. For example, the 2D and 3D models could instead be formulated based on an external mesh representation.
8.5.2.2
One-dimensional Domains
A ID domain is can be specified by its length, e.g. as depicted in Figure 8-5. () Length L
left
right
Figure 8-5. DomainLinelD can be used for one-dimensional domains like rods. The domain data structure DomainLinelD is defined using a shape function over a range, but in this case specialized to a grid representation. An instance rod with length L=2, and nx=lOO discretization intervals is declared: DomainLinelD rod(L=2, nx=lOO);
The heat diffusion PDE with boundary conditions can be stated in the following way:
au a2u at= ax 2
u = 20sin(1l'· t /12) + 300
au =0
ax
XE 0interior
XE illelt
(8-8)
XE aright
The corresponding Modelica heat diffusion model is defined on the tD line geometry of a rod, where we use rod instead of omega for the domain name: model HeatLinelD import DifferentialOperatorslD.pder; parameter DomainLinelDGrid rod; FieldLinelDGrid u(domain=rod, FieldValueType=SI.Temperature)i equation der(u) = pder(u,D.x2) in rod. interior; in rod. left; u = 20*sin(PI*time/12)+300 in rod. right; pder(u,D.x) = 0 end HeatLinelD;
The Modelica model DomainLinelDGrid with interior and two boundaries left and right: record DomainLinelDGrid "Domain being a line segment region" parameter 5I.Length L = 1; parameter Integer nx = 100; replaceable function shapeFunc linelDfunc "Span 1D line region"; replaceable record Ge = GeomLine "Record with geometry information"i
Chapter 8 Equations 267
DomainGelD interior(shape=shapeFunc,range={{O,L}},geom=Ge(nx,L»; DomainGelD left(shape=shapeFunc,range=t{O,O}},geom~Ge(nx,L»; DomainGelD right(shape=shapeFunc,range={{L,L}},geom=Ge(nx,L»; end DomainLinelDGrid; The trivial identity parametric function that spans a line region: function linelDfunc "ID identity function to span line region" input Real Vi output Real x .- Vi algorithm end linelDfunci
The field FieldLinelDGrid with a grid representation (a vector) of the field values: record FieldLinelDGrid parameter DomainLinelDGrid domain(L=l, nx=lOO); replaceable type FieldValueType = Real; replaceable type FieldType = FieldValueType[domain.nx]; parameter FieldType start = zeros (domain.nx) ; FieldType val; II Actual field values end FieldLinelDGrid;
8.5.2.3
Two-dimensional Domains
Two-dimensional domains have two independent spatial variables, e.g. x and y if Cartesian coordinates are used. A simple 20 domain is the circular region depicted in Figure 8-6. Mapping to polar coordinates would have been natural in this special case. However, here we just want to illustrate the shape function approach using a simple 2D domain, and keep the Cartesian coordinates for simplicity.
x
Figure 8-6. DomainCircular2D domain spanned by the shape function circular2Dfunc. The normal vector n of the boundary is used for the normal vector derivative operator nder ().
We state the two-dimensional version of the heat diffusion equation, with the boundary condition expressed as the partial derivative along the normal vector n perpendicular to the boundary:
a2 u a2 u at ax ay 2 au =0 au
- = -2 + -
an
(x, y)
E Qinterior
(8-9) (x, y)
e
nboundary
This problem can be specified in a model, using the operators pder () and nder () imported from the package DifferentialOperators2D: model HeatCircular2D import DifferentialOperators2D.*i parameter DomainCircular2DGrid omega; FieldCircular2DGrid u(domain=omega, FieldValueType=SI.Temperature) i equation der(u) = pder(u,D.x2)+ pder(u,D.y2) in omega. interior; nder(u) = 0 in omega.boundary; end HeatCircular2D;
268 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica The shape of the circular domain is defined by a general parametric shape function circular2Dfunc. This selects a circular subset of the grid representation of the domain. record DomainCircular2DGrid "Domain being a circular region" parameter Real radius 1; parameter Integer nx 100; parameter Integer ny 100; replaceable function shapeFunc = circular2Dfunc "2D circular region"; DomainGe2D interior(shape=shapeFunc,range={{O,radius},{O,l}},geom=... )i DomainGe2D boundary(shape=shapeFunc,range={{radius,radius},{O,l}},geom=); function shapeFunc = circular2Dfunc "Function spanning circular region"; end DomainCircular2DGrid;
The parametric shape function spanning a circular region: function circular2Dfunc input Real r,v; output Real x,y; algorithm x := r*cos(2*PI*v); y := r*sin(2*PI*v); end circular2Dfunc;
"Spanned circular region for v in range 0 .. 1"
Finally we declare the field type using a grid representation of values on the circular domain. Note that we are not using polar coordinates in this particular grid example. record FieldCircular2DGrid parameter DomainCircular2DGrid domain; replaceable type FieldValueType = Real; replaceable type FieldType = Real[domain.nx,domain.ny,domain.nz]; parameter FieldType start = zeros(domain.nx,domain.ny,domain.nz); FieldType val; II Actual field values end FieldCircular2DGrid;
8.5.2.4
Three-dimensional Domains
The third example illustrates the heat diffusion problem on a three-dimensional domain. We choose a spherical domain for simplicity, but keep Cartesian coordinates instead of switching to spherical coordinates, since this shape could be replaced by a shape with more complicated geometry.
Figure 8-7. The spherical DomainSphere3D domain is spanned by the shape function shere3Dfunc. The normal vector n of the boundary is used to define the normal vector derivative operator nder (). The PDE is similar to the 2D case, but with three partial derivative since there are three independent spatial variables of this domain:
Chapter 8 Equations 269
(x, y, z) E
Qinterior
(8-10) (x, y, Z) E
n boundary
The 3D heat diffusion problem in a sphere expressed in the HeatSphere3D Modelica model:
model HeatSphere3D import DifferentialOperators3D.*; parameter DomainSpherical~DGrid omega; FieldSphere3DGrid u(domain=omega, FieldValueType=SI.Temperature); equation in omega. interior; der(u) = pder(u,D.x2)+pder(u,D.y2)+pder(u,D.z2) in omega.boundary; nder(u) = 0 end HeatSphere3D;
The interior and boundary parts of the spherical domain are characterized as follows: • •
Interior: 0 ~ r < radius Boundary: r = radius
The corresponding domain type declaration: record DomainSphere3DGrid "Domain spanning a sphere, with grid parameters" parameter Real radius = 1; parameter Real nx 100; II Gives x discretization, for fields on grid parameter Real ny 100; II Gives y discretization, for fields on grid parameter Real nz 100; II Gives z discretization, for fields on grid function shapeFunc = Sphere3Dfunc "Function spanning the sphere"; DomainGe3D interior (shape=shapeFunc, {{O,radius}, {O,1},{O,1}},geom= •.• ); DomainGe3D boundary {shape=shapeFunc, {{radius,radius}, {O,l},{O,l}} ,geom=); end DomainSphere3DGridi
arid the parametric shape function spanning the spherical domain: function Sphere3Dfunc "Span a Sphere for u,v in range 0 .. 1, r in input Real r,U,Vi output Real x,y,z; algorithm x .- r*sin(2*PI*v}*cos{2*PI*u); y := r*sin(2*PI*v)*sin(2*PI*u); z := r*cos(2*PI*v); end Sphere3Dfunc;
o.. R"
Finally we declare the field on the spherical domain as a Modelica data structure, using a grid representation of the field data: record FieidSphere3DGrid "Field on a Sphere with Cartesian grid" parameter DomainSphere3DGrid domain; replaceable type FieldValueType = Real; replaceable type FieldType=FieldValueType[domain.nx,domain.ny,domain.nz]; parameter FieldType start=zeros(domain.nx,domain.ny,domain.nz); FieldType val; II Actual field values end FieldSphere3DGrid;
270 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
8.5.3 A POE on a 20 Domain with General Shape and FEM Solution Many realistic domains have more complicated shapes (see Figure 8-8) than the simple lines, circles, spheres, rectangles, etc., presented in the previous sections. Such shapes are usually specified by a mesh in two or three dimensions (e.g. left of Figure 8-9) that has been created by a special mesh generating tool.
Poorlyinsulated boundary Ter.' =20·
Figure 8-8. Heat diffusion problem on a 2D domain with complicated geometry, and boundary sections which are insulated, poorly insulated, or conducting.
The heat diffusion problem has been modeled in a PDE extension of Modelica similar to the approach outlined in the previous sections, but with an external mesh defining the geometry. An external PDE solver using the finite element method (FEM) was employed to produce the solution depicted Figure 8-9 (right). 58.4 56 53.5 512 48.8 46.4 44
41.&
392
36.8 34.4 3Z
-1
29.6
Z72 Z4.8
ZZ.4
20
-4
-3
-z
-1
Figure 8-9. Solution of a 2D heat flow problem specified in a PDE extension of Modelica on a domain with complicated shape. The shape is defined by an external mesh (left). The problem is solved using a version of the finite element method (FEM). The solution is shown to the right.
8.5.4 Grid Function Finite Difference Approach to 10 Heat Diffusion In the previous Modelica PDE examples we have relied on an extension of the in operator in Modelica to express which part of the domain an equation applies to (here using the second pder () representation in Table 8-1), e.g.:
= pder(u,x=2)
in
rod. interior;
= 20*sin(PI*time/12)+300
in in
rod. left;
der(u) u
pder(u,x=l) = 0
rod. right;
Another approach is to use so-called grid functions, common in many finite difference packages. A grid function applies some operation to a field defined on a grid, including arithmetic operations and selection operations such as left, right, or interior, that return part of a field. Using grid functions, the above equations can be expressed as follows:
Chapter 8 Equations 271 interior(der(u.val)) = interior(4*pder(u.val,x=2)); left(u.val) = 20*sin(PI/12*time) + 300; right(pder(u.val,x=l)) = 0;
Herewe need to use u . val instead of u, since the der () operatorcurrently is not defined for records. The use of overloaded function and operator definitions (Section 9.5, page 322) would remove that restriction. The whole model appears as follows, and can be executed in ordinary Modelica with just a slight extension such as function inlining: model HeatDiffusionlD import S1=Modelica.S1units; parameter 51.Length L=l; import Fields.*; import Domains.*; import FieldDomainOperatorslD.*; import DifferentialOperatorslD.*; constant Real PI=Modelica.Constants.Pl; DomainlD rod(left=O, right=L, n=50); FieldlD u(domain=rod, redeclare type FieldValueType SI.Temperature, start={20*sin(P1/2*x) + 300 for x in rod.x}); equation interior(der(u.val» = interior(4*pder(u,x=2i); left(u.val) = 20*sin(PI/12*time> + 300; right(pder(u,x=I» = 0; end HeatDiffusionlD;
The drawback is that part of the model has to be formulated in terms of the grid, and therefore is dependent on the domain and field data structures. The grid functions left, right, and interior for field selection on the grid, are defined below: package FieldDomainOperatorslD
"Selection operators of field on ID domain"
function left "Returns the left value of the field vector vI" input Real[:l vI; output Real v2; algorithm v2:= v l Ll l , end left; function right "Returns the right value of the field vectcr vI" input Real[:] vI; output Real v2; algorithm v2 : = v l [end l.r end right; function interior "Returns the interior values of the field as a vector" input Real vI[:]; output Real v2[size(vl,I)-2]; algorithm v2 := v1[2:end - 1]; end interior; end FieldDomainOperatorslD;
The domain and field definitions: package Domains import S1 = Modelica.Slunits; record DomainlD "ID spatial domain" parameter SI.Length left=O.O; parameter SI.Length right=l.O;
272 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica parameter Integer n=100; parameter 51.Length dx (right-left) I (n-l) ; parameter 51.Length x[n] = linspace{right, left, n); end Domain1D; end Domains; package Fields record Field1D "Field over a 1D spatial domain" replaceable type FieldValueType = Real; parameter Domains.Domain1D domain; parameter FieldValueType start [domain.n] = zeros (domain.n) ; FieldValueType val [domain.n] (start=start); end Field1D; end Fields;
The differential operators for numerical approximations to the partial derivatives. Both first and secondorder versions are available: package DifferentialOperatorslD
"Finite Difference differential operators"
function pder "Returns vector of spatial derivative values of a 1D field" input Fields.Field1D f; input Integer x=1 "Diff order - first or second derivative"; output Real df[size{f.val, 1)]; algorithm df := if x 1 then SecondOrder.diffl{f.val, f.domain.dx) else SecondOrder.diff2(f.val, f.domain.dx); end pder; package FirstOrder
"First order polynomial derivative approximations"
function diffl "First derivative" input Real u[:] ; input Real dx; output Real du[size(u,1)] ; algorithm II Left, central, and right differences du : = cat (1, {(u [2] - u [1] ) /dx}, (u [3 : end] - u [1: end-iz l ) /2/dx, { (u [end] - u [end-l] ) /dx}) ; end diffl; end FirstOrder; package SecondOrder
"Second order polynomial derivative approximations"
function diff1 "First derivative" input Real u[:]; input Real dx; output Real du[size(u,1)]; algorithm du : = cat (1 , {( - 3*u [l] + 4*u [2] - u [3] ) 12/ dx }, (u[3:end]- u[l:end-2])/2/dx, {(3*u[end] - 4*u[end-l] + u[end-2])/2/dx} ); end diffl; function diff2 "Second derivative" input Real u[:]; input Real dx; output Real du2[size(u,l)]; algorithm du2 : = cat (l , {( 2 *u [1] - 5 *u [2] + 4*u [3] - u [ 4] ) / dx/dx }, (u[3:end] - 2*u[2:end-11 + u[1:end-2])/dx/dx, { (2*u [end] - S*u [end-l] + 4*u [end-2l - u [end-3] ) /dx/dx} ); end diff2; end SecondOrder; end DifferentialOperatorslD;
Chapter 8 Equations 273
We simulate and plot the HeatOiffusionlO model using the Mathematica command mode available for MathModelica. The plot of the temperature profile is as follows at the 4th grid point (i.e. x=O. 08). Simulate [HeatDiffusionlD, {t,O,l}J ; PlotSimulation [u. val [ [4] ] rer. {t, 0, 1}] 320.0 317.5 315.0 312.5 310.0 307.5 302.5
0.2
0.4
1
t
Figure 8-10. Plot of the temperature field u at 4th grid point for the HeatDiffusionlD model.
By forming an interpolated polynomial from the matrix representation of the solution, we can create a continuous 3D-plot of the solution as a function of both x and time, as depicted in Figure 8-11. intp=Interpolation[ Flatten [Table ({ k, t, u. val [ [k] ] [t] ) , {k, I, 50, 1} , {t, 0, 1, O.1}] , 1] ] ; Plot3D[intp[x,t] ,{x,1,50},{t,0,1},PlotPoints->30, AxesLabel->{"x","t","u(x,t)"},ViewPoint->{-4,2.4,2}] 50
0.25
o. s f).7S
Figure 8-11. The temperature distribution field of the rod as a function of time and the spatial x coordinate-a solution to the HeatDiffusionlD problem.
8.5.4.1
20 Grid Functions
The grid function approach to modeling PDEs can of course be generalized to grids in 2 and 3 dimensions, grids for polar coordinates, etc. As an illustration, we show a 20 finite difference operator as a grid function for a 2D grid: function diff22D "Second order finite difference operator on 2D grid" input Real u(:,:] i input Real dxi output Real du2(size(u, 1), size(u, 2)]; algorithm du2 : = cat (1 , {( 2 *u [1, :] - 5*u [2, :] + 4 *u [3, : ) - U [ 4, : ] ) / dx/dx ] , (u(3:end,:] - 2*u(2:end-l, r l + u[1:end-2, :])/dx/dx, { (2*u [end, :] - 5*u [end-I, :] + 4*u [end-2, :] - u [end-3, : J ) /dx/dx}) ; end diff22D;
274 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica
8.6 Equation Operators for Overconstrained Connection-Based Equation Systems There is a special problem regarding equation systems resulting from loops in connection graphs where the connectors contain nonflow (i.e., potential) variables dependent on each other. When a loop structure occurs in such a graph, the resulting equation system will be overconstrained, i.e. have more equations than variables, since there are implicit constraints between certain nonflow variables in the connector in addition to the connection equations around the loop. At the current state-of-the-art, it is not possible to automatically eliminate the unneeded equations from the resulting equation system without additional information from the model designer. The purpose of this section is to describe a set of equation operators for such overconstrained connection-based equation systems, that makes it possible for the model designer to specify enough information in the model to allow a Modelica environment to automatically remove the superfluous equations.
8.6.1 An Example of an Overconstrained Connection Loop We first take a look at the typical case of a connector containing dependent nonflow variables. For example, the Frame connector class for 3-dimensional mechanical systems defined in the Modelica multibody library (see also Section 15.10.4.1, page 592), and shown below, contains a rotation matrix R in the Frame connector class of type Orientation-basically a Real [3 , 3] matrix type. connector Frame "3-dimensional mechanical connector" import SI = Modelica.Slunits;
SI.position Orientation flow SI.Force flow SI.Torque end Frame;
r_O[3] "Vector from inertial frame to Frame"; "Rotation matrix from inertial frame to Frame"; £[3] "Cut-force resolved in Frame"; t[3] "Cut-torque resolved in Frame";
R
This matrix contains 9 elements that are nonflow variables in the connector. However, the matrix can be completely defined by 3 independent variables as shown in Section 14.8.4.2, page 507, meaning that there are 6 implicit constraint equations between the 9 variables, in addition to the 9 equation equality equations between R matrices from two connected connectors, i.e. more equations than variables of no other variables were available. Let us investigate a realistic physical example of a mechanical pendulum-like system of four connected bars in a loop, described by the model MultiBody. Examples. Loops. Fourbarl shown in Figure 8-12:
~uM2~' .e.:,-
~ 1):1'.0.01
Breaking loop here
_113 _ _ _-4---',.....
Figure 8-12. Loop in the connection graph (left) of model MultiBody. Examples. Loops. Fourbarl, (see also Section 15.10.7, page 601) with overdetermined connectors, and 3D visualization (right) of the loop structure of the mechanical mechanism. The loop can be automatically broken at the connection between bar b3 and the joint to the right in the connection graph, to eliminate superfluous equations and create a tree.
Chapter8 Equations 275 In the virtualconnection graph shown in Figure 8-13 below we have marked each connect (... ) equation with a dotted arrow, and each bar or joint with a filled arrow, indicated by the presence of a Connections. Branch () in the equation section of each bar or joint. There are basically two ways of arriving at the branch position in the loop where we have indicated that the loop dependency chain could be broken (there might also be other possible places to cut branches) to obtain the desired tree structure that would eliminate the overconstraining problems. The sequence of transformation matrices R, can be computed successively, starting at the inertial world frame root node at the lower left with R I and following the graph at the left and at the top, arriving at R t3, through a sequence of equalities at connections and via bars, and rotations by angles 2, end «functionname»;
Optional explicit default values can be associated with any input or output formal parameter through declaration assignments. Such defaults are shown for the third input parameter and the second output parameter in our example. Comment strings and annotations can be given for any formal parameter declaration, as usual in Modelica declarations. All internal parts of a function are optional; i.e., the following is also a legal function: function «functionname» end
«functionname»,
9.3.1.1
Ordering of Formal Parameters
The relative ordering between input formal parameter declarations is important since that determines the matching between actual arguments and formal parameters at function calls with positional parameter passing. Likewise, the relative ordering between the declarations of the outputs is significant since that determines the matching with receiving variables at function calls of functions with multiple results. However, the declarations of the inputs and outputs can be intermixed as long as these internal orderings
16 There is an exception to this rule for external functions called in when-equations or when-statements. See the footnote in Section 9.1, page 283.
300 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica are preserved.Mixing declarations in this way is not recommended,however, since it makes the code hard to read. For example: function output input input
«functionname» Type01 out1; TypeI1 in1; TypeI2 in2;
II II
Intermixed declarations of inputs and outputs not recommended since code becomes hard to read
output Type02 out2; input TypeI3 in3; end «functionname» i
9.3.2 Function Call There are two basic forms of argument to formal parameterassociation in Modelica function calls: • •
Positional associationof actual argumentsto formal parameters. Named associationof actual argumentsto formal parameters.
These two forms can be mixed: •
Mixed positional and named associationof actual arguments to formal parameters.
As an example we will use the function polynomialEvaluator that computes the value of a polynomial given two arguments: a coefficient vector A and a value of x. function polynomial Evaluator input Real A[:]; II Array, size defined at function call time input Real x := 1.0; II Explicit default value 1.0 for x output Real sum; protected
Real
xpower;
II
Local variable xpower
algorithm
sum := 0; xpower := 1; for i in l:size(A,l) loop sum := sum + A[i]*xpower; xpower := xpower*x; end for; end polynomialEvaluator;
Function calls with positional association of actual arguments to formal parameters is the most common form of function call in Modelica as well as in other programming languages. The actual arguments are associated with the formal parameters according to their position in the argument list. Thus, the nth actual argument is passed to the nth input formal parameter based on the ordering of the input formal parameter declarations in the function definition. However, formal parameters with default values need not be given actual arguments unless those parametersshould be assigned values different from the defaults. The number of actual arguments can be less than the number of formal parameters in such a function call if the remaining formal parameters have specified default values. Otherwise the number of actual arguments and the number of formal parameters must be the same. Using positional association, in the call below the actual argument {1, 2,3,4} becomes the value of the coefficient vector A, and 21 becomesthe value of the formal parameter x. p
:=
polynomialEvaluator({1, 2, 3, 4}, 21);
The same call to the function polynomialEvaluator can instead be made using named association of actual arguments to formal parameters,as in the next example. Here the actual argument is associated with
Chapter 9 Algorithms and Functions
301
the formal parameter through an equation in the argument list with the name of the formal parameter on the left-hand side and the actual argument on the right-hand side. p := polynomialEvaluator(A={l, 2, 3, 4}, x=21)i
Named association has the advantage that the code becomes more self-documenting as well as more flexible with respect to code updates, but the drawback is less concise code. For example, assume that we make all calls to the function polynomialEvaluator using named parameter association. Then we can change the order between the formal parameters A and x and introduce new formal parameters with default values in the function definition without causing any.compilation errors at the call sites. The default value of 1 . 0 for the x input formal parameter makes the following three calls equivalent: p .- polynomialEvaluator({l, 2, 3, 4}, 1.0); p := polynomialEvaluator({l, 2, 3, 4}; P := polynomialEvaluator(A={l, 2, 3, 4})i
For both kinds of function argument passing, type compatibility of arguments and formal parameters applies: The types of the actual argument expressions at a function call must be compatible with the declared types of the corresponding formal parameters, except where the standard type conversions can be used to make the types agree. See also Section 3.14.9 on page 107 in Chapter 3 regarding type compatibility for argument passing, and the section on applying scalar functions to arrays, Section 9.3.6 on page 309, in this chapter.
•
9.3.2.1
Mixed Positional and Named Function Argument Passing
We mentioned briefly that the positional and named argument passing styles can be mixed in a function call. The placement of the positional and named arguments must adhere to the following rule: •
A function application has optional positional arguments followed by zero or more named arguments.
Such a mixed call to some example function f might appear as follows: f(3.5, 5.76, arg3=5, arg6=8.3)
i
or in the case of our well-known polynomialEvaluator function: p := polynomialEvaluator({l, 2: 3, 4}, x=21)i
We are now ready to state the complete rules for binding values to the input formal parameters of a Modelica function based on a combination of positional arguments, named arguments, and explicitly given default values: I.
First, a list of unfilled "slots" is created corresponding to all formal input parameters, where the order of the slots is given by the order of the formal input parameter declarations in the function definition.
2. If there are n positional arguments, they are placed in the first n slots, which thereby become filled. 3.
Next, for each named argument "identifier = expression," the identifier is used to determine the corresponding slot. This slot must be unfilled, otherwise an error occurs. The value of the argument is placed in this slot, thereby filling it.
4. When all arguments have been processed, the slots that are still unfilled are filled with the corresponding explicit default values of the function definition.
5.
At this stage there must not be any remaining unfilled slots, otherwise an error occurs. The contents of the complete list of filled slots can now be used as the input formal parameter values for the call.
302 Peter Fritzson Principles of Object-OrientedModeling and Simulation with Modelica We illustrate this procedure with an example. Assume that a function realToString is defined as follows for converting a Real number to a String: function input input input output
realToString Real number "Real value to be converted to a string"; Real precision.- 6 "Number of significant digits"; Real length .- 0 "Minimum length of field"; String string "Result number as a string";
end realToString; Then the following function calls are equivalent: String ns; ns .- realToString(2.0); ns .- realToString(2.0, 6, 0); ns .- realToString(2.0, 6); ns .- realToString(2.0, precision=6); ns .- realToString(2.0, length=O); As stated in the argument passing procedure it is an error to pass the same argument twice. We show an erroneous example call below where the argument value 6 is passed twice to the precision formal parameter, first using positional association and then using named association: ns := realToString(2.0, 6, precision=6); II Error: precision passed twice
9.3.2.2
Returning Single or Multiple Function Results
A function with one output formal parameter always returns a single result. Our previously presented example functions polynomialEvaluator and realToString are single result functions. However, a function with more than one output formal parameter has multiple results. An example is the function pointOnCircle below, which computes the cartesian coordinates of a point located at a certain angle on a circle with a specific radius. The Cartesian coordinates are returned via the two result variables x and y. function pointOnCircle "Computes cartesian coordinates of a point" input Real angle "angle in radians"; input Real radius; output Real Xi II l:st result formal parameter output Real y; II 2:nd result formal parameter algorithm X := radius*Modelica.Math.cos(phi); y := radius*Modelica.Math.sin(phi); end pointOnCircle; If we call a function with just one result we can put the call anywhere within an expression. This is also the case when calling a function with multiple results if we only want to access its first result. On the other hand, if we wish to call a Modelica function with multiple results and want to obtain more than the first result, there are just two syntactic forms to choose from depending on whether the function call should occur in an equation section or in an algorithm section: one equation form and one statement form, as specified below: (outl,out2,out3, (outl,out2,out3,
) = function_name (inl, in2, in3, in4, ) := function_name {inl, in2, in3, in4,
); II Equation ); II Statement
The left-hand side of both the equation and the assignment statement contains a parenthesized, commaseparated list of variables receiving the results from the function call. A called function with n results can have at most n receiving variables on the left-hand side. Fewer than n receiving variables means that some function results are discarded.
Chapter 9 Algorithms and Functions 303 For example, when calling our example function pointOnCircle with two receiving variables px and py on the left-hand side, such calls can appear as follows:
(px,py) (px,py)
=
pointOnCircle(1.2, 2); 2);
:= pointOnCircle(1.2,
II II
Equation form Statement form
Any kind of variable of compatible type is allowed in the list on the left-hand side, e.g. array elements: (arr [1] ,arr [2])
: = pointOnCircle (1.2, 2);
However, the parenthesized list on the left-hand side must contain variables, not general expressions: (a+3, h/c>
:=
pointOnCircle(1.2, 2); II Error! Should be variables lion the left-hand side
To summarize, the following rules apply when returning results from a multiple-result function: The variables in the list on the left-hand side of the equation or assignment containing the call are associated with the returned function results according to the order of the variables in the list and the corresponding declaration order of the output result variables in the function. As in any standard equation or assignment, the type of each variable on the left-hand side must be compatible with the type of the corresponding function result on the right-hand side, with or without type coercion.
•
•
9.3.2.3
Optional Function Results
In the previous section we mentioned briefly that selected results from a multiple-result function can be discarded depending on the form of the function call. This is useful since we might not always be interested in all results returned from a function call. By leaving out variables in the comma-separated list on the left-hand side of a multiple-result call equation or assignment, or calling a multiple-result function within an expression context, we can control which results are actually obtained according to the following rules: •
A multiple-result function can be called as a single-result function within an expression. In such a case the value and type of the function call are given by the value and type of the first result, and the rest of the results are discarded.
•
Selected function results can be discarded by leaving out the corresponding variables in the comma-separated list on the left-hand side of multiple-result function call equation or assignment. Enough commas must be retained to determine the position of each variable, counting from the left.
A typical case is the following example function eigen, which computes both eigenvalues and eigenvectors, whereas the user would like to obtain only one or two of these results. function eigen "calculate eigenvalues and eigenvectors" parameter Integer n = size(A,I); input Real A[:,n] i output Real eigenValues [n,2] ; II 1st result output Real leftEigenVectors [n,n]; II 2nd result output Real rightEigenVectors[n,nJ; II 3rd result algorithm II compute eigenvalues, right and left eigenvectors end eigen;
This function may be called in different ways depending on which results should be returned or discarded, e.g. as in the example calls below: (evalues,vleft,vright) .- eigen(A)i (evalues,vleft) .- eigen(A)i evalues .- eigen(A);
II II II
Return all results Eigenvalues and left eigenvectors Only eigenvalues
304 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica
x .- 2*eigen{A)i II Eigenvalues in an expression (evalues"vright) .- eigen(A); II Eigenvalues and right eigenvectors (,vleft) .- eigen(A); II Only left eigenvectors You might think that it is a waste of computational resources to compute results that are just discarded. It would be better to avoid computing these results from the start, at least if the particular computations use a significant amount of computer time. For these reasons a built-in function iSPresent(ident) is available in Modelica, to check if a variable is present in the list of variables on the left-hand side to receive the result returned by the output formal parameternamed ident. For reasons of simplicity, Modelica implementations are allowed to always return true for all calls to isPresent (). However, certain high-performance implementations may choose to return false if the corresponding output result is not used. In any case, isPresent () should be used only to increase the performance of the code. It is a programming error if it influences the contents of the result values that are actually returned from the function. Below we have restructured the function eigen to make use of isPresent () : function eigen "calculate eigenvalues and eigenvectors" parameter Integer n = size(A,l)i input Real A[:,n]; output Real eigenValues [n,2] ; output Real leftEigenVectors[n,n]; output Real rightEigenVectors[n,n]; algorithm if isPresent(eigenValues) then II Compute eigenValues end if; if isPresent(leftEigenVectors) then II Compute leftEigenVectors end if; if isPresent(rightEigenVectors) then II Compute rightEigenVectors end if; end eigen;
9.3.2.4
Empty Function Calls
An."empty" function call is a call that does not return any results. An empty call is not of much use in Modelica since a function call without results does not contribute to the simulation, and is not allowed to have side-effects that influence the simulationstate. However, this degenerate case of function call is still allowed. It can occur either as a kind of "null" equation or "null" statement,e.g. as in the empty calls to eigen () in the example below: equation eigen(A); algorithm . eigen(A)i
9.3.2.5
II
Empty function call as an equation
II
Empty function call as a statement
Function return-statement
A function is returned from when reaching the end of the function body. However, immediate return from anywhere inside a function body can be done by executing a return-statementwith the following syntax: return;
For example, the following function findMatrixElement searches an Integer matrix for a specific element. The search is done by a doubly nested for-loop, which is immediatelyexited when the function is returned from by executing a return-statement. At this point the correct index position has been found and assigned to the result variables row and column.
Chapter 9 Algorithms and Functions 305
function input input output output
findMatrixElement Integer element; Integer M[:,:]; Integer column; Integer row;
algorithm for r in l:size(M,l) loop for c in 1:size(M,2) loop if M[r,k]== element then row:=ri column:=c; return; end if; end for; end for; end findMatrixElement;
9.3.2.6
Record Constructor Functions
A record constructor function is a function that creates and returns a record. For example, consider a record called Person with three fields: name, age, and chi Idren: record Person String name; Integer age; String [2] children; end Person;
We would like to have a record constructor function Person(name, age, children) returning a Person record. However, it is normally illegal in Modelica to declare a function with the same name as a record type within the same scope. If declared, it. might be something similar to the following: function Person input String name; input Integer age; input String[2] children; output Person Pi algorithm p.name := name; p.age := age; p.children := children; end Person;
Fortunately we do not need to declare a Person constructor function explicitly in Modelica since such a function is automatically defined as a byproduct of the Person record declaration. In this special case both a record and a function with the same name is allowed. The name Person is overloaded with two different meanings. The different uses of the Person record type name and the Personfunction name can be distinguished since the first is used in a type context and the second in a function call context. See also Section 7.4.3, page 218, where we compute record field slices of arrays of Person records. We declare a Person instance called john where its value is created by a call to the Person constructor function: Person john
=
Person(nJohn",
35,
{"Carl", "Eva"});
Another use of record constructors is to create complex numbers, as in the example model AddComplex below. The declaration of the record Complex also gives rise to a record constructor function, which in the add function is called to create and return a value for the w output formal parameter. It is also called in the equation involving the variable c2: model AddComplex
306 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica record Complex "Complex number" Real re "real part"; Real im "imaginary part"; end Complex; function add input Complex u, Vi output Complex were = u.re+v.re, im end add;
u.im+v.re) ;
Complex c1, c2; equation c2 = add(c1, Complex (sin (time) , cos(time))i end AddComplex;
A third example of using record constructors is in the package Motors below. Here records are used to define a data sheet library for use in motor components. The record constructor functions represent data sheets used for creation of the different motor instances: motorl, motor2, and motor3. encapsulated package Motors record MotorData "Generic data sheet of a motor" parameter Real inertia; parameter Real maxSpeed; end MotorData; model Motor "Motor model" MotorData data; II Using the generic MotorData equation II Realistic motor model would need more variables and equations end Motor;
II Data sheets for motors 1123 and 1145 record MotorDataI123 MotorData(inertia record MotorDataI145 = MotorData(inertia end Motors
0.0010, maxSpeed 0.0015, maxSpeed
2800) 3600)
model Robot II Just refer to data sheets as constructor functions import Motors.·; Motor motorl(data MotorData1123(»; Motor motor2{data MotorDataI123(inertia=O.0012»; MotorData1145()); Motor motor3(data end Robot;
After these introductory examples we are ready to formulate the general rules for automatic creation of record constructor functions from corresponding record declarations. Whenever a record is defined, a record constructor function with the same name and in the same scope as the record class is implicitly defined according to the following rules: 1. The declaration of the record is first elaborated and expanded. This includes inheritance, modifications, redeclarations, and expansion of all names referring to declarations outside of the scope of the record to their fully qualified names. 2. All record elements, i.e., record fields and local class definitions, of the expanded record declaration are used as declarations in the record constructor function. All public record fields become input formal parameters except fields which do not allow modifications, i.e., constant and final declarations as well as protected declarations, which all become protected declarations in the function. The detailed conversion procedure is specified below. 3. An output result formal parameter is declared using the record as its type and a name that is not used by any of the other elements in the record. The result formal parameter has modifiers, which set the record variables to the corresponding input formal parameters of the function.
Chapter 9 Algorithms and Functions 307 The detailed rules according to (2) above for converting record field declarations to input formal parameters or local protected variables and constants within the constructor function are as follows: 1. Record field declarations which do not allow modifications, e.g. constant Real c=l or final parameter Real, as well as protected declarations, are declared as protected local variables and constants in the record constructor function. 2. All prefixes (e.g. constant, parameter, discrete, input, output, ...) of the remaining record fields (being public and modifiable) are removed. 3. The prefix input is added to the public variables declared in the record constructor function. In the above examples we show several uses of such constructor functions converted from records. For example, the function add in the AddComplex example has an elegant use of modifiers in its result parameter of type Complex. The following rather contrived Demo package contains two records, RecordBasel and Record2, which illustrate most of the situations that may occur in implicit record constructor function creation according to the above rules. encapsulated package Demo; record RecordBasel; parameter Real rO = 0; end RecordBasel; record Record2 import Modelica.Math.*; extends RecordBasel; constant Real cl 2.0; constant Real c2; parameter Integer nl = 5; parameter Integer n2; parameter Real rl "comment"; parameter Real r2 = sin(cl); final parameter Real r3 = cos(r2); Real r4; Real r5 = 5.0; Real r6 In t l ; Real r7 [n2] ; end Record2; end Demo;
From the above declarations of the records RecordBasel and Record2, the following record constructor functions are implicitly defined within the same Demo package: encapsulated package Demo; function RecordBasel input Real rO:= 0; output Recordl result(rO end RecordBasel; function input input input input input input input input input input
Record2 Real Real Integer
Integer Real Real Real Real Real Real
rO);
rO .- 0; c2; nl . - 5; n2; rl "comment"; II The comment is also copied from record r2 .- Modelica.Math.sin(cl); r4; rS .- 5.0; r6 [n l.] ; r7 [n2] ;
308 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
output Record2
result(rO=rO,c2=c2,nl=nl,n2=n2,rl=rl,r2=r2, r4=r4,r5=rS,r6=r6,r7=r7) ;
protected constant Real final parameter Real end Record2; end Demo;
cl .- 2.0; II Referenced from r2 r3 .- Modelica.Math.cos(r2);
For example, the Demo.Record2 constructor function can be called as below to construct a value for the instance rl, where we have used mixed positional and named parameter passing:
Demo.Record2 r1 = Demo.Record2 (1, 2, 2, n2=3, rl=l, r2=2 r4=S, rS=5, r6=1:5, r7={1,2,3}); However, the use of a record constructor function in the special case of declaring rl is not very meaningful since it would have been simpler to use modifiers directly on rl to specify its field values.
9.3.3 Additional Function Properties and Restrictions A few additional properties and constraints related to Modelica functions and their formal parameters should also be pointed out: • •
•
•
•
Input formal parameters to Modelica functions are read-only after being bound to the actual arguments, i.e., they may not be assigned values within the body of the function. It is guaranteed that the output formal parameters of a function, i.e., the result variables, always have well-defined values. This is achieved by initializing conditionally assigned result variables to their default values on entry to the function body. If an explicitly assigned default value is not available for some result, the default value for the corresponding result data type is used, e.g. the value zero for Integer or Real numbers. However, the local variables of a function are not automatically initialized to the implicit default values of the data type (e.g. 0.0 for Real) for performance reasons. It is the responsibility of the user to provide explicit defaults or to define the values of such variables before they are referenced. The size of each array result or array local variable of a function must be either given by the input formal parameters, or given by constant or parameter expressions, or by expressions containing combinations of those. A function cannot contain calls to the Modelica built-in operators der, initial, terminal, sample, pre, edge, change, reinit, delay and cardinality, and is not allowed to contain when-statements.
9.3.4 Extending Base Functions Since a function is a restricted and enhanced kind of class (see Section 3.8.6 on page 83 in Chapter 3), it is possible to inherit an existing function declaration in the declaration of a new function. In this way we can declare the common structure of a set of functions as a partial base function (analogous to base class) which we subsequently inherit into the functions we want to define. The drawback to this approach is that the number of formal parameters as well as their types are not immediately visible when reading the code of a function that inherits another function. In the example below, the common structure of having one input parameter and one result is declared as a base function which is extended and reused by several functions:
partial function oneArgBaseFunction input Real Xi II Base function with one argument output Real result; II and one result. end oneArgBaseFunction;
Chapter 9 Algorithms and Functions 309 function myTan extends oneArgBaseFunctioni algorithm result := sin(x)/cos(x)i end myTani
II II II II
Inherits a base function. The code becomes harder to read since the formal parameter list is not. available in the function.
function addTen extends oneArgBaseFunctioni algorithm result := x+lO; end addTen;
There is clearly some benefit of reuse of oneArgBaseFunct ion in the above example. On the other hand, we will find the code harder to read as we just explained. The drawbacks are probably greater than the benefits in this case.
9.3.5 Built-in Functions Certain functions are built into the Modelica language and need not be made available e.g. by being imported from some package. There are basically three groups of built-in functions in Modelica: • • •
Intrinsic mathematical functions. Special operators and functions. Array functions.
The following intrinsic mathematical functions are built into Modelica: abs, sign, sqrt, div, mod, rem, ceil, floor, and integer, as well as sin, cos, exp, etc. These functions are described in Section 6.13 on page 199 in Chapter 6. All functions in the standard Modelica library Mode1 i ca . Math behave as builtin functions and can be called using short names such as sin, cos, exp, etc. The special operators and functions have function syntax even though many of these are not really functions in the usual sense. They are described in Section 6.14 on page 200 in Chapter 6 and include the following: der, analysisType, initial, terminal, noEvent, smooth, sample, pre, edge, change, reinit, delay, cardinality, and direction. The built-in array functions are described in Section 7.9 starting on page 225 in Chapter 7. These include dimension and size functions such as size and ndims, conversion functions for changing the dimensionality of scalars and arrays, e.g. vector and matrix, constructor functions for creating array values, reduction functions for computing scalar values from arrays, matrix and vector algebra functions, and array concatenation functions. See also Chapter 16, page 615, for a list of the built-in functions and operators.
9.3.6 Scalar Functions Applied to Array Arguments In certain situations it is useful to be able to apply a function to array values even if it has not been defined for such arguments. This can be done if an obvious generalization to elementwise application of the function is possible. Modelica functions with one scalar return value can be applied to arrays elementwise, e.g. if v is a vector of reals, then cos (v) is a vector where each element is the result of applying the function cos to the corresponding element in v. For example: cos({a,b,c}) II Vector argument, result: {cos(a) ,cos(b),cos(c)} cos([1,2i 3,4]) II Matrix argument, result: [cos(1),cos(2)i cos(3),cos(4)]
310 Peter Fritzson Principles of Object-OrientedModelingand Simulation with Modelica Functions with more than one argument can be generalized to elementwise application. If more than one argument is generalized to an array, all of the arguments have to be of the same size, and they are traversed in parallel. For more information regarding the application of scalar functions to array arguments, see Section 7.10 on page 229 in Chapter 7.
9.3.7 Viewing Algorithms as Functions The function concept is a basic building block when defining the semantics or meaning of programming language constructs. Some programming languages are completely defined in terms of mathematical functions. This makes it useful to try to understand and define the semantics of algorithm sections in Modelica in terms of functions. We have already mentioned several times in this chapter that algorithm sections are special cases of functions. For example, consider the algorithm section below, which occurs in an equation context: algorithm
Y .-
Xi
:= 2*Yi := Z+Yi
Z
Y
This algorithm can be transformed into an equation and a function as below, without changing its meaning. The equation equates the output variables of the previous algorithm section with the results of the function f. The function f has the inputs to the algorithm section as its input formal parameters and the outputs as its result parameters. The algorithmic code of the algorithm section has become the body of the function f. (y,z)
=
f(x) i
function f input Real Xi output Real y,zi algorithm y .- Xi Z
.- 2*Yi
Y
.-
Z+¥i
end fi
9.3.8 Comparison of Functions with General Modelica Classes The function concept in Modelica can be regarded as a restricted class with some enhancements, e.g. see the section on restricted classes in Section 3.8 on page 81 in Chapter 3, which contains a similar but shorter description compared to the one below. The syntax and semantics of a function have many similarities to those of the block restricted class. A funct ion also has many of the properties of a general class, e.g. being able to inherit other functions, or to redeclare or modify elements of a function declaration. However, a function has the following restrictions compared to a general Modelica class: • • • •
Each formal input parameter of the function must be prefixed by the keyword input, and each formal result parameter by the keyword output. All formal parameters must be public variables. Formal input parameters are read-only, i.e., they may not be assigned values in the body of the function. A function may not be used in connections, may have no equations, and can have at most one algorithm section, which, if present, is the body of the function. For a function to be called, it must have either an algorithm section or an external function interface as its body.
Chapter9 Algorithms and Functions •
311
A function cannot contain calls to the Modelica built-in operators der, initial, terminal, sample, pre, edge, change, reinit, delay and cardinality, and is not allowed to contain
when-statements. A subtype of a function type must be type equivalent to the function type itself. This is more restrictive than the usual subtyping rules between Modelica classes. The size of each array result or array local variable of a function must be either given by the formal parameters, or given by constant or parameter expressions.
• •
A Modelica function has the following additional properties compared to a general Modelica class: • • •
A function may be called using the conventional positional calling syntax for passing arguments. A function can be recursive. A formal parameter or local variable may be initialized through an assignment (: =) of a default
•
A function is dynamically instantiated when it is called rather than being statically instantiated by
•
an instance declaration, which is the case for other kinds of classes. A function may have an external function interface specifier as its body.
value in its declaration. Initialization through an equation is not possible.
9.4 External Functions It is possible to call functions defined outside of the Modelica language, implemented in C or Fortran 77, in the C subset of C++, or in the Fortran 77 subset of Fortran 90. If no external language is specified, the implementation language for the external function is assumed to be C. The body of an external function is marked with the keyword external in the Modelica external function declaration, for example: function log input Real Xi output Real Yi external end log;
The external function interface supports a number of advanced features such as.in--out formal parameters in the external function parameter list, local work arrays, arbitrary external function parameter order, and explicit specification of row-major versus column-major array memory layout.
9.4.1 Structure of External Function Declarations The standard structure of a Modelica external function declaration is basically the same as that of a standard Modelica function. The only difference is that we have replaced the algorithm body of the function with the keyword external possibly followed by any of the optional items language_spec, extemal function caII_spec, extemal_call_spec_annotation, and extemalfunctionimnotation. The structure is as follows: function <external_call_spec_annotation> i
«externalfunctioncnnotation» i end ;
312 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica The local variables in the optional protected part allow for temporary storage, e.g. work arrays needed for certain Fortran library routines. If we just use the keyword external without any of the optional items, a number of default rules apply. If there is no language_spec, the external implementation language is assumed to be C. If there is no externaIJunction_call_spec, a default call structure mapping, see below, from the Modelica function formal parameters to the external function parameters and return value applies. The language_spec in an external function specification gives the implementation language of the external function and must currently be one of the following strings if specified:
•
"C"
•
"FORTRAN 77"
Remember that uppercase letters must be used in the string not specified the default external language n C" is assumed.
9.4.1.1
"FORTRAN 77 If.
Otherwise, if the language is
Default Call Structure Mapping
The following default mapping rules apply if no externaIJunction_call_spec is provided: • •
• •
•
The default external function name is the same as the Modelica function name. The default ordering of the formal parameters in the external function prototype in the external programming language is the same as the ordering of the Modelica function input and output formal parameter declarations. There is one exception, however. If there is just one Modelica output parameter, the default assumption is that it corresponds to the return value of the external function and not to an output formal parameter. An array argument is passed by default for both C and Fortran 77 as the address of the array followed by the array dimension sizes. The default array layout mapping is conversion to "rowMajor" when calling a C function and to "co!umnMajor" when calling a Fortran 77 function. This can be overridden by the arrayLayout annotation. Automatic mapping of Modelica types to C or Fortran 77 and back, according to the table in Section 9.4.2 on page 315.
The function tan2 below is a very simple external function specification just using the single keyword external, which implies that the default mapping rules apply. function tan2 input Real xl; input Real x2; output Real Yi external end tan2;
This Modelica external function specification gives rise to the following C function prototype, shown below together with an example call in Modelica and the corresponding translated call. double tan2(double, double) ; C-prototype: Example call in Modelica: z := tan2(S.5, 4) ; Translated call in C: z = tan2(5.5, 4) ;
We will now illustrate the default mapping of array arguments to external C and Fortran 77 functions according to the type translation table in Section 9.4.2 on page 315. First we show a simple Modelica external function that maps to an external C function: function foo input Real output Real
a [: , : , :] ; Xi
Chapter 9 Algorithms and Functions
313
external; end foo;
This corresponds to the following C function prototype and example calls: double foo (double * size t, size t, size t); w := foo( )i double temp (] [] [] = {{ {i , 2} , {3, 4} }, {{5, 6} , {7 , 8} }} ; w = foo(&temp, 2,2,2); of
The same external function foo can instead be specified as mapping to a Fortran 77 function: function foo input Real a[:, :,:]; output Real Xi external "FORTRAN 77"; end faa;
The default mapping corresponds to a Fortran 77 function defined as below: FUNCTION foo(a, nl, n2, n3) DOUBLE PRECISION a(nl,n2,n3) INTEGER nl INTEGER n2 INTEGER n3 DOUBLE PRECISION foo END
9.4.1.2
Explicit Call Structure Mapping
The extemaIJunction_call_spec allows calling external functions which do not match the default mappings of function name, external formal parameter ordering, input or output parameters, return value, and array arguments. The structure of the extemalJunction_call_spec is one of the following two variants:
1. extemalfuncnameiargumentlistt 2. output-parameter = externalfuncnameiargumentlist) The only kinds of expressions allowed in the argumentlist are identifiers. scalar constants, and the function size (arr,i) applied to an array and a constant array dimension number. The optional externalfunction jannotation is used to pass additional information to the compiler when necessary. Currently the only supported annotation is arrayLayout, which can be either "rowMajor" or lI~olumnMajor",being defaults for C and Fortran array layout respectively. We use the simple external C function j oinThreeVectors below as an example of the first variant of extemalfunction jcalljspec. A Modelica implementation joinThreeVectorsM of the same function is shown as a comparison. function joinThreeVectorsM "Modelica version" input Real vI[:] ,v2[:],v3(:]; output Real vres[size(vl,I)+size(v2,1)+size(v3,1)]; algorithm vres := cat{1,vI,v2,v3); end joinThreeVectorsM;
The external C function in this case happens to have a different name join3vec in C compared to its Modelica name joinThreeVectors. The parameter list of the C function does not follow the default mapping rules, and returns its result in an output parameter and not as a return value. Therefore an externalJunction_call_spec of the first of the above two variants is appropriate. The array layout annotation is really not needed here since II rowMaj or" is default for C. It is just shown as an example.
314 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica function input output external
joinThreeVectors "Modelica external function version" Real vl[:],v2[:],v3[:]; Real vres[size(v1,1)+size(v2,1)+size(v3,1)]; tIC" join3vec(vl,v2,v3,vres,size(vl,I),size(v2,1),size(v3,1»; annotation(arrayLayout = "rowMajor"); end joinThreeVectors;
The above Modelica external function version of j oinThreeVectors corresponds to the following Cprototype with example calls, where the predefined C type size_t is the same as the C type unsigned int, and is used to pass array dimension sizes. C-prototype:
void join3vec(double*, double* , double* , double*,size_t, size- t, size_t);
Example call in Modelica: vjoined .- joinThreeVectors(va,vb,vc); join3vec(&va, &vb, &VC, &vjoined, nl, 02, n3); Translated call in C: The next example shows how arrays can be passed an external Fortran 77 function using explicit call structure mapping. function fum Real input xlil ; y[size (x, 1) , r l ; input Real input Integer i; ul [size (y, 1) ] ; output Real output Integer u2[size(y,2)] ; external "FORTRAN 77" myfum(x, y, size(x,l), size(y,2), ul, i, u2); end fum;
The corresponding Fortran 77 subroutine would be declared as follows: SUBROUTINE myfum(x, y, n, ro, ul, i, u2) DOUBLE PRECISION(n) x DOUBLE PRECISION(n,m) y INTEGER n INTEGER m DOUBLE PRECISION(n) ul INTEGER I DOUBLE PRECISION(m) u2 END
The second form of externalJunction_call_spec is output-parameter = extemalfuncnameiargumentlist). It is needed in situations where additional information about how to map the external function value is required. The following external function returns two results: one function value and one output parameter value. Both are mapped to Modelica function results as specified. This situation requires the second form of external function call specification. function duaLkeau l.t.a input Real X; input Integer Yi output Real funcvalue; output Integer outl; external "C" funcvalue = doubleresults(x, y, outl); end dualResults;
This corresponds to the following: double doubleresults(double, int, int *) ; C-prototype: Example call in Modelica: (zl,i2) := dualResults{2.4, 3) ; zl = doubleresults(2.4, 3, &i2) ; Translated call in C:
Chapter 9 Algorithms and Functions
315
9.4.2 Argument and Result Type Mapping Arguments and result values are mapped from Modelica types to corresponding C or Fortran 77 types and back when calling an external function from Modelica. The table shows the mapping of argument and result types at external function calls between Modelica, and C or Fortran 77. Here T, TC, and TF denote corresponding Modelica, C, and Fortran array element types respectively; see further explanations. in the table below. There are two ways for an external function to return results: 1. Through output formal parameters. 2. As a function return value. The external types for output parameters are indicated in the table when different from the input parameter types. The external types for function return values should be declared in the same way in the external function as for input formal parameters of the same type, except for arrays where array dimension sizes are to be left out. If there is a single output parameter and no extemalJunction_call_spec, or if there is an explicit extemaIJunction_call_spec, in which case the left-hand side must be one of the output formal parameters, the external routine is assumed to be a value-returning function. Otherwise, the external function is assumed not to return anything, i.e., it is a void-function in C or a subroutine in Fortran. Modelica
C
FORTRAN 77
Real
double (double* for output)
DOUBLE PRECISION
Integer
int
(int*
for output)
INTEGER
Boolean
int
(int:.*
for output)
LOGICAL
String
const char* (cons t char ** for output, may need ModelicaAllocateString)
Enumeration type int
(int *
for output)
CHARACTER (Not yet in the Modelica standard; tool dependent availability) INTEGER TF, INTEGER d 1 ,
Input or output This is the default argument mapping of formal parameter an array including dimension sizes used if no extemaIJunction_caLL_spec is present. If such a call specification is present only the address of the array, of type TC*, is passed since we explicitly specify dimension size arguments in the extemaIJunction_call_spec. TC *
•••
I
INTEGER d n
Default mapping of an array including dimension sizes used if no extemaIJunction_call_spec is present. If such a call specification is present only the address of the array is passed since we explicitly specify dimension size arguments in the extemaIJunction_call_spec. TF
Return value
No dimension sizes are included when mapping return types since the sizesare already known by the caller.
record
struct *
(struct * * for output)
Only records with Each Modelica record field is mapped Real, Integer, into a C struct field with the same field Boolean, and ordering. The mapping is according to the
Not available for Fortran.
316 Peter Fritzson Principles of Object-OrientedModelingand Simulation with Modelica enumeration fields, record fields, or fixedsize array fields.
translation of types in this table, except for fixed-size arrays, where the elements are just laid out without dimension sizes according to the default array layout or any explicit array layout directive for column or row major order.
The following general and simple-type related considerations apply for argument-and return-type mapping at external function calls: •
• •
•
Formal parameters of the primitive C types double and int are declared as double* and int * for output formal parameters in C function prototypes, since addresses of receiving variables are needed for output. ITwe call an external Fortran function or subroutine, addresses are passed for both input and output formal parameters since Fortran always uses call by reference. When an argument in a C extemaIJunction_call_spec is of the form size (..., ...), then the corresponding C formal parameter type is size_t, usually defined as unsigned int, instead of the usual into Values of enumeration types used as arguments are mapped to type int when calling an external C function, and to type INTEGER when calling an external Fortran function. The ith enumeration literal is mapped to integer value i, starting at 1. Return enumeration values in integer form are mapped to enumeration types analogously: the integer value 1 is mapped to the first enumeration literal, 2 to the second, etc. Returning a value which does not map to an existing enumeration literal for the specified enumeration type is an error.
The following applies to strings passed and returned to/from external functions: •
•
Modelica string arguments can be passed to input formal parameters in C and for certain MOOeHca implementations to Fortran 77 even if not yet officially in the MOOeHca standard. Strings are NULLterminated, i.e., ending with a null character ,\ 0 ' , to simplify calling of C functions. When returning a nonliteral string as an output formal parameter or return value, the memory for this string can be allocated with the function ModelieaAlloeateString (see Section 9.4.5, page 319). The C malloe function should not be used because a Modelica simulation environment may have its own allocation scheme, e.g. a special stack for local variables of a function. After return of the external function the Modelica environment is responsible for the memory allocated with ModelicaAllocateString, e.g. to free this memory when appropriate. It is not allowed to access memory that was allocated using ModelicaAllocateString in a previous call of the external function since it might have become deallocated.
Regarding arrays and records we have the following considerations:
•
•
Array arguments of type T[d1 , •••, dnl can be passed as input as well as output formal parameters, where the element type T is one of the basic Modelica types Real, Integer, Boolean, String as well as record (but record is not supported for Fortran 77) and d 1 , •••, do are the sizes of the 1st to the nth array dimensions. TC and TF are the corresponding C and Fortran 77 versions of the element type according to the above table. An array is generally passed as the address of the array followed by n integers for the n dimension sizes. In the case of C these integer formal parameters are declared with the type size_t which normally is the same as unsigned into An array or record can also be returned as afunction return value. In that case only the address of the array or record is returned since storage for the returned data must be preallocated by the caller. Dimension sizes are not returned since the dimensions of a preallocated returned array are set by the caller. A record can be returned from a C function but not from a Fortran 77 function.
Chapter 9 Algorithms and Functions 317 •
When we pass record, array, and string arguments or return records and arrays, these are passed or returned by reference, i.e., a pointer to each argument is passed or returned, which is evident from the above type translation table.
As an example, a Modelica record Rec below is mapped to a corresponding C struct: record Rec Real Integer Boolean end Rec;
z;
mapped to
y[30];
b;
struct Rec double int int };
{ z; y[30]; b;
9.4.3 A Large Example The external function interface supports a number of advanced features such as in-out parameters and declaration of temporary work variables, which are illustrated by the following rather complicated example. For example, the formal parameters Ares, Bres, Cres, and Ores correspond to in/out parameters in the external function bilinearSampling below, which has the values A, B, C, and D as input defaults and different values as results. The ordering and usage of formal parameters to the external Fortran function is handled through explicit call structure mapping. This is used below to explicitly pass sizes of array dimensions to the Fortran routine called ab04md. Some old-style Fortran routines like ab04 md need work arrays, which are conveniently handled by local variable declarations after the keyword protected. A string constant is also passed to the Fortran function, even though passing strings to Fortran functions is not yet officially in the Modelica standard, In fact, almost aU Fortran functions or subroutines available in common numerical libraries require at least one string argument. function bilinearSampling "Function for Discrete-time continuous-time systems conversion by a bilinear transformation." input Real alpha := 1, beta := 1; input Real A[:,size(A,l)], B[size(A,l),:], C[:,size(A,l)], D[size(C,I) ,size(B,2)]; input Boolean isContinuous := true; output Real Ares[size(A,l), size(A,2)] := A, II Ares is in-out Bres[size(B,l), size(B,2)] .- B, II to the Fortran function Cres[size(C,l), size(C,2)] .- C, Dres[size(D,l), size(D,2)] .- D; output Integer info; protected Integer iwork[size(A,l)]; II Work arrays Real dwork[size(A,l)]; String c2dstring:= if isContinuous then "C" else "0"; external "FORTRAN 77" ab04md(c2dstring,size(A,I),size(B,2),size(C,I), alpha,beta,Ares,size(Ares,I),Bres,size(Bres,l), Cres,size(Cres,l),Dres,size(Dres,I), iwork,dwork,~ize(dwork,l),info) ; end bilinearSampling;
The following Modelica class contains an example call to bilinearSampling, which via the external function interface is transformed to a call to ab04md. class BilinearSampli.ngTest parameter Real alpha=l, beta=l; parameter Real A[:,:] [0, 1; 2, 4], B[:,:]
[5,
6; 7,
8),
C[:,:] D [ : , :]
[9,10; 11,12], [13,14; 15,16];
II Coefficients
318 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica Real Ares[size(A,l), size(A,2)], II Results Bres[size(B,l), size(B,2)], Cres[size(C,l), size(C,2)], Dres[size(D,l), size(D,2)]; Integer info; equation (Ares,Bres,Cres,Dres,info) bilinearSampling(alpha,beta,A,B,C,D,true); end BilinearSamplingTest;
If the external function ab04md would have been a C function instead of a Fortran function the corresponding C function prototype would become: void ab04md(const char *, size t, size t, size t, double, double, double *, size t, double *~ size t, double *, size t, double *, size=t, int *, double size_t, int *);-
*,
9.4.4 Preventing External Functions from Changing Their Inputs Modelica functions disallow changing input formal parameters. An external function called from Modelica must behave in the same way as if the function had been implemented in Modelica. Therefore an external function is not allowed to internally change its inputs, even if they are restored before the end of the function. For efficiency reasons, e.g. to avoid copying of large arrays, the Modelica function formal parameters are mapped directly to the external function formal parameters. When calling Fortran functions all arguments are passed by reference, and when calling C functions arrays and records are passed by reference. Such input arguments could theoretically be changed by the external function and thus violate the above rule. If the external function interface programmer suspects that the external function may change some of its inputs, those inputs should be copied in the interface function to prevent any problems on the Modelica side. For example, consider the following Modelica function f, which calls an external Modelica function efune that is mapped to the external Fortran function forfune. function f input Real ai output Real b; algorithm b:=efunc(a,a); b:=efunc(b,2*b) ; end f;
The Modelica compiler will usually translate the function f to the C function f below, which in tum calls the external function efunc that has been mapped from forfunc. The extra underscore in forfunc_ is usually added when calling a Fortran function from C. double f(double a) { extern void forfunc_(double*,double*,double*); double b,templ,temp2; forfunc_(&a,&a,&b); templ=2*b; temp2:b; forfunc_(&b,&templ,&temp2); return temp2;
A straightforward external function declaration of efunc being mapped to forfune can appear as follows: function efunc input Real Xi
"Straightforward version of interface function"
Chapter 9 Algorithms and Functions 319 input Real Yi output Real Z:=Xi external "FORTRAN 77" forfune(x,y,z); end efunci
If the first input is changed internally within forfune, the designer of the interface would have to change the interface function efune to the following by inserting a copying operation in order to protect against unwanted change of that input formal parameter: function efune "Version that protects first argument against change" input Real Xi input Real Yi output Real Zi protected Real xtemp:=x; II Temporary since forfunc changes l:st input external "FORTRAN 77" forfunc(xtemp,y,z); end efunci
9.4.5 Utility Functions Callable in External Functions Within external functions called from Modelica we often need access to the following two kinds of generic mechanisms: • •
Reporting errors in a way compatible with the Modelica error-handling mechanism. Allocating memory for variable-sized results such as strings that are passed back from the external function for use by Modelica code and therefore need to be Modelica-managed data. This is not needed for known-size results, e.g. arrays, since that memory is preallocated by the caller.
This kind of functionality is different from most other user-defined external code in that it needs to be compatible with and interact closely with the Modelica run-time system, which usually is not accessible to the nser. For these reasons the following utility functions are provided. They can be called within external Modelica functions implemented in C if ModelicaUtilities. h is included into the C-file. ModelicaMessage ModelicaFormatMessage
void ModelieaMessage{const char* string) Output the message s t ring as is withou~ format control. void ModelicaFormatMessage(const char* fstring,
... )
Output the message using the same format control as used by the Cfunction printf, with fstring as the format control string and ... representing the arguments to be printed. ModelicaError
void ModelicaError{const char* string) Output the error message s t ring as is without format control. This
function never returns to the calling function, but handles the error similarly to an assert in Modelica code. ModelicaFormatError
void'ModelicaFormatError(const char* fstring,
... )
Output the error message using the same format control as the C-function printf, with fstring as the format control string and ... representing the arguments to be printed. This function never returns to the calling function, but handles the error similarly to an assert in Modelica code. ModelicaAllocateString
char* ModelicaAllocateString(size_t n)
Allocate memory for a Modelica string of length n, which is used as a result formal parameter or a return function value of an external Modelica function. An extra byte for a terminating NUL-character is automatically allocated. Note that the storage for string arrays (i.e., pointer to string
320 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica array) is still provided by the calling program, as for any other array. If an error occurs, this function does not return, but calls ModelicaError. ModelicaAllocateString char*ModelicaAllocateStringWithErrorReturn(size_t len) WithErrorReturn Same as ModelicaAllocateString, except that in case of error, the function returns O. This allows the external function to close files and free other open resources in case of error. After cleaning up resources use ModelicaError or ModelicaFormatError to signal the error. We illustrate the use of one of these utility functions by the following example. A Modelica external function fillString returns a string filled with characters of the specified 8-bit ASCII-code: function fillString input Integer charCode(min=O,max=255); input Integer n(min=O)i output String result; external "C" result = fillString(charCode,n); end fillStringi
The C code for the fillString external function might be written as follows: #include "ModelicaUtilities.h" char* fillString(int charCode, int n) /* Create and return string with n characters of code charCode */ char* str ModelicaAllocateString(n)i int ii for (i=Oi i= 0.000001, do the next two steps:
• •
1. Add next term to the sum. 2. Calculate a new next term.
Tip: Every term in the sum is of the form 1/ (k*k), where k increases by one for each step. Set a variable to keep track of whether the next term is negative or positive. When the program is run the sum will be 0.82247. Exercise 9-4:
When-statement: Let us go back to the class LightSwi tch, which is initially switched off and switched on at time 5. Change this class to contain a when-statement instead of a when-equation. Now change the LightSwitch class so that in the time interval 5-20 it turns the light on every fifth second for one second and then it is switched off again.
Tip: sample (start, interval) returns true and triggers time events at time instants and rem (x, y) retums theintegerremainderofx/y, such that div(x,y) * y + rem(x, y) = x. Exercise 9-5:
reinit: Write a model BilliardBalls with two billiard balls that are rolling from opposite directions and bounce into each other.
Tip: reinit (x, value) is the same thing as x . - value, but reinit reinitializes the value of x at a specific time and the equations still holds. Exercise 9-6:
Functions: Write a function faculty, such that faculty (n)
1 *2 * 3 * 4 * .... *n.
Write a class that contains a function call to faculty. Exercise 9-7:
Functions: We want to search through an array of names and find the position of a particular name. The function should have two arguments, an array of names and the name we are looking for. The output will be the index where the name was found, or an error will occur if the name was not found. Write a class that tests the previous function.
Tip: Assert can be used to check whether the result has been found, and, if it has not been found, the message in the second argument will be shown otherwise. Exercise 9-8:
Vector Orthogonality: Write a function, ScalarProduct, that calculates the scalar product of two arbitrary vectors (ut , u2, u3, ... , un) and (v1, v2, v3, ... , vn). The result should be: ul*vl + u2*v2 + ••. + un*vn. Two vectors (ul, u2, u3, product is equal to
... , un) and (v1, v2, v3,
...
, vn) are orthogonal if the scalar
o.
Write a class, Orthogonal, that decides if two integer vectors are orthogonal. The vectors must have the same number of elements, but the number of elements should be arbitrary.
Tip: Applying the multiplication operator between two vectors gives the scalar product.
333
Chapter 10 Packages
Packages in Modelica may contain definitions of constants and classes including all kinds of restricted classes, functions, and subpackages. By the term subpackage we mean that the package is declared inside another package, no inheritance relationship is implied. Parameters and variables cannot be declared in a package. The definitions in a package should be related in some way, which is the main reason they are placed in a particular package. Packages are useful for a number of reasons: • •
• •
• •
Definitions that are related to some particular topic are typically grouped into a package. This makes those definitions easier to find and the code more understandable. Packages provide encapsulation and coarse-grained structuring that reduces the complexity of large systems. An important example is the use of packages for construction of (hierarchical) class libraries. Name conflicts between definitions in different packages are eliminated since the package name is implicitly prefixed to names of definitions declared in a package. Information hiding and encapsulation can be supported to some extent by declaring protected classes, types, and other definitions that are available only inside the package and therefore inaccessible to outside code. Modelica defines a method for locating a package by providing a standard mapping of package names to storage places, typically file or directory locations in the file system. Identification of packages. A package stored separately e.g., on a file, can be (uniquely) identified.
We will gradually cover all these aspects throughout the chapter. First we present a simple example of a package with related definitions and discuss the notions of information hiding and abstract data types in relation to Modelica packages.
10.1 Packages as Abstract Data Types The notion of a package is related to and partly originates from the notion of abstract data type. The classical definition of a data type e.g., Real with its associated operations +,-, *, /, ==, etc., is as a data structure together with operations on that data structure. An abstract data type is just like an ordinary data type i.e., definitions of data and operations, together with a method for collecting the implementations of the operations in one place and hiding the details of those implementations. As an example, consider the package ComplexNumbers below, which contains a data structure declaration, the record Complex, and associated operations such as Add, Multiply, MakeCompley: etc. The package is declared as encapsulated, which is the recommended software engineering practice to keep our software well structured as well as being easier to understand and maintain.
334 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica encapsulated package ComplexNumbers record Complex Real rei Real im; end Complex; function Add input Complex input Complex output Complex algorithm z.re := x.re + z.im := x.im + end Add;
x; Yi
z; y.re; y.im
function Multiply input Complex X; input Complex Yi output Complex Zi algorithm z.re := x.re*y.re - x.im*y.imi z.im := x.re*y.im + x.im*y.re; end Multiply; function MakeComplex input Real Xi input Real Yi output Complex Zi algorithm z.re := Xi z.im := Yi end MakeComplexi
II Declarations of Subtract, Divide, RealPart, ImaginaryPart, etc. II (not shown here) end ComplexNumbers;
How can we make use of the package ComplexNumbers? We can find one example in the class ComplexUser below, where both the type Complex and the operations Multiply and Add are referenced by prefixing them with the package name ComplexNumbers . class ComplexUser ComplexNumbers.Complex a(re=1.0, im=2.0)i ComplexNumbers.Complex b(re=1.0, im=2.0) i ComplexNumbers.Complex Z,Wi equation Z = ComplexNumbers.Multiply(a,b)i w = ComplexNumbers.Add(a,b)i end ComplexUseri What about information hiding in the package? The type Complex must be made available for use in classes and packages for allocation and initialization of variables of that type e.g., the variables a, b, z, and w in ComplexUser. The implementation details of Complex are exposed and used e.g., to initialize the variables a and b via their fields x and y. It would not work if we declared x and y protected in Complex since then these fields would not be available for the implementation of Add and Multiply, etc. However, by declaring the operations on Complex inside the class Complex itself as in the package ComplexNumbersA further below, these fields can be accessed even if they are protected. We can increase the degree of data abstraction by using the function MakeComplex for initialization instead of modifiers e.g., as in ComplexUser2 below, thus avoiding exposing the fields x and y. If we apply the programming convention that all direct access to these fields is avoided in user code it would be
Chapter 10 Packages 335 possible to change the internal implementation e.g., to polar coordinates, without changing any of the user code. However, avoiding such internal access to the fields is not checked by Modelica. class ComplexUser2 ComplexNumbers.Complex a=MakeComplex(1.O,2.0); ComplexNumbers.Complex b=MakeComplex(1.O,2.0); ComplexNumbers.Complex z,w; equation z = ComplexNumbers.Multiply(a,b) ; W = ComplexNumbers.Add(a,b); end ComplexUser2;
10.2 Package Access There are essentially two ways of accessing the definitions of a package: • •
Direct reference by prefixing the package name to definition names. Importing definitions from the package.
We have already used the first method in the previous examples. It is usually more convenient and often necessary to use the import mechanism, which is the subject of the next section. The two access levels in Modelica, public and protected, also apply to definitions declared in a package since package is a restricted and enhanced class that shares most properties of general Modelica classes. Protected definitions of a package cannot in general be accessed by other packages and classes, except for local packages and classes, and packages inheriting the current package. For discussions of these exceptions, see the sections on local packages on page 352 and inheriting packages on page 347 in this chapter.
10.2.1 Importing Definitions from a Package The import statement makes public classes and other public definitions declared in some package available for use in a class or a package. It is also the only way of referring to definitions declared in some other package for use inside an encapsulated package or class. To summarize, import statements in a package or class fill the following two needs: • •
Making definitions from other packages available for use in a package or class. Explicit declaration of usage dependences on other packages. This is important for reducing the complexity of understanding and maintaining large systems consisting of many packages.
statement can occur in one of the following four syntactic forms which are explained in more detail in the following sections:
An import
import «packagenames , import «packagename>. «definitionname» ;
import «packagename» . * ; import «shortpackagename» = «packagename»,
(qualified import) (single definition import) (unqualified import) (renaming import)
Here packagename is the fully qualified name of the imported package including possible dot notation. For example, if the package ComplexNumbers would have been declared as a subpackage inside the package Modelica.Math, its fully qualified name would be Modelica.Math.ComplexNumbers. Definitionname is the simple name without dot notation of a single definition that is imported. A shortpackagename is a simple name without dot notation that can be used to refer to the package after import instead of the presumably much longer packagename.
336 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica The four forms of import are exemplified below assuming that we want to access the addition operation of the package Modelica. Math. ComplexNumbers: import import import import
Modelica.Math.ComplexNumbers; II Access by ComplexNumbers.Add Modelica.Math.ComplexNumbers.Add; II Access by Add Modelica.Math.ComplexNumbers.*i II Access by Add Co = Modelica.Math.ComplexNumbers; II Access by Co.Add
The following rules also apply to import statements: • • • • •
Import statements are not inherited. Import statements are not named elements of a class or package. This means that import statements cannot be changed by modifiers or redeclarations. The order of import statements does not matter. One can only import/rom packages, not from other kinds of classes. Both packages and classes can be imported into i.e., they may contain import statements. An imported package or definition should always be referred to by its fully qualified name in the import statement.
10.2.1.1 Qualified Import The qualified import statement import «packagename»; imports all definitions' in a package, which subsequently can be referred to by (usually shorter) names simplepackagename . definitionname, where the simple package name is the packagename without its prefix. For example, if the package ComplexNumbers would have been a subpackage of Modelica.Math, the import statement in the package ComplexUserl would appear as import Modelica. Math. ComplexNumbers; but the rest would be the same i.e., we write ComplexNumbers. Add for the addition operation. This is the most common form of import that eliminates the risk for name collisions when importing from several packages. encapsulated package ComplexUserl import ComplexNumbersi class User ComplexNumbers.Complex ComplexNumbers.Complex ComplexNumbers.Complex
a(x=l.O, y=2.0); b(x=l.O, y=2.0)i Z,Wi
equation
= ComplexNumbers.Multiply(a,b)i
Z W =
ComplexNumbers.Add(a,b)i end User; end ComplexUserl;
10.2.1.2 Single Definition Import The single definition import of the form import «packagename>. «definitionname»; allows us to import a single specific definition (a constant or class but not a subpackage) from a package and use that definition referred to by its definitionname without the package prefix. The statement import ComplexNumbers . Add; allows us to just write Add for the addition operation as in the class User within ComplexUser2 below. The drawback is that we have to write an import statement for each imported definition which can be a bit cumbersome. There is no risk for name collision as long as we do not try to import two definitions with the same short name. encapsulated package ComplexUser2 import ComplexNurnbers.Complex; import ComplexNumbers.Multiply; import ComplexNumbers.Add;
Chapter 10 Packages 337
class User Complex a(x=1.0, y=2.0)i Complex b(x=1.0, y=2.0); Complex Z,Wi equation z = Multiply(a,b) ; w = Add(a,b)
i
end User; end ComplexUser2;
10.2.1.3 Unqualified Import The unqualified import statement of the form import packagename. * imports all definitions from the package using their short names without qualification prefixes. This might appear convenient for the lazy programmer but has a high risk for name collisions when importing from several packages. Another problem is that future compilation errors may occur if new definitions are added to the imported packages. For example, if a new type named w would be added to the package ComplexNumbers there would be a name collision causing a compilation error in the class ComplexUser3 below since there is a local variable with the same name. For these reasons, the unqualified import statement is not recommended for code that is intended to be stable and maintainable. Its main use is in small examples where conciseness is important. None of the other three forms of import has these problems. This example also shows direct import into a class instead of into an enclosing package. class ComplexUser3 import ComplexNumbers.*; Complex a(x=1.0, y=2.0); Complex b(x=1.0, y=2.0); Complex Z,W; equation Z = Multiply(a,b); w
= Add (a, b) ;
end ComplexUser3;
10.2.1.4 Renaming Import The renaming import statement of the form import «shortpackagename» = <package name > ; imports a package and renames it locally to shortpackagename. One can refer to imported definitions using shortpackagename as a presumably shorter package prefix. For example, the statement import Co = ComplexNumbers; in the class ComplexUser4 below, allows us to refer to the addition operation by Co . Add. This is as safe as qualified import but gives more concise code. class ComplexUser4 import Co = ComplexNumbers; Co.Complex a(x=1.0, y=2.0); Co.Complex b(x=1.0, y=2.0); Co. Complex Z,Wi equation Z = Co.Multiply(a,b); W
= Co. Add (a, b) ;
end ComplexUser4;
338 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
10.3 Package and Library Structuring A well-designed package structure is one of the most important aspects that influences the complexity, understandability, and maintainability of large software systems. There are many factors to consider when designing a package, e.g.: • • • •
The name of the package. Structuring of the package into subpackages. Reusability and encapsulation of the package. Dependencies on other packages.
Modelica defines a standard mapping of hierarchical package structures onto file systems or other storage mechanisms such as databases, which provides us with a simple and unambiguous way of locating a package. The Modelica library path mechanism makes it possible to make multiple packages and package hierarchies simultaneously available for lookup. All of these mechanisms give us considerable flexibility and power in structuring a package. This freedom should, however, be used in an appropriate way.
10.3.1 Package Naming and Subpackages The name of a package should be descriptive and relate to the topic of the definitions in the package. The name can be chosen to be unique within a project, within an organization, or sometimes in the whole world, depending on the typical usage scope of the package. Since classes can be placed in packages, and packages is a restricted form of class, Modelica allows packages to contain subpackages i.e., packages declared within some other package. This implies that a package name can be composed of several simple names appended through dot notation, e.g., "Root package" ." Package level two"." Package level three", etc. Typical examples can be found in the Modelica standard library, where all level-one subpackages are placed within the root package called Modelica. This is an extensive library containing predefined subpackages from several application domains as well as subpackages containing definitions of common constants and mathematical functions. See also Chapter 16, page 615, for a more complete description of the Modelica standard libraries, and Section 2.17 on page 54 in Chapter 2 for naming conventions in general recommended for Modelica code. A few examples of names of subpackages in this library follow here: Modelica.Mechanics.Rotational.lnterfaces II Four levels of packages Modelica.Electrical.Analog.Basic II Basic electrical definitions Modelica.Blocks.lnterfaces II Interfaces to Blocks library
Choosing meaningful and unique names for packages within a large organization can be a problem. Sometimes one can choose the name by the help of an internal arbiter in an organization to ensure that two projects will not pick conflicting names. However, in the world at large this approach is insufficient. One way to ensure unique package names over the whole world is to use an Internet domain name as a prefix. For example, for a company with a domain name xcompany. com, the prefix would be COM. xcompany. The use of uppercase letters in the first part of the name further reduces the risk for name conflicts. Regarding the Modelica Association having the domain name modelica. org, this kind of package prefix becomes ORG. modelica. For example, the Mechanics part of the Modelica standard library could be denoted: ORG.modelica.library.Modelica.Mechanics
Package names can become quite long using this method, but it is relatively safe against name conflicts. No one else using this scheme will take the same name as us, and for those who do not follow these
Chapter 10 Packages 339 conventions it is very unlikely that they will choose the first part of the name containing only uppercase letters.
10.3.2 Subpackages and Hierarchical Libraries The main use for Modelica packages and subpackages is to structure hierarchical model libraries, of which the standard Modelica library is a good example. Below is a small example of a hierarchical package structure which has been extracted and adapted from the Modelica standard library. We have taken the liberty of making all subpackages encapsulated, which corresponds to good software engineering practice. This library consists of a number of subpackages like Modelica.Blocks, Modelica.Mechanics, Modelica. Electrical, etc., which in tum usually are divided into subpackages to an appropriate level. The Modelica. Mechanics subpackage is divided into subpackages corresponding to different kinds of mechanical model components e.g., rotational components are in Modelica. Rotational, translational components in Modelica. Translational, etc. The example is a bit misleading since these packages are quite large and are normally stored on separate files and directories and not seen as a single piece of code as below. The fully qualified names of each package or model component are shown as comments, encapsulated package Modelica encapsulated package Mechanics encapsulated package Rotational model Inertia
II II II
Modelica Modelica.Mechanics Modelica.Mechanics.Rotational
II
Modelica.Mechanics.Rotational.Inertia
II
Modelica.Mechanics.Rotational.Torque
end Inertiai model Torque end Torque;
end Rotational; end Mechanics; end Modelica;
Public components in hierarchical libraries can be accessed through their fully qualified name. As pointed out previously, the Modelica standard library is always available for use, e.g., as in the contrived model InertiaUser below, where we instantiate an Inertia component where the type is directly referred to by its fully qualified name Modelica. Mechanics. Rotational. Inertia. model InertiaUser
Modelica.Mechanics.Rotational.Inertia
Wi
end InertiaUser;
10.3.2.1 Encapsulated Packages and Classes An encapsulated package or class for example, the model TorqueUser below, prevents direct reference to pub1 i c definitions outside itself, but as usual allows access to public subpackages and classes inside itself. Instead used packages from outside must be imported. As we have already emphasized in the preceding sections and examples, this is standard practice for packages in order to eliminate the possibility of implicit dependencies. However, sometimes it is also useful to have encapsulated models where there is no danger of implicit dependencies, e.g., application examples that are intended to be selfconsistent and might be sent around to other users and developers.
340 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
encapsulated model TorqueUserExamplel import Modelica.Mechanics.Rotational; II Import package Rotational Rotational.Torque t2; II Use Torque, OK! Modelica.Mechanics.Rotational.Inertia w2; IIError! No direct reference II to outside an encapsulated class end TorqueUserExamplel;
10.3.2.2 Name Lookup in Hierarchically Structured Packages Name lookup in a hierarchical package structure follows the same rules as for general name lookup in (nested) Modelica classes that are described in Section 3.13.1 on page 96 in Chapter 3. Since you might find that description rather detailed and technical, it can be useful to point out the main issues of name lookup in package structures. A name to be looked up consists of one or more parts e.g., Modelica. Blocks. Interfaces consists of the three parts Modelica, Blocks, and Interfaces. The first part of the name in this case is simply Modelica. The procedure for lookup of such a name consists of the following phases: •
• •
Search for the first part of the name until it is found, starting in the innermost scope and upward recursively through the package and class hierarchy until we reach the top or an encapsulated package or class boundary. If not found, search. the roots of other package hierarchies in the MODELICAPATH (see Section 10.3.4 in this chapter); otherwise, if not found, it is an error "missing declaration." If the first part of the name matches an import statement, locate the corresponding imported package or definition. Locate the rest of the name, if necessary, within the found package, class, or other kind of definition.
We apply this lookup algorithm for the lookup of Interfaces. Flange_a in the declaration of al within the model Inertia in the package hierarchy below. Note that Inertia is declared within the package Modelica. Mechanics . Rot.at.LonaL We search for the first part of the name, which is Interfaces, and find it declared within the same package i.e., within Rotational. The rest of the name i.e., Flange_a, is subsequently found as a connector class declared within Interfaces.
encapsulated package Modelica encapsulated package Blocks encapsulated package Interfaces
II Modelica II Modelica.Blocks II Modelica.Blocks.lnterfaces
end Interfaces; end Blocks; encapsulated package Mechanics II Modelica.Mechanics encapsulated package Rotational II Modelica.Mechanics.Rotational import Modelica; II Import Modelica encapsulated package Interfaces II Modelica.Mechanics.Rotational.Interfaces connector Flange_a II Define Modelica.Mechanics.Rotational.Interfaces.Flange_a end Flange_a; end Interfaces; model Inertia Interfaces.Flange_a al; II Use Modelica.Mechanics.Rotational.lnterfaces.Flange_a Modelica.Mechanics.Rotational.Interfaces.Flange_a a2; II Same type
Chapter 10 Packages 341 end Inertia;
end Rotational; end Mechanics; end Modelica; The declaration of a2 uses the same connector class Flange_a as a t, but the lookup is a bit different since it refers to Modelica. Mechanics. Rotational. Interfaces. Flange_a. The first part of the name in this case is Modelica, which is found in the import statement import Modelicai before hitting the boundary of the encapsulated package Rotational. The rest of the name, i.e., Mechanics. Rotational. Interfaces. Flange_a, is located within the found Modelica package by searching from the root and downward. First r~echanics is located within Modelica, then Rotational is located within Mechanics, then Interfaces is located within Rotational, and finally Flange_a is found within Interfaces.
10.3.3 Mapping Package Structures to a Hierarchical File System Packages and classes are usually stored in a file system, or sometimes, but this is less common, in a database. Modelica defmes a mapping that unambiguously locates the storage place of a package or class from its fully qualified name. This gives us the following advantages: • •
From its fully qualified name we can easily find the file and directory where the definition of a package or class is stored, e.g. when you need to edit it. The Modelica environment can automatically locate and load referenced packages and classes from the file system into the simulation environment when needed.
A package can be stored either as a file or as a directory, whereas classes are stored either as separate files or as part of a package file. This gives more flexibility than the related storage scheme for Java where classes are always stored on separate files and packages are always represented by directories. 10.3.3.1 The within Statement The Modelica syntax does not allow a package or class to use its fully qualified name with dot notation when declaring the package or class in question, e.g. on a separate file or storage unit. Therefore the within statement has been introduced, which states the prefix needed to form the fully qualified name, and thereby provides a "unique" identification of the declared package or class. Note that the wi thin statement is effective only for a package or class stored at the corresponding place in the package hierarchy, i.e., it cannot be used to introduce a modified package or class without actually storing it. The wi thin statement has the following syntax: within <packageprefix>i
For example, thesubpackage Rotational declared within Modelica . Mechanics has the fully qualified name Modelica. Mechanics. Rotational, which is formed by concatenating the packageprefix with the short name of the package. The declaration of Rotational is given below as it appears stored on a file: within Modelica.Mechanicsi encapsulated package Rotational encapsulated package Interfaces import ... ; connector Flange_a;
II Modelica.Mechanics.Rotational
342 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica
end Interfaces; model Inertia end Inertia; end Rotational;
Note that a wi thin statement always appears first in a file containing a package or class declaration.
10.3.3.2 Mapping a Package Hierarchy into a Directory Hierarchy A Modelica package hierarchy can be mapped into a corresponding directory hierarchy in the file system. The most visible part of this mapping is the translation of package or class names into similar or identical directory or file names. A package can be stored either as a directory or as a file: •
•
•
A package can be stored as a directory with the same short name as the package. This directory must contain a file named package. rna which starts with a wi thin statement (see the previous section), and a (possibly empty) declaration of the package in question, e.g. "encapsulated package Modelica end Modelica;" exemplified by the package Modelica. The file package. mo typically contains documentation and graphical information for the package but may also contain import statements and declarations of constants and classes in the package. The classes or subpackages in a package mapped as a directory are usually stored as their own files or subdirectories within this directory. Such files or subdirectories must not correspond to classes or packages with identical names, e.g. there should not be a file Rotational. rno and a subdirectory Rotational within the same directory. A package or class can be stored as a file with the same short name as this package or class, and with the extension. mo. This file must start by a within statement (see above), stating where the package or class belongs. A class or subpackage can of course also be stored within some package file.
In order to give the reader some visual intuition about this mapping, a small part of the Modelica standard library is depicted below, both graphically as a package hierarchy, and as an example. file directory hierarchy using directory syntax from Microsoft Windows file systems. It appears almost the same using Unix or Linux, just replace backslashes with slashes and remove "c :". The packages Modelica, Blocks, Examples, and Mechanics are all represented as directories containing the required file package. mo. The packages Continuous, Interfaces, and Rotational are stored as the corresponding files Continuous. mo, Interfaces. mo, and Rotational. mo. The class Examplel is stored in its own file Examplel. mo within the package subdirectory Examples. In this example, the directory corresponding to the root package Mode1 i ca happens to be placed within the directory c. \library. A root directory such as Modelica can be placed anywhere-the system will be able to find it through the MODELICAPATH as explained in the next section.
Chapter 10 Packages 343 Directory
and file structure:
c. \library \Modelica package.mo \Blocks package.mo Continuous.mo Interfaces.mo \Examples package.mo Examplel.mo \Mechanics package.mo Rotational.mo
Modellca
Continuous
Interfaces
Above we show the contents and names of a few files resulting from this mapping. First is the file package. rna within the root package directory C: \ library\Modelica. It contains an empty Modelica package declaration since all subpackages under Mode1 i ca are represented as subdirectories of their own. The empty within statement can be left out if desired. File: Contents:
C:\library\Modelica\package.mo within; encapsulated package Modelica end Modelica;
"Modelica root package";
Below is the file package. mo in the directory c. \library\Modelica\Blocks\Examples that stores the Examples package. It might be convenient to place import statements in the package declaration that can be used by example classes like Examplel that are stored as separate files in the directory. C:\library\Modelica\Blocks\Examples\package.mo File: Contents: within Modelica.Blocks; encapsulated package Examples "Examples for Modelica.Blocks"; import end Examples; •••
I
Here is the class Examplel stored in a separate file Examplel . mo. File: Contents:
C:\library\Modelica\Blocks\Examples\Examplel.mo within Modelica.Blocks.Examples; model Examplel "Usage example 1 for Modelica.Blocks";
...
end Examplel;
Finally we ShO'N the subpackage Rotational stored as the file Rotational. mo. Note that Rotational contains the subpackage Interfaces, which also is stored in the same file since we chose not to represent Rotational as a directory. File: Contents:
C:\library\Modelica\Mechanics\Rotational.mo within Modelica.Mechanics; encapsulated package Rotational
II Modelica.Mechanics.Rotational encapsulated package Interfaces
344 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica import ... ; connector Flange_a;
end Interfaces; model Inertia end Inertia;
end Rotational;
10.3.3.3 Mapping a Package Hierarchy or Class Into a Single File A complete package hierarchy can be stored as a single file according to the rules described in the previous sections. It is possible, but not very common, to store the whole Modelica standard library as a single file as shown in the example below. One reason could be to package a special version of the standard library into a file that can be easily distributed to other users, e.g. for debugging purposes. C:\lib3\Modelica.mo File: Contents: within ; encapsulated package Modelica encapsulated package Blocks
...
end Blocks; encapsulated package Mechanics
...
end Mechanics;
...
end Modelica;
Below is a small application model that refers to the Inertia class in the Rotational subpackage of the above Modelica standard library. It does not contain a within statement since it is not placed within any package. First it has to be loaded into the Modelica environment in order to be used. C:\applications\InertiaUser.mo File: Contents: model InertiaUser Modelica.Mechanics.Rotational.lnertia
...
W;
end InertiaUser;
10.3.4 The Modelica Library Path-MODELICAPATH The Modelica environment has an unnamed top-level scope which contains classes and packages that have been loaded into the Modelica workspace. Models to be simulated can refer to such classes or packages since they can be accessed through the normal lookup rules. For classes with version information, see also Section 11.5.1, page 371.
Chapter 10 Packages 345 However, Modelica also provides a facility to access libraries stored externally as package hierarchies. This facility is called the MODELICAPATH, which on a typical computer system is an environment variable containing a string with a semicolon-separated ordered list of names of directories where package hierarchies corresponding to Modelica model libraries are stored. If during lookup a top-level name is not found in the unnamed top-level scope, the search continues in the package hierarchies stored in these directories. Figure 10-1 shows an example MODELICAPATH = "C:\library; C:\libl; C:\lib2", with three directories containing the roots of the package hierarchies Modelica, MyLib, and ComplexNumbers. The first two are represented as the subdirectories C:\library\Modelica and C:\libl\MyLib, whereas the third is stored as the file C:\lib2\ComplexNumbers.mo.
C:\library Modelica
,/ ...~leclriCal
Pack1 Pack2
Translational
Figure 10-1. Roots of package hierarchies,e.g., Modelica, MyLib, and ComplexNumbers in MODELICAPATH = "C:\librarYi C:\lib1i C:\lib2". Assume that we want to access the package MyLib. Pack2 in Figure 10-1 e.g. through an import statement import MyLib. Pack2 ;. During lookup we first try to find a package MyLib corresponding to the first part of the import name. It is not found in the top-level scope since it has not previously been loaded into the environment. Since the name was not found in the top-level scope the search continues in the directories in the MODELICAPATH in the specified order. For the search to succeed, there must be a subdirectory MyLib or a file MyLib. rno in one of the directories mentioned in the MODELICAPATH. If there is no such subdirectory or file, the lookup fails. If MyLib is found in one of the directories, the rest of the name, in this case Pack2, is located in MyLib. If that fails, the entire lookup fails without continuing the search in possibly remaining directories. In this example the name matches the subdirectory named MyLib in the second directory "C: \ Ld.b.l," mentioned in the MODELICAPATH. This subdirectory must have a file package. mo containing a definition of the package MyLib, according to the Modelica rules on how to map a package hierarchy to the file system. The subpackage Pack2 is stored in its own subdirectory or file in the subdirectory MyLib. In this case the search succeeds and the package MyLib . Pack2 is loaded into the environment.
10.3.5 Packages versus Classes In the preceding sections we have mostly discussed various properties of packages. In fact, many of these properties also apply to classes in general, e.g. the possibility of mapping to storage places such as directories or files in the file system. This follows from the fact that a package is largely a restricted form of class in Modelica, apart from the property of being imported from. This does not imply that we should use classes instead of packages just because there are few restrictions in Modelica. Use packages for libraries and coarse-grained structuring of systems, and classes for models and model components.
346 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica
10.4 Package Variants and Operations In the following sections we will examine certain variants of packages that can be created through operations such as instantiation of generic packages, inheritance of packages, and manual editing. In addition we will examine two special types of packages local packages and nonencapsulated packages, as well as their usage and some associated inherent problems.
10.4.1 Generic Packages Generic packages are packages with some kind of formal parameter, e.g. a replaceable type. They are really a special case of parameterized generic classes described in Section 4.4 on page 133, where several examples of parameterized models are given. In the beginning of this chapter we presented the view of a package as an abstract data type containing a data structure with associated operations. Generic packages can often be regarded as parameterized abstract data types, e.g, the package GeneralStack below, which is parameterized in terms of the type of the elements in the stack-the type parameter Element. This example is rather algorithmic in contrast to the parameterized generic models presented in Chapter 4. package GeneralStack replaceable class Element end Element; record Stack parameter Integer maxsize 0; Integer size = 0; Element [maxsize] vee; end Stack; function Push input Stack si; input Element ei output Stack so; algorithm so := si; so. size := so.size+l; so.vec[so.sizel .- ei end Push; function Pop input Stack output Stack
si; SOi
algorithm so := si; so. size := so.size-l; end Pop; function Top input Stack si; output Element e;
algorithm e := si.vec[si.size]; end Top; end GeneralStacki
By "instantiating" the package GeneralStack with different values of the type parameter Element we can create specialized stack packages containing elements of a specified type. This is a different meaning of instantiation compared to our previous use of the term for creating data instances from classes. In this
Chapter 10 Packages 347 case instantiation means the creation of a more specialized package. For example, below we have instantiated GeneralStack with a type argument Integer creating the specialized stack called IntegerStack, and with Real giving the stack RealStack. package IntegerStack
GeneralStack(redeclare type Element
Integer);
package RealStack
GeneralStack(redeclare type Element
Real);
Finally, the package IntegerStack is used in the class IntStackUser into which it is imported. A stack with room for a maximum of two hundred integers is allocated. Some stack operations are performed such as pushing three numbers on the stack, getting the top element, and popping the top element. class IntStackUser import IS = IntegerStack; IS.Stack stk(maxsize = 200) i Integer item; algorithm stk .- IS.Push(stk,35)i II Push three numbers on the stack stk .- IS.Push(stk,400); stk .- IS.Push(stk,44); item .- IS.Top(stk); II Get the top element, i.e. 44 stk .- IS.Pop(stk); II Pop the top element from the stack end IntStackUser;
10.4.2 Inherited Packages Since packages are restricted and enhanced classes they can be inherited and specialized in the same way as classes in general. For example, a double-ended queue, sometimes called deque, is an (abstract) data type that combines the actions of a stack and a queue. To create a package for this data type, we can inherit all stack operations together with the data structure declaration Element from GeneralStack, and add operations to insert, remove, and access a data element at the other end of the stack/queue, i.e. at the bottom, as in the example package DoubleEndedQueue below. encapsulated package DoubleEndedQueue
"Combined stack and queue"
extends GeneralStaek; function AddBottom "Add element at the bottom / the end" input Stack si; input Element e; output Stack so; algorithm so. size := si.size+l; for i in l:si.size loop so. vee [i+l] : = si. vee (i] end loop; so.vec[l] := e; end AddBottom; function RemoveBottom "Remove element at the bottom input Stack Sii output Stack so; algorithm so. size := si.size-l; for i in l:so.size loop so.vec[i] := si.vec[i+l] end loop; end RemoveBottomi function Bottom input Stack
"Get bottom element" Sii
I
the end"
348 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica output Element e; algorithm e := si.vec[l]; end Bottom; end DoubleEndedQueuei
Below is an "instantiation" of the double-ended queue together with a small usage example. Two integers are inserted at the beginning of the queue and one integer at the end of the queue. Then the end element is accessed and the first element is removed. package IntDeQueue = DoubleEndedQueue(redeclare type Element class DeQueueUser import 10 = IntOeQueuei ID.Stack q(maxsize = 200); Integer item; algorithm q .- ID.Push(q,6S); II q := ID.Push(q,500); q := ID.AddBottom(q,455) II item := ID.Bottom(q); II q := ID.Pop(q); II end DeQueueUser;
=
Integer);
Insert two numbers at the beginning Insert at the end of the queue Get the end element, i.e. 445 Remove the first element from the queue
10.4.3 Local Packages A local package in Modelica is simply a package that is declared directly inside a class that is not a package. This is in contradiction to the usual role of packages as coarse-grained independent structuring units. However, there are situations where it can be convenient to have access to a local package which has been adapted to the specific needs within a certain model. For example, in the model MyCircuit below we use a local specialized version of the package Electrical. Components which is parameterized in terms of the type ResistorModel being replaced by the local type MyResistorModel in MyCircuit. Several classes from this local package MyComponents are subsequently used for instantiating variables. model MyCircuit model MyResistorModel extends Electrical.lnterfaces.ResistorModel; II My special declarations and equations end MyResistorModel; encapsulated package MyComponents = Electrical.Components(redeclare ResistorModel
MyResistorModel)i
MyComponents.Transformer trl MyComponents.Transducer td2; end MyCircuit;
In a similar way the class DeQueueLocalUser below uses the local package P that is a version of the package DoubleEndedQueue from the previous section parameterized by the local type VerySecret. class DeQueueLocalUser protected type VerySecret = Integer; package P = DoubleEndedQueue(redeclare type Element VerySecret); P.Stack q(maxsize = 200); Integer item; algorithm q .- P.Push(q,65)i II Insert two numbers at the beginning
Chapter to Packages 349 q
:=
q
:=
P.Push(q,SOO)i P.AddBottom(q,455) II Insert at the end of the queue item := P.Bottom(q); II Get the end element, i.e. 445 q := P.POp(q)i II Remove the first element from the queue end DeQueueLocalUseri
10.4.4 Nonencapsulated Packages A nonencapsulated package is a package declared without the prefix encapsulated. Such a package has the disadvantage of being implicitly dependent on packages in the environment through nested lookup, as discussed in the next section. However, there is one case where nonencapsulated packages are useful. Large encapsulated packages containing protected declarations can internally be structured into nonencapsulated subpackages. This is the only way protected declarations of a parent package can be accessed by subpackages since declarations imported into encapsulated subpackages have to be publ ic. For example, below the encapsulated package Blocks has been internally structured into three nonencapsulated packages Interfaces, Continuous, and Examples that all can access the protected type MySecret. encapsulated package Modelica encapsulated package Blocks protected type MySecret = 000; public package Interfaces end Interfaces; package Continuous MySecret Xi end Continuous package Examples end Examples; end Blocks; end Modelica;
It might be argued that it is against the principle of information hiding and the concept of packages as independent code units to let other packages access protected variables. This is true, but the damage is hopefully limited if nonencapsulated packages are seldom used and used only for internal structuring of large packages, at most one level down in the package hierarchy. You might think that nonencapsulated packages are more convenient than encapsulated ones since one avoids some typing, i.e., the keyword encapsulated and certain import statements. However, this is not true in general, since experience shows that people spend much more time reading code than writing it, and implicit dependencies implied by nonencapsulated packages makes the code harder to understand.
10.4.4.1 Problems with Nonencapsulated Packages We have already noted that nonencapsulated packages may create problems of understanding and maintaining code. This is caused by implicit dependencies on declarations in the environment. The usual nested lookup rules for classes apply to nonencapsulated packages and classes, rather than explicit, easily visible, import dependencies. In fact, in order to find a name used in a nonencapsulated package we may have to do the following:
350 PeterFritzson Principles of Object-Oriented Modeling and Simulationwith Modelica • •
Visually scan the whole source code of the current package, which might be quite large. Search through all packages containing the current package, i.e. higher up in the package hierarchy, since standard nested lookup allows used types and other definitions to be declared anywhere above the current position in the hierarchy. This amount of code is even larger.
The following example consisting of three levels of nested nonencapsulated packages illustrates these problems: package MyModelica package Mechanics package Rotational model Inertia MyType X; end Inertia; end Rotational; end Mechanics; package Blocks end Blocks; end MyModelica;
The type MyType used inside the Inertia model can be declared anywhere within the package Rotational, the package Mechanics, or the package MyModelica, or be one of the classes already loaded into the current workspace.
10.4.5 Moving Packages Copying or moving a nonencapsulated subpackage such as MyModelica. Mechanics. Rotational in the above example might be a bit problematic since used declarations, e.g. MyType declared in MyModelica, may not be available in the new location for Rotational, if for example we place it within the package YourModelica that probably lacks MyType. The situation is much better for encapsulated (i.e., self-contained) packages since all dependencies are explicit through import statements: •
When copying or moving an encapsulated package or class, at most the import statements inside this package or class, including subpackages and local classes, need to be updated.
The reason this works is that lookup stops at the package or class boundary for encapsulated packages and classes, and all internal references to declarations in other packages and classes are via import statements. In the example below, the subpackage Modelica. Blocks. Interfaces is imported into Rotational, which uses Interfaces. InPort: encapsulated package Modelica encapsulated package Blocks encapsulated package Interfaces connector InPort end InPort; end Interfaces; end Blocks; encapsulated package Mechanics encapsulated package Rotational import Modelica.Blocks.lnterfaces; model Torque
Interfaces.lnPort inPort;
II Import II Use
Chapter to Packages 351 end Torque; end Rotational; end Mechanics; end Modelicai
If we move the package Rotational inside YourModelica as below, it will continue to work without changes since its import statement still refers to Modelica. Blocks. Interfaces. If we would like it to instead refer to the package YourModelica. Blocks. Interfaces, just update the import statement as we have done below: encapsulated package YourModelica encapsulated package Blocks encapsulated package Interfaces connector InPort
end InPort; end Interfaces; end Blocks; encapsulated package Mechanics encapsulated package Rotational import YourModelica.Blocks.lnterfaces; model Torque
Interfaces.InPort inPort;
II Updated import II Use
end Torque; end Rotational; end Mechanics;
end YourModelica;
10.5 A Comparison Between Java and Modelica Packages You might find it useful to do a brief comparison between the Java package concept and the Modelica counterpart. The Java package concept is without question currently the best-known package concept, and the Java programming language is taught in many, perhaps the majority, of introductory programming courses around the world. It might be the case that you have been acquainted with the Java language before learning Modelica. The Modelica package concept has been considerably influenced by Java-it can almost be considered as a superset of the corresponding Java concept. There are a number of differences between the two concepts with regard to the following aspects: • • • • • • • •
Import Subpackages Encapsulation and independence of packages Local packages Inheritance of packages Lookup Mapping to the file system Identification of packages
We briefly compare and discuss each of these aspects.
352 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
10.5.1 Import Java has two forms of import statement: single definition import and unqualified import, whereas Modelica also provides qualified import of whole packages and renaming import.
10.5.2 Subpackages Java packages are always "independent" entities. Even a subpackage in Java has to be explicitly imported or its definitions referenced by their fully qualified names in order to be used within its parent package or by some other package. The subpackage relation is just a relation between the names of two packages and an organizational tool for storage in the file system, e.g. java . lang . reflect is a subpackage of java. lang, but this does not imply any special access rights between those packages. By contrast, a nested subpackage in Modelica can actually be placed inside its parent package and can in its nonencapsulated form use nested lookup for access of definitions in its parent package or higher up in the hierarchy. This may create implicit dependencies between packages, e.g. Modelica. Blocks. Interfaces may implicitly use definitions in Modelica. Blocks. Encapsulated Modelica packages are close to the Java notion of packages as independent entities. In fact, an encapsulated Modelica package is somewhat more "independent" and "encapsulated" than a corresponding Java package, since all use of other packages declared outside itself must be via import statements. Direct use of definitions via fully qualified names is not allowed in that case in Modelica. This makes package dependencies very clear. However, a Modelica package can use definitions declared in its own subpackages without import, e.g. code in Modelica. Blocks, which can use definitions in Modelica. Blocks. Interfaces without explicit import.
10.5.3 Encapsulation and Independence of Packages Java packages are more independent than Modelica packages in the sense that no other Java package, not even a subpackage, can access protected or private definitions of a Java package. A nonencapsulated Modelica subpackage may access protected definitions in its parent package-there is no way a parent package can prevent that. On the other hand, an encapsulated Modelica package always requires import for access of definitions in other packages that are not subpackages. Therefore such MOOeHca package dependences become cleaner and more visible than in Java where direct references using fully qualified names of definitions in other packages often occur.
10.5.4 Local Packages Local packages are packages that are declared inside a class and not directly inside a package. Such packages are allowed in Modelica but are disallowed in Java and most other programming languages.
10.5.5 Inheritance of Packages Modelica packages can be specialized and extended through inheritance, whereas Java packages cannot. Using inheritance on packages can be quite useful and encourages reuse, as we saw in the example where a stack was extended to become a double-ended queue.
Chapter 10 Packages 353
10.5.6 Lookup In Java there are only two modes of lookup of definitions from other packages: lookup via import statements or lookup through directreferences using fully qualified names. The Modelica package concept supports both of those mechanisms. Additionally, in Modelica nested lookup is possible from nonencapsulated packages. Also, definitions in subpackages can be used or imported without giving fully qualified names. Thirdly, local packages can be defined inside classes in Modelica, which is not allowed in Java.
10.5.7 Mapping to the File System Java has a simpler convention for mapping packages and classes to storage places in the file system, whereas Modelica's mapping gives increased flexibility. In fact, the Modelica mapping is approximately a superset of the Java mapping. A Java class is always mapped to a file and Java packages to different levels of directories corresponding to the dot notation in the package name, e.g. java. utile Date is mapped to a two-level directory structure such as C: \java\util \ containing the file Date. j with the class Date. In Modelica we have the choice of either mapping each class to a separate file as in Java, or storing whole packages including all their classes, and possibly subpackages, on a single file. For example, the Modelica. Blocks. Interfaces might be stored on the single file package C:\Modelica\Blocks\Interfaces.rno, be part of some file, e.g. C:\Modelica\Blocks.mo, or be represented as the directory C:Modelica\Blocks\Interfaces\ containing a number of files, one for each class.
10.5.8 Identification of Packages This property concerns the ability to (unambiguously) identify a class or package from its declaration, e.g. as stored on a file. A Java class file always contains a package statement that identifies which package the class belongs to and in which directory it is stored in the file system. For example, the Java class Bi tSet in the package java. ut i 1 can be declared on a file as follows: package java.util; class BitSet {
A corresponding declaration in Modelica with the Util package represented as a directory and BitSet as a file Bitset. rna could be: within Modelica.Util;
II The file BitSet.mo
class BitSet end BitSet;
If the Ut i 1 subpackage is instead represented as a whole file Ut i 1 . mo, we will have: within Modelica; II The file Util.mo package Utili class BitSet end BitSet;
354 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
end Utili
10.5.9 Remarks The MOOeHca package concept is an improvement over the Java package concept by being more flexible and powerful. On the other hand, the Java concept is simpler-simplicity versus power. It is almost the case that the MOOeHca package concept is a superset of the Java concept The Modelica import mechanism is more convenient and solves some problems often caused by unqualified import in Java. The file mapping algorithm in Modelica is slightly more complicated but gives possibilities for better structuring. by allowing the grouping of classes, and even subpackages, on the same file in addition to the usual directory mapping. The concept of nonencapsulated packages in MOOeHca can provide some increased flexibility in internal structuring of encapsulated packages, but can on the other hand easily be misused to create package structures and hierarchies with many implicit dependencies that are hard to understand and maintain. This matter to some extent depends on personal taste, but if we want to keep most of the simplicity and style of Java packages and still get the advantages of MOOeHca packages, the following coding conventions might be a good compromise: • •
•
Avoid unqualified import and use the increased possibilities of qualified and renaming import in Modelica. Always use encapsulated packages with explicit import of used packages even including subpackages. The extra typing will be paid off by increased readability through easily visible and unambiguous package dependencies. Avoid the use of nonencapsulated packages if there are not very strong reasons to use them.
Remember that saving a few keystrokes of typing is not the most important factor. Experience has shown that code is read approximately 10 times more often than written. Structuring our models in a way that reduces complexity is one of the most important design goals, for which the package mechanism is a quite valuable tool.
10.6 Summary This chapter is devoted to the Modelica package concept, which is used for constructing libraries of reusable model definitions. We started by discussing packages as abstract data types, followed by a description of different mechanisms for accessing packages and importing definitions from packages. We also described the structuring of packages and libraries, as well as the notion of encapsulated packages and classes. The mapping of package structures to a hierarchical file systems was described, as well as the Modelica library path for searching externally stored package hierarchies. We presented generic packages, inherited packages, local packages, and nonencapsulated packages. Finally, the chapter was concluded by a comparison between the Java and Modelica package concepts.
10.7 Literature Further reading on the topic of abstract data types and their relation to the module and package concept can for example be found in (Louden 1993).A classic article on information hiding is (Parnas 1972). The package presentation briefly relates to the Modelica language specification (Modelica Association 2003), but with a substantially expanded explanatory text. The example of a package structure has been adapted from the Modelica. Mechanics. Rotational example in (Modelica Association 2000) and the
Chapter 10 Packages 355 corresponding part of the Modelica standard library. The comparison between Modelica packages and
Java packages relates to the Java package presentation in (Arnold and Gosling 1999) concerning the Java language.
10.8 Exercises Exercise 10-1:
Question: Packages are nice to use in Modelica, but what exactly is a package? Why use the word encapsulated when creating packages? Exercise 10-2:
Creating a Package: Create a package that contains a constant PI, a type Distance, a function RectangleArea, a function TriangleArea, a function CirclePerimeter, and a function CircleArea. Write a class, GeometryUser, that uses the package and calls the functions.
Exercise 10-3: Question: What is important to consider before designing a package? Exercise 10-4: Question: There are different kinds of packages. What is a generic package? What is a local package? Is there something called a nonencapsulated package? If so, explain it. Why might it be a problem to move packages? Exercise 10-5: Question: Is it really possible to inherit packages? Inheriting Packages: Inherit the package Geometry into a class GeometryUser, which is calling functions from Geometry. class GeometryUser end GeometryUser;
package Geometry constant Real PI = 3.1415926536; type Distance = Real(unit = "m"); function RectangleArea input Distance B; input Distance H; output Distance area; algorithm area := B*H; end RectangleArea; function TriangleArea input Distance B; input Distance Hi output Distance area; algorithm area := RectangleArea(B, H)/2; end TriangleArea; function CirclePerimeter input Distance radius;
356 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica output Distance perimeter; algorithm
perimeter := 2*PI*radius; end CirclePerimeter; function CircleArea input Distance radius; output Distance area; algorithm
area := PI*radius A2; end CircleArea; end Geometry;
357
Chapter 11
Annotations, Units, and Quantities
This chapter presents some additional constructs and attributes that are not really part of the Modelica core language but still belong to Modelica in a broad sense, and therefore are part of the Modelica language definition. Here we will present the foUowing features: • •
Annotations Units and quantities
What is an annotation? It can be understood as an attribute or property containing information associated with some element of a Modelica model. Examples are model documentation and graphical layout information concerning icons and connections associated with models. This is needed, e.g. by graphical connection editors used to combine Modelica model components. The graphical view usually makes models easier to understand as we have seen in many examples earlier in this book. The Modelica annotation construct is similar to the concept of pragma known from the Ada programming language. It has the following syntactic structure:
annotation tannotationelementsi where annotationelements is a comma-separated list of annotation elements that can be any kind of expression compatible with the Modelica syntax. In the rest of this chapter we will present a number of predefined standard annotations that should be recognized by Modelica environments. Below is an example of an annotation containing information about the graphical layout of an icon representing a resistor model:
model Resistor! annotation(Icon(coordinateSystem{extent={{-120,-120},{120,120}}), graphics = ( Rectangle (extent= [-70, -30; 70, 30], fillPattern=FillPattern.None), Text (extent= [-100, 55; 100, 110], textString="lname=tR"), Line(points=[-90, 0; -70, 0]), Line (po i nt.s e l zo , 0; 90, 0]) } ) ) ;
end Resistorl; The annotation in this example has the name I con and contains instances of the graphical annotation elements Rectangle, Text, Line, etc. The whole annotation is expressed using Modelica modifier syntax. Neither the majority of annotations (except a few) nor the above-mentioned units and quantities are supposed to influence the simulation of a Modelica model. Apart from some exceptional cases such as the external function arrayLayout annotation described in the following, one should be able to remove both annotations and unit and quantity information from a model and rerun the simulation of the model without any change of results. Annotations are needed primarily by tools such as programming environments for Modelica, which access the annotation information associated with models. A typical example of a tool in a Modelica environment is the already-mentioned graphical connection editor, which reads the model together with
358 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica graphical annotations about the layout including icons and arrows, allows the user to graphically edit the model, and saves the edited result, including possibly changed values of the annotations. The usual strong type checking of Modelica models is not applied to annotations. This is motivated by the fact that annotations are automatically generated and read by tools, and not manually edited by humans. Therefore the information is presumably correct. Another reason for avoiding type checking in this case is to make it simple for tools to support and extend their own annotation notation without undue constraints. Apart from annotations, the rest of this chapter deals with the topic of units and quantities. The uni t attribute of a variable can be seen as some kind of more precise type information, whereas the quantity attribute defines the physical category of the variable, like Length, Mass, and Pressure. Several units are possible for the same quantity, e.g. a variable measuring Length could have one of the units "m" (meter), "rnrn", or "km", A Modelica tool is not required to do any unit analysis based on the unit information, Certain tools may offer dimension analysis, including unit checking, which is an analysis related to type checking that may help the user to find certain modeling errors based on inconsistent use of quantities and units, e.g. in equations or expressions.
11.1 Standard Annotations In order to maintain portability of models, all Modelica tools should recognize a minimum set of annotations, i.e., the annotations described in this chapter. All Modelica tools are free to add their own annotations, but other tools may not recognize these. However, all tools are able to parse annotations of any kind since they follow the Modelica modifier syntax, including attribute values that are Modelica expressions. The following are the names of the predefined standard Modelica annotations, annotation elements, and annotation attributes, to be described in more detail in subsequent sections. First we show the standard annotation names: Documentation, Icon, Diagram, choices, derivative, arrayLayout
The following predefined graphical annotation elements are typically used within the graphics attribute of Icon or Diagram annotation elements: Line, Polygon, Rectangle, Ellipse, Text, BitMap
A few additional graphical annotation elements: Placement, transformation, iconTransformation
11.2 Annotation Syntax and Placement The syntax of a Modelica annotation is the keyword annotation followed by a parenthesized commaseparated list of elements. These elements have the same syntax as MOOeHca modifiers. There are two kinds of annotation elements: • •
Simple annotation elements. Redeclaration annotation elements.
Simple annotation elements have the same syntax as simple modifiers described in more detail in Section 11.2.1, and redeclaration annotation elements comply with the syntax of redeclaration modifiers described in Section 11.2.2. Both forms of annotation elements can be nested to any level.
Chapter 11 Annotations, Units, and Quantities 359
11.2.1 Simple Annotation Elements An annotation with simple annotation elements consists of pairs associating a name with an expression, e.g. according to the following structure where possible prefixes and other details are left out: annotation(namel = exprl, name2 = expr2, ... )
An example de r i vat i ve annotation containing a simple annotation element: annotation (derivative=fool) ; Annotations can be nested to any level. The following is a common structure for two-level simple annotations: annotation{name{namel = exprl, name2 = expr2, ... ), ... )
Here is an example of a two-level simple annotation called choices, where the element.s on the second level contain string comments that can be used by tools to generate menu altemati ves: annotation(choices(choice=l "P", choice=2 "PI", choice=3 "PID"));
11.2.2 Redeclaration Annotation Elements Annotation elements also can be structured as redeclarations, e.g. as in the example structure below containing a redeclaration of a class: annotation (name (redeclare class ClassName field]; field2 ; end ClassName, ... » Type] Type2
It is more common to use redeclarations with short class definitions, e.g.: annotation (Namel (Name2 (redeclare class Name3 = Name2,
... ))
He is an example of a level-three nested choices redeclaration annotation using short class definitions in the redeclarations: annotation (choices ( choice(redeclare MyResistor=lib2.Resistor(a={2}) n ••• n), choice(redeclare MyResistor=lib2.Resistor2 " ... "»));
Redeclaration annotations also can be like variable declarations: annotation (name (redeclare Type] variablel t i ,
11.2.3 Class Annotations A class annotation contains information associated with a class. One or more class annotations may be placed as elements anywhere among the list of elements in a long class declaration. Remember that the class can contain elements such as local classes, variable declarations, import statements, extends statements, equation sections, and algorithm sections. For example here is a Documentation annotation inside a long class declaration:
annotation (Documentation (info <element] > ; «elements» ;
" ... n»
360 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica end
;
This also can be used to attach documentationinformation to a package: package Modelica annotation(Documentation(info
= " ... "»
end Modelica;
The Resistor2 example below illustrates that annotation elements can occur anywhere among the list of elements in a class. The public keyword is used to end the equation section before starting the annotation; otherwise the annotation becomes associated with the equation section: model Resistor2 Pin Pi Pin n;
parameter R "Resistance in [Ohm]"; equation R*p.i = p.v - n.v; n.i = p.i; public annotation (Icon ( graphics = {Rectangle (extent= [-70, -30; 70, 30], style(fillPattern=l», ... }, ... » ;
end Resistor2;
Class annotations for classes defined by short class definitions are placed at the end of the declaration: «identifierl» = < identifier2> <array dims> <modifiers>
For example, the Icon annotation is placed at the end of the Velocity declaration below, after the optional string comment: type Velocity = Real(3] (unit="m/s t'
)
Ita comment" annotation(Icon( ... »;
11.2.4 Variable Annotations A variable annotation associates information with a declared variable. Such an annotation is placed at the end of the variable declaration after the optional string comment. For example: Pin p annotation(Placement(transformation(x = -100, Y
=
0, scale = 0.2);
11.2.5 Import Annotations Analogous to variable annotations, import annotations are placed in the end of the import statement after the optional string comment, e.g.: import Modelica.Mechanics.Rotational "Rotational import" annotation( .. . )i
11.2.6 Equation Annotations The most common form of equation annotation is annotations to connection equations. It is natural to associate graphical attributes such as lines with a certain position, length, and color to such equations. As in the previous cases, the declaration is placed at the end, after the optional comment. For example: connect(pl.n,p2.p) "comment" annotation (Line (points=[-90, 0; -70, 0]»;
Chapter 11 Annotations, Units, and Quantities 361 It is also possible to have equation section annotations associated with an equation section. Such annotations can be placed as elements anywhere in the list of equation elements in an equation section.
11.2.7 Statement and Algorithm Annotations Statements can also be annotated, even though the need is less obvious than for connection equations. As for equations, statement annotations are placed at the end of the statement after the optional string comment, e.g.: name := x+2*y
"comment"
annotation ( )j
Analogous to equation section annotations, it is also possible to have algorithm annotations associated with an algorithm section. Such annotations can be placed as elements anywhere in the list of statements in an algorithm section.
11.3 Graphical Annotations Graphical annotations is the most common form of annotation in typical MOOeHca models. All models created using a graphic model editor and saved as Modelica text usually contain annotations that describe the graphical layout of the model components, including positions and sizes of icons and lines representing connections between the components. The predefined graphical annotations, annotation elements, and annotation attributes in MOOeHca provides a notation to express and save this kind of graphical information, The description given here specifies the meaning for a subset of standard graphic annotations that should be supported by all Modelica environments. Remember that a Modelica environment is free to define and use other annotation attributes in addition to those defined here. The only requirement is that any environment must be able to save files with all attributes intact, including those that are not used. To ensure this, annotations must be represented with constructs according to the Modelica syntax.
11.3.1 Graphical Representation of Models Graphical annotation information is normally given together with five different kinds of Modelica entities. We have the following cases where graphical annotations can appear: • • • • •
Annotations of a class to specify the graphical representation of its icon as a diagram and common properties such as a local coordinate system. Annotations associated with an instance of a class, typically to specify the position and size of the graphical representation of the instance. Annotations of connectors. Annotations of extends clauses. Annotations associated with a connection, i.e., its line representation, the color of the connection line, etc.
The example below shows the use of such graphical attributes in the form of annotations to define the different parts of the Resistor icon in Figure 11-1. R
n~
Figure 11-1. A Resistor icon defined by graphical annotations.
362 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
The class annotation named Icon in the Resistor model below defines the graphical layout of its icon, which in this case is a rectangle. This rectangle is specified by the Rectangle annotation element in which its two opposite corners are given by the extent attribute, and its visual pattern by the fillPattern attribute (see the graphical annotation attributes described in a subsequent section). Additionally, the resistor icon contains a text label given by the Text annotation elements with its attributes extent and string. The resistor also has two line segments, given by the two Line annotation elements, to visually emphasize its pins. The resistor has two Pin connectors represented by the two small squares. The left filled square represents the p connector whereas the right unfilled square represents the n connector. This square is the graphical icon for the Pin class. The icon image for Pin is positioned and scaled to the right size by the Placement annotation for the component, e.g. p and n in Figure 11-1 and in the code below. The icon is first drawn in the master coordinate system specified in the component's class, e.g. Pin. The graphical image is subsequently scaled and translated so that the coordinate system is mapped to the region defined by the transformation or iconTransformation attributes in the components declaration. model Resistor Pin p annotation (Placement (transformation(x=100,y=0,scale=0. 1), iconTransformation(x=100,y=O,scale=0.1)) ; Pin n'annotation(Placement(transformation(x=80,y=O,scale=O.1), iconTransformation(x=80,y=O,scale=0.1»; parameter R "Resistance in [Ohm]"; equation R*p.i
= p.v
- n.v;
n.i = p.i; public
annotation(Icon{coordinateSystem(extent={{-120,-120},{120,120}}), graphics = ( Rectangle (extent=[-70, -30; 70, 30], fillPattern=FillPattern.None), Text (extent= [-100, 55; 100, 110], textString="%name=%R"), Line (points= [-90, 0; -70, 0]), Line (points= [70,
0; 90,
0])
}
» ;
end Resistor;
11.3.1.1 Icon and Diagram Layers of Graphical Annotations The graphical representation abstraction of a class consists of two graphical layers: • •
The icon graphical layer. The diagram graphical layer.
Both representations show graphical objects such as icons to represent class instances, connectors, and connection lines. • •
The icon representation typically visualizes an instance by hiding hierarchical details. The diagram graphical layer typically describes the hierarchical decomposition by showing icons of subcomponents.
A graphical layer description is represented as an Icon or a Diagram annotation element. The structure of an Icon annotation element is given by one of these expressions: I
con (coordsys_specification, graphics) Icon (graphics)
A Diagram annotation element has one of the following two analogous forms: Diagram (coordsys_specification, graphics)
Chapter It Annotations, Units, and Quantities 363 Diagram (graphics)
Here is an example of a simple icon with a coordsysjspecification element and a graphics element defining the appearance through a list of two graphical primitives: annotation ( Icon(coordinateSystem={{-10,-lO}, {10,lO}}, graphics={Rectangle(extent={{-lO,-10}, {lO,lO}}), Text ({ {-10, -10}, {10, 10}}, textString=" Icon") }) ) ;
The graphics of an icon is specified as an ordered sequence of graphical primitives, which are described in Section 11.3.5 further below. Note that such an ordered sequence is a syntactically valid Modelica annotation, although there is currently no mechanism in Modelica for defining an array of elements of heterogeneous types.
11.3.2 Graphical Annotation Attributes There are a number of predefined graphical annotation attributes, which can be divided into basic attributes; attributes to classes, instances, and connections; and attributes that are graphical elements to specify the appearance of class icons. The attributes represent component positions, connections, and various graphical primitives for building icons as shown below. The attribute structures are described through Modelica classes. Points are denoted by vectors, and extents (two opposite points) are described using vectors of two points.
11.3.3 Basic Graphical Attributes These definitions of basic graphical attributes are used for the specification of the graphical annotation elements in the subsequent sections. type DrawingUnit = Real (final unit="mm"); type Point = DrawingUnit[2] "{x, Y}"; type Extent = Point(2) "Defines a rectangular area {{xl, yl}, {x2, y2}}";
The interpretation of uni t is with respect to printer output in natural size (not zoomed). On the screen, one mm in "natural size" is typically mapped to four pixels for a common value of screen resolution. All graphical entities inherit the partial record Graphicltem that has a visible attribute which indicates if the entity should be displayed or not. partial record Graphicltem Boolean visible = truei end Graphicltem;
11.3.3.1 Coordinate Systems for Icon and Diagram Graphical Layers Each graphical layer is a graphical object that has its own coordinate system. A coordinate system is defined by the coordinates of two points: the lower-left comer and the upper-right corner. This is represented by the extent attribute, of type Extent=Point [2], where each Point is a two-dimensional coordinate. record CoordinateSystem Extent extent; end CoordinateSystem;
"Attribute to graphical layer"
For example, a coordinate system for an icon could be defined as: CoordinateSystem(extent
=
{{-IO, -10}, {i o, 10}});
364 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica i.e., a local coordinate system extent with width 20 units and height 20 units, with the local x coordinate from -10 to 10 and the local y from -10 to 10. The exact interpretation of the units is to a certain extent tool dependent. The coordinate systems for Icon and Diagram are by default defined as follows. The graphics attribute being an array of Graphicltem represents an ordered list (a sequence) of graphical primitives. record Icon "Representation of Icon graphical layer" CoordinateSystem coordinateSystem(extent = {{-lO, -lO}, flO, 10}}); Graphicltem[:] graphics; end Icon; record Diagram "Representation of Diagram graphical layer" CoordinateSystem coordinateSystem(extent = {{-IOO, -lOO}, {lOO, lOO}}); Graphicltem[:] graphics; end Diagram;
For example, a coordinate system with extent for a connector icon could be defined as: CoordinateSystem(extent = {{-I, -I}, {I, I}});
11.3.3.2 Color and Appearance of Graphical Objects Color and pattern properties of graphical objects and connection lines are described using the following attribute types: type Color = Integer [3] (min=O, max=255)
"RGB representation";
type LinePattern
enumeration (None, Solid, Dash, Dot, DashDot, DashDotDot)i
type FillPattern
enumeration (None, Solid, Horizontal, Vertical, Cross, Forward, Backward, CrossDiag, HorizontalCylinder, VerticalCylinder, Sphere};
type BorderPattern = enumeration (None, Raised, Sunken, Engraved); constant Color Black = zeros(3);
II Default color
The FillPattern attribute values Horizontal, Vertical, Cross, Forward, Backward, and CrossDiag specify fill patterns drawn with the border lineColor over the fillColor. The attributes HorizontalCylinder, VerticalCylinder, and Sphere specify color intensity gradients that represent a horizontal cylinder, a vertical cylinder, and a sphere, respectively. The borderline pattern attributes Rai sed and Sunken represent panels that are rendered in a systemdependent way. The border pattern Engraved represents a system-dependent outline. type Arrow
=
enumeration {None, Open, Filled, Half);
type TextStyle
= enumeration (Bold,
Italic, UnderLine);
Filled-shape graphical objects, e.g. rectangle, polygon, and ellipse, inherit the record FilledShape that has the following attributes for the border and the interior: record FilledShape "Style attributes for filled shapes" Black "Color of border line"; Color lineColor Black "Interior fill color"; Color fillColor LinePattern.Solid "Border line pattern"; LinePattern pattern FillPattern.None "Interior fill pattern"; FillPattern fillPattern 0.25 "Border line thickness" DrawingUnit lineThickness end Style;
When a color gradient is specified, the color fades from the specified fill color to white and black using the hue and saturation of the specified color.
Chapter 11 Annotations, Units, and Quantities
365
11.3.4 Graphical Representation of Certain Model Elements So far we have primarily discussed the graphical representation of a whole class in the icon or diagram graphical layer, as well as a set of basic graphical attributes. Now we turn to the graphical representation of certain elements appearing in classes, such as instances, extends clauses, connectors, and connections.
11.3.4.1 Instances and extends Clauses Graphical representations of class instances and extends clauses can be placed within a diagram or icon graphical layer. Each kind of graphical element has an annotation with a Placement modifier to describe its placement. record Placement "Attribute for instances and extends clauses" extends Graphicltem; Transformation transformation "Placement in diagram graphical layer"; Transformation iconTransformation "Placement in icon graphical layer"; end Placement;
Placements are defined in terms of transformation objects, defining the position and orientation of a graphic object with its local coordinate system, relative to the coordinate system of the graphic object associated with the enclosing class: record Transformation DrawingUnit x 0; DrawingUnit y 0; Real scale 1; Real aspectRatio = 1; Boolean flipHorizontal = false; Boolean flipVertical false; Real rotation (quantity= "angle " , unit::.::"deg") end Transformation;
=
0;
The coordinate attributes {x,y} define the position of the origin of the component's icon coordinate system. The scale attribute defines a uniform scale factor of the icon's coordinate system when drawn in the coordinate system of the enclosing class. See the Pin p example in the next sect.ion. The aspectRatio attribute defines nonuniform scaling, where sy=aspectRatio* sx. The flipHorizontal and flipVertical attributes define horizontal and vertical flipping around the coordinate system axes. The graphical operations are applied in the following order: scaling, flipping, and rotation. Figure 11-2 illustrates scaling and rotation of a rectangle.
Figure 11-2. Scaling and rotation coordinate system transformations on a rectangular object.
11.3.4.2 Connectors A connector can be displayed in both an icon graphical layer and a diagram graphical layer of a class. Since the coordinate systems typically are different, placement information needs to be given using two different coordinate systems. More flexibility than just using scaling and translation is needed since the abstraction views might need different visual placement of the connectors.
366 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica The transformation attribute of a Placement annotation element gives the placement in the diagram graphical layer and the i conTrans forma t i on attribute gives the placementin the icon graphical layer. For example: . Pin p annotation (Placement {transformation(x=100,y=0,scale=O. 1), iconTransformation(x=100,y=20,scale=0.1»i
When a connector is shown in a diagram graphical layer, its diagram graphical layer is displayed to facilitate opening up a hierarchical connector to allow connectionsto its internal subconnectors. For connectors, the icon graphical layer is used to represent a connector when it is displayed in the icon graphical layer of the enclosing model. The diagram graphical layer of the connector is used to represent it when shown in the diagram graphicallayer of the enclosing model. Protected connectors are shown only in the diagram graphical layer, Public connectors are shown in both the diagram graphical layer and the icon graphical layer. Non-eonnector components are shown only in the diagram graphical layer. 11.3.4.3 Connections
A connectionis specified with an annotationcontaining a Line primitive, as exemplifiedbelow: connect {a.x, b.x) annotation {Line {points= { {-25,30}, {10, 30}, {10, -20}, {40, -20} } ) ) ;
11.3.5 Definitions of Graphical Elements The following predefined graphical elements are used as graphical annotation elements when describing the appearance of graphical objects in annotations. This includes annotation attributes used when defining the appearanceof class icons.The Line graphicalelement can also be used for connection lines. A list of such graphical elements of type Graphicltem occur as the value of the graphics attribute. The following elements are available:
• • • • • •
Line Polygon Rectangle Ellipse Text Bitmap
In the subsequent sections we specify the structureof each graphical element in more detail. 11.3.5.1 Line
The propertiesof a line are describedby the following record definition: record Line extends Graphicltem; Point[:l points; Color color Black; LinePattern pattern LinePattern.Solid; DrawingUnit thickness 0.25; Arrow [2] arrow = {Arrow.None, Arrow.None}; "{start arrow, end arrow}" DrawingUnit arrowSize 3; Boolean smooth = false "Spline if true"; end Line;
Remember that the Line primitive is also used to directly specify the graphical representation of a connection, as described in Section 11.3.4.3above.
Chapter 11 Annotations, Units, and Quantities 367
11.3.5.2 Polygon The propertiesof a polygon are specifiedby the following record definition: record Polygon extends Graphicltem; extends FilledShape; Point[:l points; Boolean smooth = false end Polygon;
"Spline outline if true";
A polygon is closed by definition. This is obvious if the first and the last points are the same. However, if the first and the last points are not identical, the polygon is automatically closed by generating a line segment between these two points.
11.3.5.3 Rectangle A rectangle is described as follows: record Rectangle extends Graphicltem; extends FilledShape; BorderPattern borderPattern = BorderPattern.none; Extent extent; DrawingUnit radius = 0 "Corner radius"; end Rectangle;
The extent attribute specifies the bounding box of the rectangle. If a nonzero radius value is specified, the rectangle is drawn with rounded corners of the given radius.
11.3.5.4 Ellipse An ellipse graphic element is specified by the following record type: record Ellipse
extends Graphicltem; extends FilledShape; Extent extent; end Ellipse;
The extent attribute of the record specifies the bounding box of the ellipse.
11.3.5.5 Text The graphical properties of a text string are described by the Text record: record Text extends Graphicltem; extends FilledShape; Extent extent; String textString; DrawingUnit fontSize; String fontName; TextStyle[:] textStyle; end Text;
The style attribute fontSize specifies the font size in "points", the standard unit used in typesetting. If the fontSize attribute is 0 the text is scaled to fit its extent according to the value of the extent attribute. Otherwise, the fontSize specifies the absolute size of the font. Note that the unit "point" is 1/72 inch, which is approximately 0.35 rom. The style attribute textStyle specifies variations of the font such as TextStyle.Bol~TextStyle.ltalic,e~.
368 Peter Fritzson Principles of Object-Oriented Modelingand Simulationwith Modelica 11.3.5.6 Bitmap
A bitmap image is specified as follows: record BitMap extends Graphicltem; Extent extent; String fileName String imageSource end BitMap;
"Name of bitmap file"; nPixmap representation of bitmap";
The bitmap graphic descriptor contains information for rendering a graphical bitmap image. The data of the image can be stored either on an external file or in the annotation itself. The image is scaled to fit the value of the extent attribute. When the string attribute fileName is specified as a nonempty string it refers to an external file containing image data. The mapping from the string to the file is unspecified. The supported file formats include PNG, BMP and JPEG-Other supported file formats are unspecified. When the attribute imageSource is specified as a nonempty string it contains the image data. The image is represented using the Pixmap format, This format is well-known and clearly defined. It can be both used as a file format and embedded as a string. There are public-domain libraries for reading and writing Pixmap files. The image is uniformly scaled in order to preserve its aspect ratio. By doing so it exactly fits within the extent, touching the extent along one axis. The center of the image is positioned at the center of the extent.
11.3.6 Annotations Defining Interactive Menus Most Modelica environments allow us to specify simulation parameter values through interactive graphical menus and forms. This is commonly used to interactively assign numerical values for parameters of model components before a specific simulation run, e.g. to give a resistance parameter value for a certain resistor component. In certain situations, e.g. when there is a small number of predefined choices of a simulation parameter, it is more user-friendly to be able to choose among alternatives in a menu containing easy-to-understand descriptive menu items. For example, we might have a parameter that specifies the kind of controller to be used, where alternative 1 is a proportional controller, the 2nd alternative is a proportional and integrating controller, and the 3rd alternative is a PID controller. Instead of giving the number 2 to choose the second alternative, we interactively choose the PI alternative in a menu containing. the three items: P, PI, and PID. In order to specify such menus Modelica supports a standard annotation called choices. This annotation can be associated either directly with a parameter declaration or with a declaration of a type in some class or package. The choices annotation contains a number of choice annotation elements, one for each menu item. 11.3.6.1 Choices Annotations for Variables and Enumeration Types
The choices annotation is applicable to both replaceable and nonreplaceable elements. Examples of the latter are simple parameter variables and types used for enumerations. For example, consider the following Integer type called KindOfController used to represent a choice of controller in the modeling process. This choice is made from the following enumeration of three recommended alternatives: type KindOfController=Integer(min=1,max=3) annotation (choices ( choice=l "P", choice=2 "PI", choice=3 "PID"»;
Chapter 11 Annotations, Units, and Quantities 369 Assume that KindOfController is used in a model A as below: model A parameter KindOfController
end
Xi
Ai
Without the choices annotation an interactive Modelica environment would present us with an integer value field for x in the parameter menu of model A. Instead, the choices annotation makes it possible for the environment to present a choice selection menu with the entries" P"," PI"," PIn". If we interactively choose the third alternative from the menu this corresponds to giving the default value 3 for the instantiated variable x in the following code for an instance a2 of the model A: A a2 (x=3 "PID");
11.3.6.2 Choices Annotations for Replaceable Model Elements The choices annotation also can be used to generate menus with redeclaration alternatives for replaceable models. The user interface can suggest reasonable redeclarations, where the string comment in a choice annotation element is used as a textual explanation of the choice alternative. Based on the interactions with the user, the graphical user interface then generates the appropriate Modelica code. See also Section 4.3.7 in Chapter 4 concerning redeclarations. For example, consider the following replaceable model with a choices annotation: replaceable model MyResistor=Resistor annotation (choices ( choice(redeclare MyResistor=lib2.Resistor "Resistor 1"), choice(redeclare MyResistor=lib2.Resistor2 "Resistor 2")));
If the user would choose the first alternative, the following code might be produced if MyResistor is part of the class MyCircui t and the chosen name of the instantiated component is x: MyCircuit x(redeclare MyResistor=lib2.Resistor)
Additional examples of replaceable class declarations with redeclaration choices are shown below. In the frrst example we can choose between a resistor and a capacitor as choices of components with two pins, and in the second example a friction function is implemented as a constant, a table, or defined as an exponentiation function depending on our choice. replaceable Resistor Load(R=2) extends TwoPin annotation (choices ( choice{redeclare lib2.Resistor Load{a={2}) "Resistor"), choice(redeclare Capacitor Load(L=3) "Capacitor"»); replaceable FrictionFunction a(func=exp) extends Friction annotation (choices ( choice (redeclare ConstantFriction a(c=l) "Friction-constant"), choice {redeclare TableFriction a(table="~") "Friction-table"), choice(redeclare FunctionFriction a(func=exp)"Friction-exp"»));
11.4 Documentation Annotations Documentation is important for any kinds of software including Modelica models. The additional documentation information helps understanding and reusing code, as well as providing hints for its use in different kind of applications. Regarding the form of Modelica documentation, we have already mentioned string comments that can be associated with various constructs in Modelica and are displayed by most Modelica browser tools. Standard Modelica comments can be given everywhere but are not processed by Modelica tools.
370 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Modelica also defines a Documentation annotation for classes and packages, where information can be structured in key-value pairs, e.g.:
annotation (Documentation ( info = "Text string", revisions = "Text string", key3 "Text string", key4 = "Text string" )) ;
Currently there is no Modelica standard for the categories (e.g. represented as key-value pairs) in this kind of documentation, except the "standard" info attribute described in the next section, which is used for general documentation of packages and classes in the Modelica standard library, and the revisions attribute used for a log of the revisions (may be left out in printout) of Modelica classes. It is expected that most organizations will specify their own documentation guidelines. We give the following hints for categories of information that typically should be part of good documentation: • • • • •
Revision (development) history and author information, Literature references. Validation information regarding model behavior and comparison with measurement data. Explanations and schematic drawings of models. User advice for reuse and application of models.
11.4.1 Information and HTML Documentation In the Modelica Standard Library and generally in Modelica code the Documentation annotation with the info attribute is a standardized way to define documentation. A Modelica environment should recognize documentation annotations of the following form:
Documentat ion (info
= string)
For example, the documentation of the Modelica standard library package is expressed as the following annotation:
annotation(Documentation(info = "
Package Modelica is a standardized and pre-defined package that is developed together with the Modelica language from the Modelica Association, see http://www.Modelica.orgc:: f a>. It is also called Modelica Standard Library. It provides constants, types, connectors, partial models and model components in various disciplines.
" ) ); As we can see from the above example, HTML tags can be present in the info text. When extracting documentation information from a model, a Modelica tool should store this part of the documentation as an HTML-file that, e.g. can be displayed by an appropriate lITML-browser.
11.5 Version Handling Annotations A toplevel package or model can specify the version of toplevel classes it uses, its own version number, and if possible how to convert from previous versions. This can be used by a Modelica environment to
Chapter 11 Annotations,Units, and Quantities 371 guarantee that consistent versions are used, and if possible to automatically upgrade usage from an earlier version to a current one.
11.5.1 Version Numbering Version numbers are of the forms, where the notation {} means repetition zero of more time (see Appendix A for interpretation of UNSlGNED_ INTEGER and S - CHAR):
•
Main release versions: "" .. UNSIGNED_INTEGER
" "
UNSIGNED_INTEGER
nn n ,
e.g.
"2.1".
•
Pre-release versions: """ UNSIGNED_INTEGER "." UNSIGNED INTEGER CHAR} """,e.g. "2.1 Beta 1". Unordered versions: """ NON-DIGIT {S-CHAR} """,e.g. "Test 1".
•
" " {s-
The main release versions are ordered using hierarchical numerical names, and follow the corresponding prerelease versions. The prerelease versions of the same main release version are internally alphabetically ordered.
11.5.2 Version Handling In a toplevel class, the version number and the dependency to earlier versions of this class are defined using one or more of the following annotations: •
The annotation vers ion = current-version-number defines the version number of the model or package. All classes within this toplevel class have this version number.
•
The annotation conversion (noneFromVersion = version-number) defines that user models using the version-number can be upgraded to the current-version-number of the current class without any changes.
•
•
The annotation conversion (from (version = version-number, script = "..."» defines that user models using the version-number can be upgraded to the current-version-number of the current class by applying the given script. The semantics of the conversion script is not defined. The annotation uses tident (version = version-numberi i defines that classes within this toplevel class uses version version-number of classes within the top-level class IDENT.
The annotations uses, and conversion may contain, several different subentries. For example: package Modelica annotation(version="2. 1" , conversion(noneFromVersion="2.1 Beta 1", from(version~"1.5",
script::"convertFromModelical_S.mos tf » ) ; end Modelica; model A annotation (version=ul. 0", uses(Modelica(version="1.5"»)i end A; model B annotation(uses(Modelica(version="2.1 Beta 1"»); end B;
372 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica In this example the model A uses an older version of the Modelica library and can be upgraded using the given script, and model B uses an older version of the Modelica library but no changes are required when upgrading.
11.5.3 Mapping of Versions to the File System A toplevel class, named ident, with version version-number can be stored in one of the following ways in a file system directory given in the MODELICAPATH: • • • •
The file idents» . mo", e.g. "Modelica. mo", Thefileident+" "+version-number+".mo",e.g. "Modelica 2.1.mo". The directory ident, e.g. "Modelica". The directory ident+" n+ version-number, e.g "Modelica 2.1".
This allows a Modelica environment to access multiple versions of
th~
same package.
11.6 Function Annotations Two rather special annotations are defined for functions. These are the function de r i vat i ve annotation and the arrayLayout annotation. The function derivative annotation allows us to explicitly specify the computation of the derivatives of a function to any order, e.g. in order to gain performance and/or numerical accuracy. The external function annotation arrayLayout can be used to explicitly give the layout of arrays, e.g. if it deviates from the default rowMajor and columnMajor order for the external languages C and Fortran 77 respectively.
11.6.1 Function Derivative Annotations A Modelica compiler usually needs to differentiate functions called in equations and expressions of a
model when transforming the model into a form that is better suited for execution. A function defined in Modelica can be automatically differentiated based on symbolic differentiation of the statements in the body of the function. However, this option is not possible for external functions, for which the only alternative for the system usually is to resort to numerical approximations of the derivatives. Also, even for Modelica functions the automatically obtained symbolic derivatives may sometimes (but rather seldom) be inefficient or have numerical instabilities. For these reasons, an annotation called deri vative, with an associated optional annotation attribute order, is available for Modelica functions, i.e., for both external functions and functions implemented in Modelica. This allows us to explicitly state the computation of the derivatives of a function to any desired order. We should point out that the derivat i ve annotation is seldom needed, but is useful in certain cases where accuracy and/or performance need to be improved. For example, the function hO below specifies its time derivative to be given by the function hI, which in tum specifies its derivative (of order 2) to be computed by the function h2. function hO annotation(derivative=hI); end hOi
function hI annotation(derivative(order=2)=h2)i end hI;
function h2 end h2;
Chapter II Annotations, Units, and Quantities 373 The formal parameter list of a de r i va t i ve function of order 1 is constructed as follows: •
First comes all the input formal parameters of the original function. After those we will in order append one derivative input formal parameter for each input formal parameter containing Realtyped values, e.g. scalars, arrays, or records. The outputs are constructed by starting with an empty list and then in order appending one derivative formal parameter for each output containing reals.
•
The formal parameter list of a derivative function of order n+ 1 >1 is defined as follows:
•
If the Modelica function for which the derivative function is specified is an nth derivative (n>=I), the derivati ve annotation should indicate the (0+ l)th derivative by setting the attribute order=n+l. The list of input formal parameters is amended by the (n+l)th derivative formal parameters, which are constructed in order from the nth order derivatives. The output formal parameters are similar to the output formal parameters for the nth derivative function, but each output is one higher in derivative order.
• •
An input or output formal parameter to a function with a derivative annotation may be of any predefined type (Real, Boolean, Integer, and String) or a record, or array thereof, provided the record does not contain fields of both Real and non-Real predefined types. The function must have at least one input formal parameter containing reals. The set of output formal parameters of the derivative function may not be empty. We apply this construction to a function hO with three formal parameters: the Integer-valued Li , the Real-valued x (implicitly a function x(t) of time as all Real variables), and the Boolean-valued b. Let y(t) be the return value of ho: y(t) = ho(i. ,x(t),b)
(11-1)
By differentiating twice, using inner derivatives, we obtain:
dy( t) = h•(.,) ,x() t , b, dx( t) ) dt dt 2
2
d y(t) = h (. () b dx(t) d x(t) 2 2 II' X t, , , 2 dt dt dt
(11-2)
Applying this to the example function y(t) = hO(t) = exp(x(t»+iJ when specifying the first- and secondorder derivative functions gives the following definitions of hO, hI, and h2: function hO II exp(x(t)+il) annotation(derivative=hl); input Integer il; input Real x; input Boolean linear; II not used output Real y; algorithm y := exp(x)+il; end ho , function hI II (d/dt) (exp(x(t)) annotation(derivative(order=2)=h2)i input Integer il; input Real Xi input Boolean linear; input Real der_x; output Real der_y; algorithm der_y := exp(x)*der_x;
374 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica end hI; function h2 II (d/dt) (exp(x(t)*der_x(t») input Integer il; input Real Xi input Boolean linear; input Real der_x; input Real der_2_x; output Real der_2_y; algorithm der_2_y .- exp{x)*der_x*der_x + exp{x)*der_2_x; end hl;
11.6.2 External Function Annotations Regarding specific annotations only for external function declarations there is an optional arrayLayout annotation, which can have one of the values "rowMajor" or "columnMajor". These are the defaults for C and Fortran 77 array layout respectively. This annotation causes additional information to be passed to the compiler when necessary. It is needed only when the array storage layoutdeviates from the default for the external language. This is the case for the function j oinThreeVectors2 'below where the C function uses column-major array representation, which is different from the default row-major layout that normally is used for C. For more information on externalfunctions, see Section9.4 on page 311 in Chapter
9. function joinThreeVectors2 "External C function with column-major arrays" input Real vl[:] ,v2[:],v3[:]; output Real vres[size(vl,1)+size(v2,1)+size(v3,1»); external "C" join3vec(vl,v2,v3,vres,size(vl,1),size(v2,1),size(v3,1»; annotation(arrayLayout = "columnMajor")i end joinThreeVectors2;
11.7 Units and Quantities What is the meaning of unit and quantity? These notionsare often used in the literatureof naturalsciences, e.g. in physics and chemistry. We speak about measuring physical quantities, and the unit by which we are measuring those quantities. Unfortunately the literature is sometimes confusing. Some texts use the terms unit, quantity, and dimension more or less interchangeably. Nonetheless one can discern some kind of consensusregardingthe definitionof unit and quantitybasedon the majority of scientifictexts in the area:
• •
Quantity, also called dimension, is what we measure, i.e., any measurable extent or magnitude such as length, mass,time, etc. A unit is a "yardstick" by which we express our measurements. For example, a measurement of the length quantitycan be expressed as a numberof meterunits.
As we just stated, quantity can be interpreted as the basic notion of what we measure. There is a set of seven base quantities defined in the ISO SI system, stated below. The associated measurement unit is given within parentheses: • • • • • •
Length (m). Mass (kg). Time (s). ElectricCurrent (A). Temperature (K). Amountof substance (mol).
Chapter 11 Annotations, Units, and Quantities 375 •
Luminosity (Cd).
However, the set of base quantities is not enough for engineering application modeling. For example, Angle is not included among the Sf system base quantities-it is regarded as dimensionless. A number of derived quantities are quite important, e.g. Force (N), Torque (N.m), ElectricPotential (V), Voltage (V), Velocity (mls), AngularVelocity (radls), etc.-the list is quite long. Applications in areas such as information technology may require additional quantities, e.g. information flow with an associated unit of bit/second. The choice of the SI system base quantities above is somewhat arbitrary, partly influenced by practical considerations regarding the complexity of common unit expressions. Some unit systems use ElectricCharge as a base quantity instead of ElectricCurrent, since this can be considered as somewhat more basic from a physical modeling point of view. However, that leads to longer unit expressions in many practical cases when converting to base units. Modelica provides somewhat more precise definitions of quantity and unit compatible with the above guidelines, as well as a formal syntax of unit expressions according to guidelines found in the ISO SI unit standard.
11.7.1 Quantity, Unit, and displayUnit in Modelica The Modelica notions of quantity and unit correspond to the definitions given in the previous section, but with a concrete representation as string attributes to the Real predefined class (see below and in Section 3.9 on page 84 in Chapter 3). type Real "Pseudo class declaration of predefined Real type" parameter 'StringType' parameter 'StringType' parameter 'StringType'
quantity unit displayUnit
It" It"
""
"Physical quantity"; "Unit used in equations"; "Default display unit";
end Real; The quantity, unit, and displayUnit attributes of the Real predefined type have the following meaning: •
•
•
quant i ty-a string describing what physical quantity the type represents. Example quantities are: "Mass," "Force," "Torque," "Acceleration," etc. The quantity attribute defines the category of a variable. It is used as a grouping mechanism for different units belonging to the same physical quantity. unit-a string describing the physical measurement unit of the type. Examples are "kg", "m", "m/s", "N.m", "kg.m/s2", "kg.m.s-2", "l/rad", etc. The unit attribute defines the unit of variable values as used for computation in expressions and equations. The numeric values of variables are interpreted with respect to their associated units. displayUnit-gives the default unit used by a Modelica tool for interactive input/output. For example, the display unit for angle might be "deg," but the unit might be "r'ad." Values interactively input or output as "deg" are then automatically converted to/from "rad."
Below are examples of definitions and uses of types corresponding to some physical quantities. Remember that the final prefix on quanti ty and uni t means that these attributes cannot be changed by further modification of the types Force and Angle.
1/ Define quantity types -type Force
Real (final quantity="Force", final unit="N"); type Angle = Real(final quantity="Angle", final unit="rad", displayUnit="deg"); II Use the quantity types
376 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Force Force Angle Angle
fli
f2(displayUnit="kp")i alpha; beta{displayUnit="rad");
As stated above, the quantity attribute can be used as a grouping mechanism in interactive Modelica environments. The quantity name is needed because it is in general not possible to determine just from the uni t whether two different units belong to the same physical quantity. For example, consider the following two types: type Torque
Real(final quantity="MomentOfForce", final unit="N.m")i
type Energy
Real(final quantity="Energy"
final unit="JIt);
The units of type Torque and type Energy both can be transformed to the same combination of base units, i.e., "kg. m2/s2". However, the two types still characterize different physical quantities. In an interactive Modelica environment with a menu prompting for a choice of displayUnit for an instantiated component of the Torque type, the unit "J" should not appear in the menu. If only the uni t of the variable is given without any quantity information, it is not possible for the Modetica environment to produce a correct list of alternatives in the menu for using a display unit. The Modelica standard library package Modelica. SIunits contains predefined quantity and connector types in the form shown in the above examples. This library contains approximately 450 predefined types comprising the complete set of ISO SI standard units, which is quite helpful when defining the interfaces of a model. Some additional examples from this library are shown below: Real(final quantity=IIElectricCurrent", final unit= "A"); ElectricCurrent; Current Resistance Real(final quantity="Resistance ll , final unit="Ohm", min=O); Inductance Real(final quantity="Inductance ll , final unit="H", min=O); Time Real(final quantity="Time", final unit="s" ); Length Real(final quantity="Length", final unit="m" ); position Real(final quantity="Length", final unit="m"); AngularVelocity Real(final quantity="AngularVelocity", final unit="rad/s", displayUnit="rev/min"); AngularAcceleration Real(final quantity="AngularAcceleration", final unit="rad/s2")i MomentOflnertia Real(final quantity="MomentOflnertia", final unit="kg.m2");
type ElectricCurrent type type type type type type type
type type
11.7.2 Unit Conversion Automatic conversion between units is not required by a conforming Modelica language implementation. This is a facility that can be provided by separate tools such as unit and dimension checkers, or special high-quality Modelica implementations. Not requiring automatic unit conversion simplifies a Modelica translator considerably, partly because it is hard to define a complete unit database with conversion rules. As a consequence, the semantics of a correct Modelica model is independent of the uni t and quan tit Y attributes, which are ignored during code generation. It is even the case that the uni t attributes are not checked for connections, i.e., connected variables may -have different units and quantities. However, an interactive Modelica environment, e.g. a- model connection editor, is free to provide support for such automatic unit conversion when two interfaces are connected. IT there are conflicting units a warning will be issued since this is not really considered an error. As a general rule it will always be allowed to connect any variable to a variable without unit and quantity information.
Chapter I I Annotations, Units, and Quantities 377
11.7.2.1 Dimension and Quantity Checking The more common tenn dimension checking refers to consistency checking regarding compatible quantities and units in expressions and equations. For example, a Modelica environment may optionally check the consistency of the quanti ty and uni t attributes between the left-hand side and the right hand side of an equation. Dimension checking is done by transforming the quantity and unit information into combinations of the seven base quantities with associated units. For example, consider the equation:
/=m'a
(11-3)
The quantity of the right-hand side is initially Mass*Acceleration, which is reduced to Mass*Length in terms of base quantities. The corresponding units are converted to "kg.m2/s2". If the left-hand side has the quantity Force with the unit ''N'', this can be converted to the same base quantities as in the right-hand side. However, if, for example, the unit off instead would have been "N . m", a unit inconsistency warning should be issued. A 2 / T i m e A2
11.7.3 Unit Expression Syntax The Modelica syntax rules for unit expressions determine the structure of Modelica uni t attributes represented as strings, e.g. as in the following example unit strings: "kg", "m", "m/ s", ''N. m", "kg. ml s 2", "kg. m. 8-2", "l/rad". These rules are conformant with the international standards ISO 31/0-1992, "General principles concerning quantities, units and symbols" and ISO 1000-1992 "SI units and recommendations for the use of their multiples and of certain other units." Unfortunately, neither these standards nor any other previous standard define a formal syntax for unit expressions. However, Modelica defines a formal syntax for unit expressions based on recommendations in the above standards. These formal syntax rules can be found in Appendix A. Below we informally describe the Modelica syntax rules for unit expressions together with a few examples: • • • •
•
•
•
The unit of a dimension-free quantity is denoted by "1". The only permitted operators in unit expressions are division, represented by "/", and multiplication, represented by a dot" . ", Implied multiplication between units in unit expressions is not allowed, e.g. ''Nm'' is incorrect, instead "N . m" should be used. There is no operator symbol for exponentiation. Instead a possibly signed number immediately after a unit operand is interpreted as an exponent. There should be no space between the operand and the exponent, e.g. for square meter, m2, write "mz", The ISO standard recommends at most one division where the expression to the right of "I" either contains no multiplications or is enclosed within parentheses. It is also possible to use negative exponents, for example, "J I (kg. K) " may be written as "J . kg -1 • K -1". A unit symbol is a string of letters, e.g. "kg", "Ohm", etc. A basic support of units in a Modelica tool should know the basic and derived units of the SI system. It should be possible to support user-defined unit symbols. In the base version, Greek letters are not supported, but full names must then be written, for example "Ohm". A unit operand expression should first be analyzed with an interpretation as a unit symbol. Only if not successful the second alternative assuming a prefixed operand should be investigated. There should be no spacing between the unit symbol and a possible unit prefix. The possible value of the prefix is according to the ISO standard, i.e., one of Y, Z, E, P, T, G, M, k, h, da, d, c, m, U, p, f, a, Z, y. The letter u is used as a symbol for the prefix micro.
378 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Below are some examples of combinations of prefixes, unit symbols, and possible exponents. Prefixes have a higher priority than exponents, and may not be used in isolation. • • •
The unit expression "m" means meter and not milli (10-3) , since prefixes cannot be used in isolation. For millimeter use "mm" and for square meter, m2, write "mz". The expression "mmz" means mm2 = (lO·3 m) 2 = lO·6m2. Note that exponentiation includes the prefix. The unit expression "T" means Tesla, but note that the letter "T" is also the symbol for the prefix tera, which has a multiplier value of 1012•
11.8 Summary In this chapter we presented the Modelica annotation concept followed by a short overview of units and quantities in Modelica. First we described annotation syntax and placement, including annotation elements for redeclarations, classes, variables, imports, equations, and algorithms. Then followed a description of graphical annotations, which comprise a large part of the predefined annotations in Modelica. We subsequently presented the layered structuring of graphical annotations and the different graphical annotation attributes. We also defined the graphical annotation elements as record structures in Modelica, as well as annotations defining interactive menus, documentation annotations, and different kinds of function annotations. Finally we presented the concepts of units and quantities with associated attributes, unit conversion, and unit expression syntax.
11.9 Literature The Modelica language specification (Modelica Association 2003) and the tutorial (Modelica Association 2000) specifies the rules for annotations in Modelica, and gives the basics of units and quantities. Regarding the Pixmap bitmap format used in graphic annotations, see (pixmap 2(03). More information concerning the general principles of quantities, units and symbols and their use can be found in (ISO 31/0-1992; ISO 1000-1992). Information on units and unit conversion is available in (Cardarelli 1997).
379
Part III
Modeling and Applications
381
Chapter 12 System Modeling Methodology and Continuous Model Representation
So far in this text we have primarily discussed the principles of object-oriented mathematical modeling, a number of Modelica language constructs to support high-level model representation and a high degree of model reuse, and many model examples that demonstrate the use of these language constructs. However, we have not yet presented any systematic method on how to create a model of a system to be investigated. Nor have we previously presented the underlying mathematical state space equations in any detail. These are the topics of the current chapter. However, the state space representation presented here covers only the simple case for continuous systems. The background for discrete event and hybrid continuous-discrete system modeling is explained in Chapter 13, whereas the complete hybrid DAE representation that also handles discrete events and hybrid systems is defined in Chapter 17.
12.1 Building System Models A basic question is: How do we arrive at reasonable mathematical models of the systems we want to study and possibly simulate? That is, what is an effective modeling process? The application domain is of primary importance in all kinds of modeling. We talk: about physical modeling when the systems to be modeled are described by natural laws in physics, chemistry, biology, mechanical and electrical engineering, etc., and these laws can be represented directly in the mathematical model we are constructing. However, it does not really matter whether the application domain is "physical" or not. There are laws governing economic systems, data communication, information processing, etc., that should be more or less directly expressible in the model we are building when using a high-level modeling approach. All of these laws are given by the universe where we exist (but formulated by human beings), and can be regarded as basic laws of nature. An overview of common laws for a number of application domains is given in Chapter 14. At the start of a modeling effort we first need to identify which application domains are involved regarding the system we want to model, and for each of these domains find out the relevant governing laws that influence the phenomena we want to study. In order to be able to handle the complexity of large models and to reduce the effort of model building by reusing model components it is quite useful to apply hierarchical decomposition and object-oriented component-based techniques such as those advocated in this text. To make this more clear, we will briefly contrast the traditional physical modeling approach to the object-oriented component-based approach. However, one should be aware that even the traditional approach to physical modeling is "higher-level" than certain other approaches such as block-oriented modeling or direct programming in common
382 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica imperative languages, where the user has to manually convert equations into assignment statements or blocks and manually restructure the code to fit the data and signal flow context for a specific model use.
12.1.1 Deductive Modeling versus Inductive Modeling So far we have dealt almost exclusively with the so-called deductive modeling approach, also called physical modeling approach, where the behavior of a system is deduced from the application of natural laws expressed in a model of the system. Such models are created based on an understanding of the "physical" or "artificial" processes underlying the system in question, which is the basis for the term "physical modeling". However, in many cases, especially for biological and economic systems, accurate knowledge about complex systems and their internal processes may not be available to an extent that would be needed to support physical modeling. In such application areas it is common to use an entirely different approach to modeling. You make observations about the system under study and then try to fit a hypothetical mathematical model to the observed data by adapting the model, typically by finding values of unknown coefficients. This is called the inductive modeling approach. Inductive models are directly based on measured values. This makes such models difficult to validate beyond the observed values. For example, we would like to accommodate mechanisms in a system model is such a way that disasters can be predicted and therefore possibly prevented. However, this might be impossible without first observing a real disaster event (that we would like to avoid by all means) in the system. This is a clear disadvantage of inductive models. Also notice that just by adding sufficiently many parameters to an inductive model it is possible to fit virtually any model structure to virtually any data. This one of the most severe disadvantages of inductive models since in this way one can be easily fooled concerning their validity. In the rest of this book we will mainly deal with the deductive or physical modeling approach, except for a few biological application examples where we present models that are partly inductive and partly have some physical motivation.
12.1.2 Traditional Approach The traditional methodology for physical modeling can be roughly divided into three phases: 1. Basic structuring in terms of variables. 2. Stating equations and functions. 3. Converting the model to state space form. The first phase involves identification of which variables are of interest, e.g. for the intended use of the model, and the roles of these variables. Which variables should be considered as inputs, e.g. external signals, as outputs, or as internal state variables? Which quantities are especially important for describing what happens in the system? Which are time varying and which are approximately constant? Which variables influence other variables? The second phase involves stating the basic equations and formulas of the model. Here we have to look for the governing laws of the application domains that are relevant for the model, for example, conservation equations of quantities of the same kind such as power in related to power out, input flow rate related to output flow rates, and conservation of quantities such as energy, mass, charge, information, etc. Formulate constitutive equations that relate quantities of different kind, e.g., relating voltage and current for a resistor, input and output flows for a tank, input and output packets for a communication link, etc. Also formulate relations, for example, involving material properties and other system properties. Consider the level of precision and appropriate approximation trade-offs in the relationships.
Chapter 12 System Modeling Methodology and Continuous Model Representation 383
The third phase involves converting the model in its current form consisting of a set of variables and a set of equations to a state space equation system representation (see page 402 in this chapter) that fits the numeric solver to be used. A set of state variables needs to be chosen, their time derivatives (for dynamic variables) expressed as functions of state variables and input variables (for the case of state space equations in explicit form), and the output variables expressed as functions of state variables and input variables. If a few unnecessary state variables are included this causes no harm, just some unnecessary computation. This phase is completely eliminated when using Modelica since the conversion to state space form is performed automatically by the Modelica compiler.
12.1.3 Object-Oriented Component-Based Approach When using the object-oriented component-based approach to modeling we first try to understand the system structure and decomposition in a hierarchical top-down manner. When the system components and interactions between these components have been roughly identified, we can apply the first two traditional modeling phases of identifying variables and equations on each of these model components. The objectoriented approach has the following phases:
I. Define the system briefly. What kind of system is it? What does it do? 2. Decompose the system into its most important components. Sketch model classes for these components, or use existing classes from appropriate libraries. 3. Define communication, i.e., determine interactions and communication paths between these components. 4.
Define interfaces, i.e., determine the external ports/connectors of each component for communication with other components. Formulate appropriate connector classes that allow a high degree of connectivity and reusability, while still allowing an appropriate degree of type checking of connections.
5.
Recursively decompose model components of "high complexity" further into a set of "smaller" subcomponents by restarting from phase 2, until all components have been defined as instances of predefined types, library classes, or new classes to be defmed by the user.
6.
Formulate new model classes when needed, both base classes and derived classes: a.
Declare new model classes for all model components that are not instances of existing classes. Each new class should include variables, equations, functions, and formulas relevant to define the behavior of the component, according to the principles already described for the first two phases of the traditional modeling approach.
b.
Declare possible base classes for increased reuse and maintainability by extracting common functionality and structural similarities from component classes with similar properties.
To get more of a feeling for how the object-oriented modeling approach works in practice, we will apply this method to modeling a simple tank system described in Section 12.2 on page 385, and to a DC motor servo in Section 12.3 on page 392.
12.1.4 Top-Down versus Bottom-Up Modeling There are two related approaches to the structuring process when arriving at a model:
•
Top-down modeling. This is useful when we know the application area rather well, and have an existing set of library component models available. We start by defining the top-level system
384 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica
•
model, gradually decomposing into subsystems, until we arrive at subsystems that correspond to the component models in our library. Bottom-up modeling. This approach is typically used when the application is less well known, or when we do not have a ready-made library at hand. First we formulate the basic equations and design small experimental models on the most important phenomena to gain a basic understanding of the application area. Typically start with very simplified models, and later add more phenomena. After some experimentation we have gained some understanding of the application area, and can restructure our model fragments into a set of model components. These might have to be restructured several times if they tum out to have problems when used for applications. We gradually build more complex application models based on our components, and finally arrive at the desired application model.
Section 12.3, page 392, on modeling of a DC-motor from predefmed components gives a typical example of top-down modeling. The small tank modeling example described in Section 12.2 has some aspects of bottom-up modeling since we start with a simple flat tank model before creating component classes and forming the tank model. A better example is the thermodynamic application described in Section 15.2, page 530, which is gradually developed, starting from scratch with very simple model examples. These examples gradually grow into a set of components that are used for the final application models.
12.1.5 Simplification of Models It is sometimes the case that models are not precise enough to accurately describe the phenomena at hand. Too extensive approximations might have been done in certain parts of the model. On the opposite side, even if we create a reasonable model according to the above methodology, it is not uncommon that parts of the model are too complex, which might lead to problems, e.g.: • • •
Too time-consuming simulations. Numerical instabilities. Difficulties in interpreting results due to too many low-level model details.
Thus, there are usually good reasons to consider simplification of a model. It is sometimes hard to get the right balance between simplicity and preciseness of models. This is more an art than a science and requires substantial experience. The best way to acquire such experience, however, is to keep on designing models together with performing analysis and evaluation of their behavior. The following are some hints of where to look for model simplifications, e.g. reduction of the number of state variables:
• •
Neglect small effects that are not important for the phenomena to be modeled. Aggregate state variables into fewer variables. For example, the temperatures at different points in a rod might sometimes be represented by the mean temperature of the whole rod.
Focus modeling on phenomena whose time constants are in the interesting range, i.e.:
• •
Approximate subsystems with very slow dynamics with constants. Approximate subsystems with very fast dynamics with static relationships, i.e. not involving time derivatives of those rapidly changing state variables.
An advantage of ignoring the very fast and the very slow dynamics of a system is that the order of the model, i.e. the number of state variables, is reduced. Systems having model components with time constants of the same order of magnitude are numerically simpler and more efficient to simulate. On the other hand, certain systems have the intrinsic property of having a great spread of time constants. Such systems give rise to stiff systems of differential equations, which require certain adaptive numerical solvers for simulation (see also Chapter 18).
Chapter 12 System Modeling Methodologyand Continuous Model Representation 385
12.2 Modeling a Tank System Regarding our exercise in modeling methodology, let us consider a simple tank system example containing a level sensor and a controller that is controlling a valve via an actuator (Figure 12-1).
Figure 12-1. A tank system with a tank, a source for liquid, and a controller. The liquid level h in the tank must be maintained at a fixed level as closely as possible. Liquid enters the tank through a pipe from a source , and leaves the tank via another pipe at a rate controlled by a valve.
12.2.1 Using the Traditional Approach We first show the result of modeling the tank system using the traditional approach . A number of variables and equations related to the tank system have been collected into the flat model presented in the next section. At this stage we do not explain how the equations have been derived and what exactly certain variables mean. This is described in detail in subsequent sections where the object-oriented approach to modeling the tank system is presented.
12.2.1.1 Flat Tank System Model The FlatTank model is a "flat" model of the tank system with no internal hierarchical "system structure" visible, i.e. just a collection of variables and equations that model the system dynamics. The internal system structure consisting of components, interfaces, couplings between the components, etc ., is not reflected by this model: model FlatTank II Tank related variables and parameters parameter Real flowLevel(unit="m3/s")=0 .02 ; parameter Real area(unit= "m2") =1; parameter Real flowGain(unit="m2/s") =0. 05 ; Real h(start=O,unit ="m") "Tank level" ; Real qlnflow(unit="m3/s") "Flow through input valve"; Real qOutflow (unit="m3/s") "Flow through output valve"; II Controller related variables and parameters parameter Real K=2 "Gain"; parameter Real T(unit="s")= 10 "Time constant"; parameter Real minV=O , maxV=10; 1/ Limits for flow output Real ref = 0 .25 "Reference level for control"; Real error "Deviation from reference level" ; Real outCtr "Control signal without limiter"; Real x; "State variable for controller" ; equation assert (minV>=O, "minV must be greater or equal to zero") ;/1 der(h) = (qlnflow-qOutflow)/area; 1/ Mass balance equation qlnflow = if time>150 then 3*flowLevel else flowLeveli qOutflow = LimitValue(minV,maxV,-flowGain*outCtr); error ref-hi der(x) = error/T;
386 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica outCtr = K*{error+x); end FlatTank;
A limiter function is needed in the model to reflect minimum and maximum flows through the output valve: function LimitValue input Real pMin; input Real pMaxi input Real p; output Real pLim; algorithm pLim := if p>pMax then pMax else if p=O, "minV - minimum Valve level must be >= 0 ,,) ;11 der(h) (qln.lflow-qOut.lflow)/area; II Mass balance equation qOut.lflow LimitValue(minV,maxV,-flowGain*tActuator.act);
388 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica tSensor.val = h; end Tank;
As already stated, the tank has four connectors. These are instances of the following three connector classes: connector ReadSignal "Reading fluid level" Real val(unit="m"); end ReadSignal; connector ActSignal Real act; end ActSignal;
"Signal to actuator for setting valve position"
connector LiquidFlow "Liquid flow at inlets or outlets" Real lflow(unit="m3/s"); end LiquidFlow;
The fluid entering the tank must come from somewhere. Therefore we have a liquid source component in the tank system. The flow increases sharply at time= 150 to factor of three of the previous flow level, which creates an interesting control problem that the controller of the tank has to handle. model LiquidSource LiquidFlow qOut; parameter flowLevel = 0.02; equation qOut.lflow = if time>lS0 then 3*flowLevel else flowLevel; end LiquidSource;
The controller needs to be specified. We will initially choose a PI controller but later replace this by other kinds of controllers. The behavior of a continuous PI (proportional and integrating) controller is primarily defined by the following two equations:
dx
error
-=--
dt T outtltr > K*(error+x)
(12-1)
Here x is the controller state variable, error is the difference between the reference level and the actual level of obtained from the sensor, T is the time constant of the controller, outiltr is the control signal to the actuator for controlling the valve position, and K is the gain factor. These two equations are placed in the controller class PlcontinuousController, which extends the BaseController class defined later. model PlcontinuousController extends BaseController(K=2,T=10)i Real x "State variable of continuous PI controller"; equation der(x) = error/T; outCtr = K*(error+x); end PlcontinuousController;
By integrating the first equation, thus obtaining x, and substituting into the second equation, we obtain the following expression for the control signal, containing terms that are directly proportional to the error signal and to the integral of the error signal respectively, i.e. a PI (proportional and integrating) controller.
J
error ouultr = K * (error + Tdt)
(12-2)
Both the PI controller and the PID controller to be defined later inherit the partial controller class BaseController, containing common parameters, state variables, and two connectors: one to read the sensor and one to control the valve actuator.
Chapter 12 System Modeling Methodology and Continuous ModelRepresentation 389
In fact, the BaseController class also can be reused when defining discrete PI and PID controllers for the same tank example on page 387. Discrete controllersrepeatedly sample the fluid level and produce a control signal that changes value at discrete points in time with a periodicityof Ts. partial model BaseController parameter Real Ts(unit="sU)=O.l parameter Real K=2 parameter Real T=10(unit="s") ReadSignal cIn ActSignal cOut parameter Real ref Real error Real outCtr equation error ref-cIn.val; cOut.act outCtr; end BaseController;
"Time period between discrete samples"; "Gain"; "Time constant"; "Input sensor level, connector"; "Control to actuator, connector"; "Reference level"; "Deviation from reference level"; "Output control signal";
We simulate the TankPI model and obtain the same response as for the FlatTank model, which is not surprising given that both models have the same basic equations (Figure 12-4). simulate (TankPI, stopTime=250) plot (tank.h)
50
100
150
200
250
time
Figure 12-4. The tank level response for the TankPI system containing a PI controller.
12.2.4 Tank with Continuous PIC Controller We define a TankPIO system which is the same as the TankPI system except that the PI controller has been replaced by a PID controller. Here we see a clear advantage of the object-oriented component-based approach over the traditional modeling approach, since system components can be easily replaced and changed in a plug-and-play manner (Figure 12-5).
TankPID
Figure 12-5. The tank system with the PI controller replaced by a PIO controller. The Modelica class declaration for the TankPID system appears as follows: model TankPID
390 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with ModeJica LiquidSource source(flowLevel=O.02)i PIDcontinuousController pidContinuous(ref=O.2S)i Tank tank(area=l)i equation connect (source.qOut, tank.qln)i connect (tank.tActuator, pidContinuous.cOut}i connect (tank.tSensor, pidContinuous~cln); end TankPIDi
A PID (proportional, integrating, derivative) controller model can be derived in a similar way as was done for the PI controller. PIO controllers react quicker to instantaneous changes than PI controllers due to the term containing the derivative. A PI controller on the other hand puts somewhat more emphasis on compensating slower changes. The basic equations for a PID controller are the following:
dx
error dt T d error y= T dt outetr= K*(error+x+ y)
-=--
(12-3)
We create a PIDcontinuousController class in Modelica containing the three defining equations: model PIDcontinuousController extends BaseController(K=2,T=10)i Real Xi II State variable of continuous PID controller Real Yi II State variable of continuous PlD controller equation der(x) error/Ti y T*der(error)i outCtr K*(error + x + Y)i end PIDcontinuousControlleri
By integrating the first equation and substituting x and y into the third equation, we obtain an expression for the control signal which contains terms directly proportional, proportional to the integral, and proportional to the derivative of the error signal, i.e., a proportional integrating derivative (PID) controller. error d error outCtr= K*(error+ --dt+T--) T dt
J
We simulate the tank model once more but now including the PID controller (Figure 12-6): simulate {TankPID, stopTime=2S0) plot (tank.h)
0.4
0.3
0.2
0.1
-f-------~------------ time 200 250 100 150 50
Figure 12-6. The tank level response for the TankPID system containing a PID controller.
(1
2-4
)
Chapter 12 System Modeling Methodology and Continuous Model Representation 391
The tank level as a function of time of the simulated system is quite similar to the corresponding system with a PI controller, but with somewhat faster control to restore the reference level after quick changes of the input flow. The diagram in Figure 12-7 shows the simulation results from both TankPI and TankPID plotted in the same diagram for comparison. simulate (compareControllers, stopTime=250) plot({tankPI.h,tankPID.h}) ------ tankPI.h - - - tankPID.h
0.4
0.3
0.2
0.1
50
100
150
200
time 250
Figure 12-7. Comparison of TankPI and 'fankPID simulations.
12.2.5 Two Tanks Connected Together The advantages of the object-oriented component-based approach to modeling become even more apparent when combining several components in different ways, as in the example depicted in Figure 12-8 where two tanks are connected in series, which is not uncommon in process industry.
TanksConnectedPI
Figure 12-8. Two connected tanks with PI controllers and a source for liquid connected to the first tank. The Modelica model TanksConnectedPI corresponding to Figure 12-8 appears as follows:
model TanksConnectedPI LiquidSource source(flowLevel=O.02); Tank tankl{area=l); Tank tank2(area=1.3); PlcontinuousController piContinuousl(ref=O.2S); PlcontinuousController piContinuous2(ref=O.4); equation connect{source.qOut,tankl.qln); connect(tankl.tActuator,piContinuousl.cOut)i connect(tankl.tSensor,piContinuousl.cln) i connect(tankl.qOut,tank2.qln) ; connect(tank2.tActuator,piContinuous2.cOut)i connect(tank2.tSensor,piContinuous2.cln)i end TanksConnectedPI;
392 Peter Fritzson Principles of Object-OrientedModeling and Simulation with Modelica We simulate the connected tank system. We clearly see the tank level responses of the first and second tank to the changes in fluid flow from the source, where the response from the first tank of course appears earlier in time than the response of the second tank (Figure 12-9). simulate (TanksConnectedPI, stopTime=400) plot ({tankl.h,tank2 .h}) tank1 .h
0.8
t a nk 2.h 0 .6
, '''' ..... _---------
0 .4 0.2
10 0
20 0
300
4 00
t ime
Figure 12-9. The tank level responses for two tanks connected in series.
12.3 Modeling of a DC-Motor Servo from Predefined Components In this section we illustrate the object-oriented component-based modeling process when using predefined library classes by sketching the design of a DC motor servo model. We do not go into any detail since the majority of the used classes are described in the context of the DC motor application presented in Section 15.1, page 524, and the previous tank example was presented in quite some detail.
12.3.1 Defining the System What does a DC motor servo do? It is a motor, the speed of which can be controlled by some kind of regulator (Figure 12-10). Since it is a servo, it needs to maintain a specified rotational speed despite a varying load. Presumably it contains an electric motor, some mechanical rotational transmissions and loads, some kind of control to regulate the rotational speed, and some electric circuits since the control system needs electric connections to the rest of the system, and there are electric parts of the motor. The reader may have noticed that it is hard to define a system without describing its parts, i.e., we are already into the system decomposition phase.
Figure 12-10. A DC motorservo.
12.3.2 Decomposing into Subsystems and Sketching Communication In this phase we decompose the system into major subsystems and sketch communication between those subsystems . As already noted in the system definition phase, the system contains rotational mechanical parts including the motor and loads, an electric circuit model containing the electric parts of the DC motor
Chapter 12 System Modeling Methodology and Continuous Model Representation 393
together with its electric interface, and a controller subsystem that regulates the speed of the DC motor by controlling the current fed to the motor. Thus there are three subsystems as depicted in Figure 12-11: controller, an electric circuit, and a rotational mechanics subsysterrr, Regarding the communication between the subsystems, the controller must be connected to the electric circuit since it controls the current to the motor. The electric circuit also needs to be connected to the rotational mechanical parts in order that electrical energy can be converted to rotational energy. Finally, a feedback loop including a sensor of the rotational speed is necessary for the controller to do its job properly. The commutation links are sketched in Figure 12-11. Electrical Circuit
~
Controller
Rotational Mechanics
f---
I
I
Figure 12-11. The subsystems and their connections.
12.3.3 Modeling the Subsystems The next phase is to model the subsystems by further decomposition. We start by modeling the controller and manage to find classes in the standard Modelica library for a feedback summation node and a PI controller. We also add a step function block as an example of a control signal. All these parts are shown in Figure 12-12.
,,
...,
\
\
\
,,
~ontroller
,
\
I---
l" \
\
\
\
,, ,
,
\
\
\
\
\
\
\
\
... ... ,
....
....fJectrical
CiibHt... ........ ,,
... ,
~
....
Rotational Mechanics
. . . . ....... , ... I ....
' ......
........
........
.............
\
Figure 12-12. Modeling the controller.
The second major component to decompose is the electric circuit part of the DC motor (Figure 12-13). Here we have identified the standard parts of a DC motor such as a signal-controlled electric voltage generator, a ground component needed in all electric circuits, a resistor, an inductor representing the coil of the motor, and an electromotoric force (EMF) converter to convert electric energy to rotational movement.
Figure 12-13. Modeling the electric circuit.
394 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica The third subsystem, depicted in Figure 12-14, contains three mechanical rotational loads with inertia, one ideal gear, one rotational spring, and one speed sensor for measuring the rotational speed needed as information for the controller.
spring 1 speedSensorl
Figure 12-14. Modeling the mechanical subsystem including the speed sensor.
12.3.4 Modeling Parts in the Subsystems We managed to find all the needed parts as predefined models in the Modelica class library. If that would not have been the case, we would also have needed to define appropriate model classes and identified the equations for those classes, as sketched for the parts of the control subsystem in Figure 12-15, the electric subsystem in Figure 12-16, and the rotational mechanics subsystem in Figure 12-17.
Figure 12-15. Basic equations and components in the control subsystem. The electric subsystem depicted in Figure 12-16 contains electrical components with associated basic equations, e.g., a resistor, an inductor, a signal voltage source, and an electromotoric force (EMF) component. II I
.
di =Ldt
/
induct orl
EMFI
.
I
1=1:I ' ' mf Figure 12-16. Defining classes and basic equations for components in the electric subsystem.
Chapter 12 System Modeling Methodology and Continuous Model Representation 395 The rotational mechanics subsystem depicted in Figure 12-16 contains a number of components such as inertias, a gear, a rotational spring, and a speed sensor.
~
ldealGear1
.> 8 2 = k8.
Inertla/ r i n91
T 4
1
T 2 =-T I k2
speedSensor1
=k)(8) - 8 2 )
T ) =T 4
Figure 12-17. Defining classes and basic equations for components in the rotational mechanics subsystem.
12.3.5 Defining the Interfaces and Connections When each subsystem has been defined from predefined models, the interfaces to the subsystem are given by the connectors of those components that interact with other subsystems. Each subsystem has to be defined to enable communication with the other subsystems according to the previously sketched commutation structure. This requires the connector classes to be carefully chosen to be type compatible. Actually, the selection and definition of these connector interfaces is one of the most important steps in the design of a model. Control
Electric:
Rotatl onai Mechanics
r--------------------ir------------------l 1-------------------.-----------------1
ID-'«dbIcki
,
I
I I
, , I
I,
II I,
_ supl
L_________ _
I, ,I JL__ ~~~~ I,
PI!
ro>Islor1
Inductor!
EMF1
II ,
'
I
'
I I .L
,II lL
II ~ I ........1
I I
II I
spmg l
~~~~ _
-I
Figure 12-18. Finalizing the interfaces and connections between the subsystems. including the feedback loop. The completed model of the DC motor servo is depicted in Figure 12-18, including the three subsystems and the feedback loop .
12.4 Designing Interfaces-Connector Classes As in all system design, defining the interfaces between the components of a system model is one of the most important design tasks since this lays the foundation for the communication between the components, thereby also heavily influencing the decomposition of the model. Most important is to identify the basic requirements behind the design of component interfaces, i.e., connector classes, that influence their structure. These requirements can be briefly stated as follows:
• •
It should be easy and natural to connect components. For interfaces to models of physical components it must be physically possible to connect those components. Component interfaces should facilitate reuse of existing model components in class libraries.
396 Peter Fritzson Principles of Object-Oriented Modelingand Simulation with Modelica Fulfilling these goals requires careful design of connector classes. The number of connector classes should
be kept small in order to avoid unnecessary mismatches between connectors due to different names and types of variables in the connectors. Experience shows that it is surprisingly difficult to design connector classes that satisfy these requirements. There is a tendency for extraneous details that are created during software (model) development for various computational needs to creep into the interfaces, thereby making them harder to use and preventing component reuse. Therefore one should keep the connector classes as simple as possible, and try to avoid introducing variables that are not really necessary. A good role of thumb when designing connector classes for models of physical components is to identify the characteristics of (acausal) interaction in the physical real world between these components. The interaction characteristics should be simplified and abstracted to an appropriate level and reflected in the design of the connector classes. For nonphysical components, e.g. signal blocks and software components in general, one has to work hard on finding the appropriate level of abstraction in the interfaces and trying these in practice for feedback on ease-of-use and reusability. The Modelica standard library contains a large number of well-designed connector classes which can serve as inspiration when designing new interfaces. There are basically three different kinds of connector classes, reflecting three design situations: 1. If there is some kind of interaction between two physical components involving energy flow, a combination of one potential and one flow variable in the appropriate domain should be used for the connector class. 2. If information or signals are exchanged between components, input/output signal variables should be used in the connector class. 3. For complex interactions between components, involving several interactions of type (1) and (2) above, a hierarchically structured composite connector class is designed that includes one or more connectors of the appropriate type (1), (2), or (3). When all the connectors of a component have been designed according to the three principles above, the formulation of the rest of the component class follows partly from the constraints implied by these connectors. However, these guidelines should not be followed blindly. There are several examples of domains with special conditions that deviate slightly from the above rules. The topic of designing connector classes is discussed in more detail, including a number of examples, in Section 5.5 on page 158 in Chapter 5.
12.5 Block Diagram Models A block diagram model can be regarded as a special case of model for which the causality of each interface variable has been fixed to either input or output. Such models for example, can be represented by Modelica models which have the prefixes input or output on all their connector variables, and thereby fulfill the requirements for the restricted block class in Modelica. Before digital computers became common, analog computers were used for simulation. These were a physical realization of block diagrams in terms of building blocks such as multipliers, adders, integrators, etc., as depicted in Figure 12-19. These are graphical representations, e.g., of basic mathematical operations like multiplication, addition, integration, etc., that also can be expressed in textual programming language syntax. The well-known Simulink~ product realizes block diagrams on digital computers and provides a graphical user interface where block diagrams can be specified, as well as an environment where block diagram models can be simulated.
Chapter 12 System Modeling Methodology and Continuous Model Representation 397
Muhiplier
Adder
Integrator
Function
Branch Point
Figure 12-19. Examples of common block diagrams. A block diagram is a more primitive model concept than general Modelica classes in the sense that it is valid only for specific data-flow context and thereby is less reusable. It represents a signal-oriented way of thinking, where the signal direction in terms of data flow is always known. Block diagrams consist of blocks that are connected by arrows. A block is a transducer that transforms the incoming signals to one or more output signals. A block can represent simple arithmetic operations or functions without memory, but also operations whose results are dependent on previous input to the block, i.e. with memory. Hierarchical decomposition is supported since connected bJ.ocks forming a block diagram can itself be treated as a block. While a block diagram clearly depicts the data flow in a system, it does not preserve any of the structure of the system itself, as can be seen in the block diagram model of the DC motor servo in Figure 12-20. A small change in the model or in the set of variables we want to study may force us to rearrange the entire structure of the block diagram, which may have little similarity to the previous version. This is a clear disadvantage of a block diagram that forces many engineers in industry to redesign the block diagram models over and over again.
r--------------------------------------------------------Electric
R --------'
r--------------------------------------------------- -
I
I
~~
I~~ ~
~
!...---------I II
-
_
--------------------------------------
1
I I I I I
I I I
~
r --------------- -------------------------------------- Rotational Mechanics
T load
Figure 12-20. A block diagram model of the DC motor servo.
398 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica These disadvantages are not as noticeable in control engineering, where block diagrams are quite popular. The reason is that control engineers force their circuits to behave in such a way that the signal flow structure and the topological structure coincide, e.g. by effectively decoupling stages and using feedback loops. A number of common block classes, e.g. for use in control applications, are available in the Modelica library Modelica. Blocks, see Section 16.6, page 623).
12.6 Categories of Variables and Constants in Mathematical Models It is rather obvious from the previous discussions of mathematical models and presented examples that several different categories of variables and constants can be present in those models. For a certain model under some experimental conditions, some variables play roles as inputs, others as outputs, others are internal state variables, and some are not variables but constants since they keep the same value over time.
12.6.1 Input, Output, State Variables, and Constants The following is a list of definitions concerning variables and constants having different roles in mathematical models (see also Section 17.1.3, page 655). These roles are usually not a property of the model or the modeled system as such, but rather a consequence of a combination of a model, some experiments, or simulation, and conditions given by what we want to study. However, we should be aware that models can be formulated in more or less general or reusable ways. An acausal equation-based model fits many different data-flow contexts with different roles of variables, e.g. as inputs or outputs, whereas a model for which the variables have been fixed in either input or output roles only fits a few experimental settings.
• •
Constant-a quantity in the model that does not vary with time. Such a quantity is declared with the constant prefix in Modelica. Model parameter-a constant in the model that is determined by the system, i.e. a system parameter, or a constant that can be changed in order to give the system different properties, i.e. a design parameter. It is declared with the parameter prefix in Modelica, and is constant during a
• •
Variable-a quantity in the model that varies with time, sometimes also called signal. Output variable-a variable whose behavior we want to observe. Usually denoted by y(t). Whether
simulation run, but can be modified between simulation runs.
a variable is an output variable is not a property of the modeled system, but is determined by what we want to study. However, it is often the case that we also want to observe a few state variables (see below).
•
•
Input variable-a variable that affects the model behavior without being affected by the model's other variables, i.e. an external signal, and whose time variations we can control, usually denoted by u(t). Disturbance signal-an external signal whose time variations we cannot affect, usually denoted by w(t), but usually u(t) and w(t) are grouped together into a single input vector denoted u(t).
• •
Internal variable-a model variable that is neither an output, an input, nor a disturbance signal. State variable-for continuous-time ODE models: an internal variable whose time derivative appears in the model, usually denoted by x(t), and its time derivative by x(t). A state variable must be of type Real or a subtype of Real in Modelica. If we want to study some state variable x;(t), we can always introduce a corresponding output variable YJ{t) together with an equation YJ{t)=x;(t), or directly observe the state variable. For hybrid models containing discrete-time variables, a more general but less precise definition might be appropriate: a variable that needs to be stored and updated during the simulation in-order to compute the output. For DAEs the set of
Chapter 12 System Modeling Methodology and Continuous Model Representation 399 state variables is a selection of some dynamic variables x(t) together with some algebraic variables
•
yet) (see also Section 18.2.6, page 686). Algebraic variable-a variable that appears in algebraic equations, but whose derivative does not appear in the model, usually included in the set of variables denoted by y(t) even if we are not interested in observing that variable.
Any of the above-mentioned model variables-y(t), u(t), w(t), x(t) and x(t)--ean denote a scalar if there is just one variable of that kind in the model, but usually a vector, i.e.:
x(t)
XI (t») = : , (
x n (t)
y(t) =
YI(t») :
( Yr(t)
,
u(t)
(UI(t») : ,etc.
=
(12-5)
um(t)
A block diagram model of a generic system with outputs y(t), internal state variables x(t), controllable inputs u(t), and disturbance inputs w(t) is depicted in Figure 12-21. In the following we group u(t) and w(t) together into a single input vector denoted u(t). w(t)
x(t) , i(t)
u(t)
y(t)
Figure 12-21. A simple block diagram modei of a generic system.
12.7 Types of Equations in Mathematical Models So far we have seen many examples of equations in Modelica models. One might ask what is a natural classification of different categories of equations in mathematical models intended for simulation, and what subset of those categories can be represented in the Modelica language? The form of equations derived from simple Modelica models was briefly discussed in Chapter 2, Section 2.20.1, page 58. In this section we will give a short overview of different types of equations and their relation to Modelica, whereas in Chapter 17, page 653, we will go into more depth concerning the general form of the hybrid DAE representation that is used to represent the full range of mathematical models expressible in Modelica, We exclude integral equations from this overview.
12.7.1 Ordinary Differential Equations-ODEs Ordinary differential equations (ODEs), arise in most mathematical models of continuous dynamic systems since the time dependency in those systems usually is reflected by the presence of time derivatives of state variables of the corresponding models. Newton's force law that the force F is equal to the mass m times the second-derivative s of the position s with respect to time (i.e., the acceleration) is a simple example of a second order ODE: ms(t)
= F(t)
(12-6)
By introducing an additional variable v(t) we can get rid of the second derivative. After a slight rearrangement of the first equation we have all derivatives on the left-hand side (in explicit form) and they are all first-order derivatives. This means that we have transformed the system into a first-order ODE system in explicit form:
400 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
v(t)
= F(t) m
s(t)
(12-7)
=v(t)
An ODE system in this form is especially efficient to solve numerically. The general structure of an ODE system in explicit state space form is the following, with inputs u(t), outputs y(t), and state variables x(t):
=f(x(t),u(t» y(t) = g(x(t),u(t» x(t)
(12-8)
Here we have also introduced outputs y(t) that are directly computable from the state variables and the inputs but do not influence the solution for the state variables x(t).
12.7.2 Algebraic Equations Algebraic equations are relations between variables not involving derivatives of any variables. Such equations arise naturally in models of natural and artificial systems, especially when some kind of constraint is involved .
...."
=
=1 0 . 0 in the when-equation below will cause a time-event at time=10.0 since it becomes true at approximately (floating-point numbers might not be exact) that time instant: when time>=10.0 then end when;
Another way to cause a time event is to pass a time expression as an argument to one of the built-in mathematical functions with discontinuities described in Section 13.2.5.12, page 420 in this chapter, e.g. as in the function call sign (time-IO). The built-in functions sample, initial, and terminal described in Section 13.2.5, page 413, can also be used to create time events since they become true at wellspecified instants in time. Time events are primarily used for model related reasons.
13.2.4.3 State Events State events usually cannot be scheduled in advance, and are related to value changes in the state variables of a model in a wide sense, also including input and output variables. A state event can be induced by a conditional expression involving at least one state variable, e.g. as in the when-equation below where an event is generated and handled each time sin (x) becomes greater than 0.5 as a result of value changes in the state variable x: when sin(x»O.5 then end when;
A state-event can also be induced by passing an expression containing a reference to a state variable to one of the built-in functions described in Section 13.2.5.12, e.g. as in mod (x - 5 , 2) . The Modelica simulator. is continually watching event-inducing expressions, e.g. the above examples sin(x»O.s and mod(x- 5,2), during the numerical solution of the continuous part of the system of equations. State events can be created for modeling reasons as in the above when-equation. However, a more common use is automatic triggering of state events to get better performance and to avoid numerical difficulties for the solver at discontinuities.
13.2.5 Event-Related Built-in Functions and Operators Modelica provides a number of built-in functions and operators related to events and time, which you will find quite useful in discrete and hybrid modeling. Some functions generate events, some can be used to express conditions for triggering events, one function prevents events, and some operators and functions provide access to variable values before the current event as well as causing discontinuous change of variable values at an event.
13.2.5.1 Initialization Actions Triggered by Initial() The function call initial () returns true at an instant immediately before the beginning of the simulation, when time still is equal to time. start (usually time=O). By using initial () somewhere in the code we can generate a fictitious event immediately before the start of the simulation, e.g. as depicted in Figure 13-7.
414 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
initial() true
false -------------------~ event at start time
t
Figure 13-7. The function initial () returns true at an event at the start of the simulation. The typical use of initial () is in conditions for when-equations, e.g. as below, sometimes used for possibly needed additional initialization of discrete-time variables in addition to the initial values provided by the start attributes of those variables.
when initial() then II some initialization or other actions end; In fact, if ini t ia1 () is part of the conditions of a when-equation or when-statement, the equations within the when-equation or statements within the when-statement become part of the initialization equation system to be solved before start of simulation. Another way of specifying behavior at the initial time is by the initial equation construct. A more thorough discussion of initialization based on initial equation, initial (), and the start attribute can be found in Section 8.4, page 250.
13.2.5.2 Using terminal() to Trigger Actions at the End of a Simulation The function call terminal () returns true at an instant at the end of a successful simulation. If it is used somewhere in the code it can trigger an event as depicted in Figure 13-8. terminal()
true
false
L--
~
Figure 13-8. The function tenninal() returns true at an event at the end of the simulation. This is typically used to trigger actions at the end of a simulation, e.g. calling an external function to store some data on the file system. If the simulation is not successful it will be aborted prematurely, and terminal () will never return true during this simulation.
when terminal() then II some action at the end of the simulation end when;
13.2.5.3 Terminating a Simulation Using terminate() Since we have been discussing the termination of a simulation in the previous section, it can be useful to briefly recapitulate terminate, which is described in more detail in Section 9.2.10.3 on page 298 in Chapter 9. The statement terminate (message) causes a successful termination of the simulation and passes the message string to the simulation environment in order to inform the user. The reason might be
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 415 that it is no longer relevant to continue the simulation, e.g. as in the moon landing example on page 76 in Chapter 3 when the moon lander is starting to sink below the surface because the simulation has gone outside the domain where the model is valid. If you would like to check for conditions that when violated should cause abortion of the simulation, i.e., unsuccessful termination, you should instead use the assert () statement, which is described in more detail in Section 9.2.10.2 on page 298 in Chapter 9.
13.2.5.4 Generating Repeated Events Using sample() The function sample (first, interval) returns true and can be used to trigger events at time instantsfirst + i*interval (i=O,l, ...), where first is the time of the first event and interval is the time interval between the periodic events. It is typically used in models of periodically sampled systems.
~~ sample(tO,d) true
false
'--------------&------------------1•.......... to
to+d
to+2d
to+3d
to+4d
time
Figure 13-9. The call sample (to, d) returns true and triggers events at times to+i *d, where i=O, 1, etc.
The function acts as a kind of clock that returns true at periodically occurring time instants (Figure 13-9). We can use this behavior in combination with a when-equation to periodically trigger events, e.g. as below: class SamplingClock parameter Modelica.Slunits.Time Boolean clock; equation clock = sample (first, interval) ; when clock then
first, interval;
end when; end SamplingClocki
You should note that the function sample always returns false between the events it generates, i.e., during the solution of the continuous part of the equation system that is going on as part of the simulation between events. The starting time stan and the sample interval need to be parameter expressions, i.e., they are constant during simulation, and need to have Real or Integer types, or subtypes of those types, e.g. Modelica. SIunits. Time, which is a subtype of Real.
13.2.5.5 Preventing Events Using noEvent() The function noEvent texpri evaluates and returns the expression expr in a way that prevents generating events. Suppressing events for an expression is useful, e.g. to prevent expressions like log (x) and sqrt (x) protected by guards like x s 0 from going outside their domain of validity--in this case to prevent negative values ofx. The expression x s O is a discrete-time expression with possible values true and false. We need to search for the value of x for which the event will OCCUf, i.e., when x>o switches between false and true. This occurs at the zero-crossing of the expression x- 0, i.e., when the expression switches from negative to positi ve value or vice versa.
416 Peter Fritzson Principles of Object-Oriented Modeling andSimulation withModelica To performthis zero-crossing search for an expression, e.g. for sqrt (x) , it is necessary to evaluate the expression also for small negative values of x, which will cause problems for the above type of expressions. By contrast, noEvent (x>O) is an example of a continuous-time expression that does not generate events and therefore avoids these problems by not performing any zero-crossing search. See Section 18.2.5.5, page 685, for a morethoroughdiscussionregarding zero-crossing functions. Another use for noEvent is to slightly improve performance for expressions that are continuous despite the fact that they normallygenerateevents, e.g. as in the example below (Figure 13-10). However, to improveperformancefor continuousexpressionsit is better to call smooth () (see Section 13.2.5.6).
event
time
time
Figure 13-10. The expression noEvent texpri avoids generating events thatotherwise would be triggered byexpr. For example,consider the equation: equation z = if x and delay (expr, delay'Iime) . Both variants return the value of expr at the time (time-delayTime) , i.e., its value at a point in time delayTime earlier compared to the value of the current simulated time represented by the built-in time variable. During an initial period of length delayTime at the beginning of the simulation when time. start =1 then x := pre(x)+1; end when;
13.2.6.5 Event Synchronization and Propagation
Events often need to be synchronized and propagated. However, Modelica gives no guarantee that two different independentevents occur at exactly the same time instant if they are not explicitly synchronized, e.g. via equations. This has to do with the fact that Modelica deals with both continuous and discrete system modeling, in contrast to certain purely discrete modeling languages that may provide implicit synchronization of events using a central clock. For example, events triggered by independent calls to sample, e.g. sample( 0, 3 .3), may not necessarily occur at exactly the same time instants as those triggered by sample(O, 1.1). Numerical roundoff errors can create small differences in the time values even though the first sample period appears to be a multiple of the second one. Of course, two or more independent events may actually occur at the same time instant, but MOOeHea gives no guarantee of synchronizationif the events are not coupled by equations. To achieve guaranteed synchronization between two events, we use the synchronous principle that computation at an event takes no time. An event can instantaneously via one or more equations change the values of certain discrete-time variables used for the synchronization, typically Boolean or Integer variables. These changes may trigger other events without any elapsed time, which thereby are synchronized. For example, you can synchronize counters performing their counting behavior at different frequencies, e.g. as in the example below. The equation involving slowPulses and count synchronizes the two counters, i.e., slowPulses = mod (count, 2) ==0. model SynchCounters Boolean slowPulses; Boolean fastPulses;
II Two synchronized counters
Integer count, slowCount;
equation fastPulses = sample(l,l); when fastPulses then II Count every second count pre (count) +1; slowPulses = mod(count,2)==O; II true when count=2,4,6, ... end when; when slowPulses then II Count every 2nd second slowCount = pre(slowCount)+l; end when; end SynchCounters;
Figure 13-17 shows the two synchronized counters count and slowCount in a simulation of the SynchCounters model. The slowPulses when-equation is evaluated at every 2nd occurrence of the fastPulses when-equation. The single assignment rule and the requirement to explicitly model the synchronization of events in Modelica allow a certain degree of model checking and error detection already at compile time. For example, a kind of "deadlock" between different when-equations is present if there are mutual dependencies, a so-called "algebraic loop," between the equations of the when-equations, as in the example below. This case should be detected by a Modelica compiler.
426 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica --count ------- slowCount
5 4
3
!
2
1 1
2
. 3
r----------------.l 5
4
time
6
Figure 13-17. Two synchronized counters, where the slow counter is incremented every 2nd pulse of the fast counter. In general, as is well known from process programming theory, deadlocks can occur between mutually dependent parallel processes competing for the same resource. In Modelica each when-equation can be thought of as specifying a kind of parallel process. However, the great advantage here is that the deadlock is detected at compile time in contrast to asynchronous parallel programming languages where deadlocks often cause problematic bugs first noticed at run-time. model DeadLock Boolean bl,b2; equation when bl then
II by a more realistic example
b2 = true; end when; when b2 then bl = true; end when; end DeadLock;
After having focused on event synchronization for a while, we will now tum to general propagation of events of which synchronization is a special case. Furthermore, we should not forget that an event also might involve the change of continuous variables, which might be used in equations and conditions of other models and when-equations. Propagation of events thus might require evaluation of both continuous equations and conditional equations. Regarding simple propagation of events, Boolean variables are quite useful. For example, a level sensor in a tank may generate a tank . level measurement value. If the tank . level variable exceeds a certain tank. maxl.eve l., an overflow event should be generated and propagated (Figure 13-18). For propagation of the overflow event we declare a variable called overflowing in the connector out belonging to the level sensor, and define the variable by a Boolean equation, e.g.:
levelSensor.out.overflowing
maxLevel ~_._._ level
>
tank.maxLevel;
levelSensor out
tank
= tank. level
in
pump
Figure 13-18. A level sensor in a tank may set the variable overflowing to true, causing an event which propagates to the pump via the connection between the connectors out and in.
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 427 Furthennore, we connect the level sensor to a pump to be able to automatically start pumping when an overflow happens in order to reduce the level. This is modeled by connecting the levelSensor. out connector to the pump. in connector as below: connect (levelSensor.out, pump. in) ;
This connection generates an equation for the Boolean variable overflowing, which enables propagation of overflow events from the level sensor to the pump: levelSensor.out.overflowing = pump.in.overflowing;
The pump might react on such events by testing its corresponding variable in. overf lowing from its connector pump. in. The condition for starting pumping, for example, could be either tank overflow or the user pushing a start button on the pump: startPumping = in.overflowing or startPushed;
For simulation, these equations need to be solved for the variable pump. startPumping. Equations that define boolean variables usually need to have a simple form in order to be solvable. There should be a single Boolean variable on the left-hand side or on the right-hand side of such equations. 13.2.6.6 Multiple Events at the Same Point in Time and Event Iteration Multiple events may actually occur at the same point in time, as hinted at in the previous section about event synchronization. Two or more independent events may just happen to be fired at the same time instant, or additional events may be fired at the time instant as a consequence of handling one of the events at that time instant. It is useful to maintain a well-defined ordering between events also if they occur at the same time instant when time ordering is not possible. An important reason is to provide a deterministic execution, i.e., the simulation will always give the same results given the same input data. Two rules can be used to define this ordering, where the first is mandatory and the second is somewhat arbitrary since it is not supported by the Modelica language specification: • •
Data dependency order. Declaration order.
The data dependency order is determined by data-flow dependencies from defining equations to event conditions. For example, in the model MUltipleEvents below the event handler c gives the new value 2 to the variable x, which in tum causes the event condition x==2 of the event handler A to become true, thereby generating an additional event at the same time instant. The handler A subsequently gives x the value 3, which triggers the event B. This gives the ordering: C ~ A ~ B. Note that when several events are generated at the same time instant, the value of the pre function, e.g. pre (x) in the example below, refers to the value of x previous to the current event according to the event ordering, and not to the value of x immediately before the current time instant. The declaration order or some other deterministic ordering rule could in principle be used to order the independent events c and D, which both occur at the same time instant when time=2. However, since declaration order is not supported by Modelica we need to use e 1 sewhen for priorities. Using "declaration order" and elsewhen, we obtain the ordering c ~ D, since the event handler for c occurs before the one for D in the elsewhen-sequence in the Modelica code below. model MultipleEvents discrete Integer x(start=l);
Boolean
signal(start=False);
equation when x==2 then
x
=
pre(x)+l;
elsewhen x==3 then x = pre(x)+5i
II Event handler A II x becomes 2+1 II Event handler B II x becomes 3+5
3 8
428 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica end when; when time>=2 then II Event handler C x = 2; II x becomes 2 elsewhen time>=2 then II Event handler D signal = true; end when; end MultipleEvents;
The second issue concerns the event-handling order in the queue of events pending at the same time instant. For example, the ordered set of events {C,D} is initially pending at time=2. According to the above ordering rules, C is serviced first. What happens next is dependent on the event-handling ordering algorithm. The simplest algorithm would always service the first event according to the event ordering. In theory, but not in this example, c might cause the c event to be triggered once more and thereby be serviced first again since it comes first in the event ordering, giving the C event unfair advantages. A servicing algorithm that is more fair would handle the remaining events in the queue before coming back to the first event. Such an algorithm is sketched below, where steps 1--4 are repeated until you exit from the algorithm: 1. Determine the ordered set of pending events. 2. If this set is empty, i.e., no conditions for conditional equations are true, exit this algorithm and continue continuous simulation and/or future time-event handling. 3. Otherwise handle the first event in the ordered set of pending events. 4. For each of the remaining events in the ordered set, check if the event condition is still true, and if this is the case, handle the event. It is possible to formulate models for which this algorithm never terminates, However, in practice, for most practical models the algorithm terminates within a few iterations. This kind of iterative procedure is also known as event iteration. Note that according to step 2 in the algorithm all event conditions (e.g. typical edge conditions for when-equations) are false at exit. This kind of algorithm also assumes that it is possible to compute a consistent state after handling each event. If we apply the algorithm to the above MultipleEvents example, the following sets of ordered pending events are created and serviced in order: 1. The initial ordered set of pending events is determined to be (c. D} at time = 2. First service C, then D. 2. The next set of pending events is {A}, since event c triggers A. 3. The next set becomes {D}, since A triggers D. 4. The final set is {}, i.e., .empty, causing, exit from the algorithm and continuation of continuous simulation and handling of future events. This is just an example of an event-servicing algorithm. The Modelica language specification does not prescribe any special algorithm, thereby giving freedom to the Modelica language implementer to invent even better algorithms.
13.3 Discrete Model Examples and Related Formalisms The purpose of this section is to provide you with a number of model examples of different kinds of discrete systems, and to compare with several well-known discrete modeling formalisms. You will see that the modeling power of Modelica is quite sufficient to conveniently represent models based on these formalisms.
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 429
13.3.1 Sampled Systems A simple type of discrete-time model is the sampled data model often used in applications because of its simplicity and favorable analytical properties. A sampled model is characterized by its ability to periodically sample continuous input variables u( t), calculate new outputs y that can influence the physical world as well as continuous parts of the model, and update discrete-time state variables x. Both the output variables y and the state variables x keep their values between the sample events since they are discrete-time variables. Such a sampled system model is schematically depicted in Figure 13-19. A sampled system model has only one kind of event, the sample event, and can be represented by the following state space equations:
= !(Xk 'Uk ,tk ,tlc+1) Yk = h(Xk .u, ,t k )
Xl:+ 1
(13-6)
Here Xk is a sequence of state vectors or scalars, Uk is a sequence of sampled input vectors or scalars, and Yk is a sequence of output vectors or scalars at points in time t = to,tl,... ,tk,lk+I,... etc. In a real-time environment, periodic sampling is usually assumed with t k = k T, k = 0,1,2,3,... , where T is the fixed sample interval. At any sample event occurring at time tA;, the model should compute Xk+1 and Yk depending on Uk and X/c. It is important that the input Uk can propagate through the system without any time delay, since the input might be the output of another subsystem.
Physical World
Figure 13-19. A sampledsystem wherea computerobtains sampledinputs Ul and controls the continuous physical world through the output signals Yl. The current discretestate is represented by Xl:, and the
computedstate to be used at the next sampleevent is X1c+J. The discrete state space model in equation (13-6) can be derived from the usual continuous-time state space model: (13-7)
i(t):: j(x(t),u(t» y(/) = h(X(/), uit)
using the Euler approximation of the derivative x(t): .( ) xt k
(13-8)
X(lk+I)-X(t lc )
=::-~--~
IIc+1 - I k
By substituting the above approximation for x(t/c) into the continuous state space model equations and doing a few rearrangements, we obtain the following approximate state space equations on a difference equation form: X(l k+1) = !(x(t k ),u(tk ),tk,lk+l) = x(t k)
y(l k ) = h(x(tk ),U(lk»
+ (t/c+l
- tic )j(x(t lc ),U(lk »
(13-9)
430 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Using the definitions below for Xt, Xk+l, us, and Yk we obtain the previously presented state space equations for sampled systems. In the following Modelica models of sampled systems we will use the notation u, y, x, and pre (x) as defined below:
u =uk
=U(lk) Y= Yk = y(tA:)
x=
Xk+l
= ;~o X(t l+ 1 -E)
(13-10)
pre(x) = Xl =~X(tl -e)
f=! Figure 13-20 illustrates the relationships between the input ui, output Ykt and state variables between sampling points IA: in a sampled system model.
Xk
at and
Y
Yk-t
Yk U(t) Uk
X
x(t)
Xk
tk
tk+1
time
Figure 13·20. At a sample point tb the sampled value Ule of U(I) together with the value Xl of the discrete state variable x are used to compute the output value Yle and the next state value Xk+l. The discrete-time variable x is an approximation to the continuous-time variable x(t).
13.3.1.1 Simple Periodic Sampler The following model is a simple periodic sampler with a sampling period T that is constant and defined as a parameter that can be changed by the model user. As we remarked previously, this model has only one kind of event, the sampling event. We use the built-in function sample in the when-condition sample (0 , T) to periodically generate sampling events with a period time T. This is a simple model using the state space equations that were defined in the previous section.
model SimpleperiodicSampler parameter Real T=l "Sample period"; input Real u "Input used at sample events"i discrete output Real Yi "Output computed at sample events" protected discrete Real Xi II discrete state variable equation when sample(O,T) then x = f(pre(x),u) i II state update expression y = h(pre(x),u)i II output expression end when; end SimplePeriodicSampleri
Chapter 13 DiscreteEvent, Hybrid, and Concurrency Modeling 431 13.3.1.2 Base Class for Sampling Models
It is possible to formulate a base class for scalar sampling models using the previously presented statespace equations. The class BaseSampler below can, for example, be specialized to either a periodic sampler or an aperiodic sampler. partial class BaseSampler input Real u; discrete output Real y; Boolean doSample; replaceable function f Modelica.Math.atan2; II atan2 used as dummy replaceable function h Modelica.Math.atan2; II default function protected discrete Real X; equation when doSample then X = f{pre(x),u); II state update expression y = h(pre(x),u); /1 output expression end when; end BaseSampler;
Below the base model is extended to a periodic sampling model PeriodicSampler with a fixed period time T: model PeriodicSampler extend BaseSampler; parameter Real T=l "sample period"; equation doSample = sample (0, T); end PeriodicSampler;
13.3.1.3 Aperiodic Sampler
Besides the above periodic sampler, an aperiodic sampling model with a time-varying sample period can be obtained by specializing the base class. A variable nextSampling is used for the next sampling time, which is current time + periodTime when the current time has reached the previous value of nextSampl ing. In this example we increase the period time by the logarithm of the current time just to have a time-varying period time. model APeriodicSampler extend BaseSampler; discrete Real nextSampling(start=O); discrete Real periodTime\start=l) "time-varying sample period"; equation doSample = time>=pre(nextSampling); when doSample then nextSampling pre(nextSampling)+periodTimei periodTime = pre(periodTime) +log(pre(periodTime»); II example end when; end APeriodicSampler;
13.3.1.4 Discrete Scalar State Space Sampling Model
A discrete first-order scalar state space model with periodic sampling can be formulated as follows, essentially being a special case of the above BaseSampler model even though we do not extend that class in this particular case. model DiscreteScalarStateSpace parameter Real a, h, c, d; parameter Real T=l; input Real U;
432 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica discrete output Real Yi protected discrete Real Xi equation when sample(O,T) then x = a*pre(x) + b*Ui Y = c*pre(x) + d~Ui end when; end DiscreteScalarStateSpace;
Alternatively, the discrete scalar stale space model can be expressed by extending the BaseSampler model for periodic sampling and redeclaring the functions f and g as below. However, in this case the result is not shorter or more readable since the syntax for expressing the local functions f 1 and h1 is not very concise. On the other hand, if the functions f 1 and hl instead would be used in several places, the modeling style based on replaceable functions would be preferable. model DiscreteScalarStateSpace2 extend BaseSampler(redeclare function £=£1, redeclare function h=h1)i parameter Real a, b, c, d; parameter Real T=l "sample period"; function f1 input Real Xl; input Real x2; output Real yl; algorithm yl := a*xl + b*x2; end £1; function hI input Real xl; input Real x2; output Real yl; algorithm yl := c*xl + d*x2; end hi equation doSample = sample (0, T)i end DiscreteScalarStateSpace2;
13.3.1.5 Discrete Vector State Space Sampling Model
Usually state space models are expressed using the more general vector form, as in the DiscreteVectorStateSpace periodic sampling model below: model DiscreteVectorStateSpace parameter Integer n,m,Pi parameter Real A[n,n], B[n,m], C[p,n], D[p,m]i parameter Real T=li input Real u[m]; discrete output Real y[p] ; protected discrete Real x[n]; equation when sample(O,T) then x = A*pre(x) + B*u; y = C*pre(x) + D*u; end when; end DiscreteVectorStateSpacei
Chapter 13 Discrete Event, Hybrid, andConcurrency Modeling 433 13.3.1.6 Two-rate Sampling Model A rather general structure for many sampled systems is a common clock together with one or more subsystems that are synchronized by this common clock. The sample events are synchronized and the sampling frequencies are integer fractions of the common clock frequency (Figure 13-21). Sampled System
Figure 13-21. A sampled system consisting of a sampler and two subsystems, all synchronized by a common clock.
One of the simplest examples of this structure is a two-rate sampler with a fast sampling system coupled to a fast clock, and a slow sampling system with a sampling frequency that is an integer fraction of the frequency of the fast clock. At every 5th activation of the fastSample when-equation is the slowSample when-equation evaluated. For example, in the TwoRateSampler model below, the slow sampler is five times slower than the fast sampler, i.e., the slowSample when-equation is evaluated at every 5th activation of the fastSample when-equation. The two samplers are synchronized via equations involving the cyCounter variable. This is an example of the synchronization method described in Section 13.2.6.5. model TwoRateSampler discrete Real x,y; Boolean fastSample; Boolean slowSample; Integer cyCounter(start=O); II Cyclic count 0,1,2,3,4, 0,1,2,3,4, ... equation fastSample = sample(O,l); II Define the fast clock when fastSample then cyCounter if pre(cyCounter) < 5 then pre (cyCounter) +1 else 0; slowSample = pre(cyCounter) == 0; II Define the slow clock end when; equation when fastSample then II fast sampling x = sin(time); II end when; equation when slowSample then II slow sampling (S-times slower) y = log (time) ; II end when; end TwoRateSampler;
13.3.2 Finite State Automata Finite state automata is a simple and often-used formalism for modeling the behavior of certain discrete systems. Applications include digital circuits such as control units, neural networks, lexical analysis of text input to compilers, etc. A finite state automaton consists of the following components: •
A finite set of states, often denoted Q = {qt, qu ...}.
434 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica • •
•
A finite set or alphabet of values, corresponding to event types, denoting state transitions. An event is the arrival of a value e in this finite set. A next state function 6 mapping a state q and a transition value e to a set of states. A deterministic finite automaton maps to a set containing a single state, making the choice of the next state unambiguous. A set of initial states and a set of final states.
A pure finite state automaton has no notion of time. However, it is often used as a model component in a continuous-time dynamic system where time is relevant. In this case each state transition value corresponds to an event type. A specific event is the arrival of a certain value at some point in time. A finite state automaton can be viewed as a kind of control unit that always is in some state, denoted q, belonging to a finite set of states Q. It continuously receives values, denoted e, thereby switching to new states as specified by the next state functiond (q,e). The automaton moves from a state q to a state q', where q' E t5'(e,q). The automaton is deterministic provided that the following two conditions hold: • •
The next state function lJ ' (e, q) = {q/} , i.e., the target set contains only one state. There is only one initial state.
The arrival of values in the alphabet can be viewed as inputs, as outputs, as external control signals, or as internal events, depending on how the finite state automaton interacts with the rest of the system.
Events
-1
Recognizer
control
---,
Events
-1lnpUtlOUlput Process
Event Generator
"',
~
Accept event
~
Events
~
Events
I I
control
Figure 13-22. Three common uses of finite state automatons as model components. There are at least three common uses of finite state automatons as model components which are depicted in Figure 13-22: •
•
•
In the first configuration, the finite state automaton works as a recognizer for certain sequences of input events. A very common application is as a string acceptor in lexical analysis of text, typically in compiler frontends, Input events are the arrival of characters in an input stream. For example, in Figure 13-23 the arrival of the character values "." and U=" are accepted and recognized as the symbol "assignment operator," generating an output accept ": =" event. The automaton moves into a final state when a sequence of characters has am ved that is recognized as the string that should be accepted. The second configuration is that the finite state automaton works as a generator, i.e., it generates a sequence of output events. It is controlled by the environment, e.g. via input variables or input control events. This control influences the selection of events from the set of possible transitions, and the time when a transition should occur. In the third configuration, the finite state automaton works as an input/output process. Certain events are considered to be input events generated by the environment, some are output events, and some are internal events. The process can be controlled by the environment through external input variables or control events.
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 435 "."
Figure 13-23. A finite state automaton that recognizes the assignment operator ":=". The following is an example of a simple generator model that produces periodic sampling signals. The state transitions of the finite state automaton are hidden inside the implementation of the built-in function sample. model SampleSignalGenerator parameter Real startTime 0; parameter Real period = 1; output Boolean outSignal; equation outSignal = sample (startTime, period); end SampleSignalGenerator;
13.3.2.1 Simple Server One of the simplest possible examples of an input/output process modeled as a finite state automaton is the simple server whose state transition diagram is depicted in Figure 13-24. Start
Done
Figure 13-24. A finite state automaton model of a simple server system-an exampleof an input/output process with Start as input event and Done as output event.
The simple server finite automaton has two states, denoted Active and Passive, and a set of values {Start, Done} which is an alphabet of two symbols. The system becomes active and provides some service after receiving a Start event. After finishing the service item, the system emits a Done event and returns to the Passive state. This is described by the next-state mapping function: ~Passive, Start) =
=
Active, ~Active,Done) Passive.
13.3.2.2 Watchdog System A watchdog system is a slightly more elaborate example of an input/output process than the simple server. It has two basic states, Passive and Active, but can also enter a third state Alarmed when receiving a deadlineSignal event. When entering this third state the watchdog immediately emits an Ala:cm event. In general the function of a watchdog in its active state is to emit an alarm when a deadline is passed. Thus, the finite state automaton of the watchdog system in Figure 13-25 has a set of three states {Passive, Active, Alarmed} and a set of four values {Off, On, deadlineSignal, Alarm}, of which the arrival of any of the first three are input or control events, and emitting the last. value is an output event.
436 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
On
Figure 13-25. A finite state automaton of a watchdog system. The watchdog system shown in Figure 13-26 consists of the watchdog itself and three event generators, emitting On events, Off events, and deadlineSignal events.
WatchDogSystem Alarm!
Figure 13-26. A watchdog system. A Modelica model of the watchdog system follows below, consisting of the watchdog itself and the three event generators. The watchdog is formulated using an algorithm section since otherwise the multiple when-equations would cause multiple assignments to be reported for the variable watchdogActive. model WatchDogSystem EventGenerator turnOff(eventTime=O.25)i EventGenerator
turnOn(eventTime=l) i
EventGenerator deadlineEmitter(eventTime=1.5); WatchDog watchdog; equation connect {turnOn.dOutput, watchdog.dOn); connect (turnOff.dOutput, watchdog.dOff); connect (deadlineEmitter.dOutput, watchdog.dDeadline)i end WatchDogSystem; model WatchDog event Port dOn; eventPort dOff; eventPort dDeadline; eventPort dAlarm; Boolean watchdogActive(start=False); II Initially tur~ed off algorithm when change{dOn.signal)thenll Event watchdog on watchdogActive := true; end when; when change (dOff. signal) then II Event watchdog off watchdogActive .- false; dAlarm.signal := false; end when; when (change (dDeadline.signal) and watchdogActive) then II Event Alarm! dAlarm.signal .- true; end when; end WatchDog;
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 437
connector eventPort Boolean signal; end eventPort; model EventGenerator parameter Real eventTime=l; eventPort dOutput; equation
dOutput.signal = time>eventTime; end EventGenerator; We simulate the WatchDogSystem and plot the alarm signal in Figure 13-27, letting true be represented by 1 and false by 0 in the diagram. The watchdog receives an Off event at time = 0.25 and an On event 1.0, which causes it to be in the Act i ve state to emit an Alarm at time 1.5, when the at time deadlineEmi t ter component generates its "deadline reached" event.
=
=
simulate (WatchDogSystem, stopTime=4) plot (watchdog.dAlarm.signal)
2
3
4
5
time
Figure 13-27. Simulating the watchdog system which emits an alarm event at time
=1.5.
13.3.3 Cellular Automata A cellular automaton is a regular spatial array of cells which interact with one another, each of which can be in anyone of a finite number of states. Thus it is related to finite state automatons. The cells are arranged in a configuration, e.g. a one-dimensional line of cells, a 2-dimensional grid, or a 3-dimensional array. Other configurations are also possible, such as a honeycomb array of hexagonal cells. Each cell has a neighborhood which includes neighboring cells according to a well-defined pattern, which mayor may not include the cell itself. The following are examples of I-dimensional and 2-dimensional neighborhoods to the cell c marked by the letter n:
nnn nnn nen nen nenn n nnn nnn n
nen
The state of each cell in the array is updated according to a transition mapping which may depend on the state of the cell and its neighbours at the previous time step. Each cell in a cellular automaton could be considered to be a finite state machine which takes its neighbors' states as input and outputs its own state. To summarize, a finite state automaton is characterized by the following properties:
• •
State. Each cell is assigned one of a finite set of state values, e.g. integer values. Neighborhood, which is the set of cells interacting with the cell according to a well-defined pattern. The neighborhood of border cells in the array of cells mayor may not be determined according to
438 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica
•
"wraparound" semantics, e.g. top and bottom cells, and left and right cells respectively in a 2dimensional grid may be treated as "touching" each other. A transition mapping, usually expressed as transition rules and a transition function that take as input the present states, i.e., the present values, of all of the cells in a given cell's neighborhood and generate the next state, i.e., the next value, of the given cell. In some cases it is possible for different groups of cells in the automaton to have different transition rules and functions.
For example, regard a very simple cellular automaton consisting of a linear sequence of cells, with the neighborhood being the left and right cells, and wraparound semantics for defining the border cells. The transition function is simply the sum of the state values of the neighborhood cells, here the border cells and the cell itself. Step 1: Create the initial state:
00011000 Step 2: Compute the transition function, i.e., the sum, for each cell:
00122100 Step 3: Apply the following transition rules (0 ~ 1, 1 ~ 0, 2 ~ 1, 3 ~ 0 ):
11011011 13.3.3.1 The Game of Life An example of cellular automata in Modelica is a simple model representing Conway's game of life (Figure 13-50). Life is played on a grid of square cells where a cell can be alive or dead. In our example, we represent the grid of square cells as a matrix and a live cell is indicated by placing the value 1 on the corresponding element in the matrix. Obviously, each cell in the grid has a neighborhood consisting of the eight cells in every direction including the diagonals. We simulate the game of life over a limited time, on a grid of lOx 10 with the help of the following model: model GameOfLife
parameter Integer n=10; parameter Integer initialAlive[:,2]={{2,2},{2,1},{1,2},{3,3},{3,2}}i Integer lifeHistory[n,n] (start=zeros(n,n»i initial equation
lifeHistory = firstGeneration(pre(lifeHistory),initialAlive)i equation when sample(O.l,O.l) then
lifeHistory = nextGeneration(pre(lifeHistory»; end when; end GameOfLifei
We simulate for 1 second, using the Simulate [] command using the Mathematica frontend to MathModelica, and plot using the Mathematica function PlotGameOfLife, creating a new generation every 0.1th second as specified by the sampl e (0 . 1 , 0 . 1) expression in the above model. Simulate[GameOfLife,{t,O,l}];
PlotGameOfLife[lifeHistory]
PlotGameOfLife(table_] := For[z=O, zFalse,AspectRatio->Automatic] ; z=z+O.l]
•
1
•
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 439
••••••
--
•• ••• •
••
•
•
•• •• •••
.~
M
••
••
• •••
•• • •••
•
•
••
••
• •• • •••••
Figure 13-28. The first 8 generations from the simulation of the GameOfLife model.
The simulation starts with an initial generation represented by the initialAlive parameter which updates the lifeHistory variable in the initial equation section. This is done by calling the function f irstGeneration. function firstGeneration input Integer M(:,:]; input Integer 1[:,:]; output Integer G[size(M,l),size(M,l)] algorithm for i in l:size(I,l) loop G[I(i,l],I[i,2]] .- 1; end for; end firstGeneration;
.- M;
At each event, generated by the sample statement, the nextGeneration function is called, which applies the rules of the game to each cell of the grid. To apply one step of the rule we count the number of live neighbors for each cell. The value of the cell depends on the number of live neighbors according to the following rules: • • •
A dead cell with exactly three live neighbors becomes a live cell (birth). A live cell with two or three live neighbors stays alive (survival). In all other cases, a cell dies or remains dead (overcrowdingor loneliness).
The rules of the life game are illustrated by the nextGeneration function, which uses wraparound semantics (indices computed by the mod function) for determining neighborsof cells on the border: function nextGeneration input Integer M[:,:]; output Integer G[size(M,l) ,size(M,l)]; protected Integer borderSum,iW,iE,jN,jS; II West,East,North,South parameter Integer n=size(M,l)i algorithm for i in l:n loop for j in 1:n loop iW := mod(i-2+n,n)+I; iE := mod(i+n,n)+1; jS := mod(j-2+n,n)+I; jN := mod(j+n,n)+l; borderSum := M[iW,j] + M[iE,jl + M[iW,jS] + M[i,jS] M(iE,jS] + M[iW,jN] + M[i,jN] + M[iE,jN]; if borderSum==3 then G [i, j] : = 1; I I Alive elseif borderSum==2 then G[i,j] .- M[i,j]; II Unchanged else G [i , j ] end if;
. - 0;
II
Dead
+
440 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica end fori end for; end nextGeneration; The behavior of the GameOfLi f e model is dependent on the start configuration. Certain configurations, e.g. as in Figure 13-29, reach steady state already after a few generations. Other configurations never reach a steady state. GameOfLife2 = GameOfLife(initialAlive = {{l,l}, {2,2}, {3,3}, {4,4}, {s,s}, {6,6}, {7,7}, {a,a}, {9,9}, (ro.uo}. {l,10}, {2,9}, {3,B}, {4,7}, {S,6}, {6,S}, {7,4}, {B,3}, {9,2}, {10,1}}> ; Simulate [GameOfLife2, {t,O,l}]
..
•••• •••• • •••• •••• •••• • •••• •• •• •••• •• ••••••• •• ••• ••• ••• • •• • • •• •• ••• •• •• • •• • • ••• ••• • ••••• • •••• ••••
.... '
Figure 13-29. With another ini t ia lAl i ve start configuration the behavior of the GameOfLife model reaches steady state already at the third generation.
It is not necessary to employ user-written functions like nextGeneration as an aid to model the game of life in Modelica, as shown below by GameofLife3, which is equivalent to the previous GameOfLife model but is considerably shorter and uses only equations to model its behavior. The borderSum is computed by applying the sum reduction function with iterators over each neighborhood including its center element, which subsequently is subtracted. model GameOfLife3 "Game of Life model only based on equations" parameter Integer n=10; parameter Integer initialAlive[:,2]={{2,2},{2,l},{1,2},{3,3},{3,2}}; Integer lifeHistory[n,n] (start=zeros(n,n)); Integer M[n,n] ; Integer borderSum[n,nl ;//borderSum array because of single assigment initial equation for i in l:size(initialAlive,l) loop lifeHistory[initialAlive[i,l] ,initialAlive[i,2]] 1; end for; equation when sample(O.l,O.l) then M = pre(lifeHistorY)i for i in l:n loop for j in l:n loop borderSum[i,j] = -M[i,j] + II West/south, center, east/north sum(M[k,p] for k in {mod(i-2+n,n)+l, i, mod(i+n,n)+l}, p in (mod(j-2+n,n)+l, j, mod(j+n,n)+l}); lifeHistory[i,j] if borderSum[i,j]==3 then 1 II Alive else (if borderSum(i,j]==2 then M[i,j] II Unchanged else 0); II Dead end for; end for; end when; end GameOfLife3i
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 441
13.3.4 Models for Event-based Stochastic Processes If we generalize a finite state automaton by letting the time between two events be stochastic, and possibly also letting the choice of the next state be stochastic, we obtain a model for event-based stochastic processes. Such models have many applications, of which one are queuing systems. 13.3.4.1 Generalized Semi-Markov Processes Generalized semi-Markov processes is one model for stochastic processes often used for queuing systems in manufacturing industry, or for server models in general with stochastic customer arrival. Such processes are generalized in the following major ways compared to finite state automatons: • • •
The time between two events is stochastic. The choice of the next state might be stochastic. The set of states to choose from can be an infinite enumerable set instead of a finite set. y(t)
~--
10 ~
.. T,
I,
b
12
f.4
~.--.....
T2
T3
T4
.
time
Figure 13-30. An output variable generated by a generalized semi-Markov process.
We show an example of an output variable from a semi-Markov process in Figure 13-30. The level of the output variable y(t) changes in discrete steps between values in an enumerable set of discrete values. The changes occur at events at times t = to, ti, tz. etc. Both the output level and the time of the events may depend on random variables. The time intervals Ii = Ii - Ii-I between two successive events are stochastic variables with some random distribution. The choice of the output value may depend on stochastic variables. This is typical for a queuing system where customers arrive and leave at discrete points in time, increasing or decreasing state variables such as the number of customers in the system. We regard the output sequence of values Yn as being generated from some internal sequence Xn of state variable values together with random variables Rn: X n+1 = f(Rn+.,X n ) X o =fo(Ro )
Yn = h.(X n) Tn =h 2(X n)
(13-11)
13.3.4.2 Server with Queue As a simple example of discrete-time stochastic process simulation we can consider a simple server model with a queue. We first start by defining a model which generates customers at random points in time. The time delay until the next customer arrival is assumed to be a normally distributed stochastic variable T, here computed by calling the random number function normalvariate O), N.m/rad"; Flange_a flange_a "(left) driving flange - connector"; Flange_b flange_b "(right) driven flange - connector"; parameter Real phi_relO o "Angle when spring exerts no torque"; Real phi_reI "Relative rotation angle betw. flanges"; Real phi_deY "Angle deviation from zero-torque pas"; Real tau "Torque between flanges"; equation phi reI flange__b.phi - flange_a.phi; phi dev phi_reI - phi_relO; backward phi_reI < -b/2; II Backward angle gives torque tau b/2; II Forward angle gives torque tau>O slack not (backward or forward);11 Slack angle gives no torque tau = if forward then II Forward angle gives c*(phi_dev - b/2) 1/ positive driving torque else (if backward then 1/ Backward angle gives c*(phi_dev + b/2) II negative braking torque
466 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Flange_b flange_b "(right) driven flange - connector"; parameter Real phi_relO o "Angle when spring exerts no torque"; Real phi_reI "Relative rotation ~ngle betw. flanges"; Real phi_dev "Angle deviation from zero-torque pos"; tau Real "Torque between flanges"; equation phi_reI flange_b.phi - flange_a.phi; phi_deY phi_reI - phi_reIO; backward phi_reI < -b/2; II Backward angle gives torque tau b/2; II Forward angle gives torque tau>O slack not (backward or forward) ;11 Slack angle gives no torque tau = if forward then II Porward angle gives c*{phi_dev - b/2) II positive driving torque else (if backward then II Backward angle gives c*(phi dev + b/2) II negative braking torque else II Slack gives 0); II zero torque end SimpleElastoBacklash; We now employ the elastic transmission with backlash for the small application shown in Figure 13-61, where the DC motor circuit described in Section 5.6, page 162 and Section 15.1, page 524, is connected to a load denoted inertia2 via the elastoBacklash instance of the transmission. resistor
Motorside
inductor
\
\
inertia1 \ .
load side
/
!
I
,~~ ~.,
inertia2 .
Y.::._;c~WU~: elastoBacktash
step ground
Figure 13-61. A DCMotorCircuitBacklash model including a transmission with elastic backlash. The Modelica model corresponding to Figure 13-61 is as follows, using classes from the Modelica standard library:
model DCMotorCircuitBacklash import Modelica.Mechanics.Rotational: import Modelica.Electrical.Analog; import Modelica.Blocks: Rotational. Inertia inertial (J=l) ; Rotational.Inertia inertia2(J=6) i Rotational.ElastoBacklash elastoBacklash{b=3,c=lO,d=0.8) ; Analog.Basic.Inductor inductor; Analog.Basic.Resistor resistor; Analog.Basic.Ground ground; Analog.Basic.EMF emf; Analog.Sources.SignalVoltage signalVoltage; Blocks.Sources.Step step: equation connect {step.y, signalVoltage.v); connect (signalVoltage.n, resistor.p); connect (resistor.n, inductor.p) ; connect (signalVoltage.p, ground.p)i connect {ground.p, emf.n); connect {inductor.n, emf.p); connect {emf. flange b, inertial.flange a)i II rotFlange connect {inertial. flange_b, elastoBacklash.flange_a); II rotFlange
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 467 The ElastoBacklash model consists of a backlash element connected in series to a spring and damper element, which are connected in parallel (Figure 13-62). This is a slight extension compared to the previous SimpleElastoBacklash model since we have introduced a damping element with a damping constant d. The damping element contributesto the torque tau equation by the expression d*w_rel that is nonzero provided d is nonzero. The spring constant must be nonzero,otherwise the modelcannot be used. Another extension compared to the simple model is that a constant b_min for minimum backlash has been introduced.The backlash behavior of the model is available only if b/2 > b_min, since if b is too small or zero, numeric problems with too manygenerated state events will occur. The following ElastoBacklash model is from the Modelica standard library, but slightly reformatted to increase readability, leaving out some attributes like unit and min. The Boolean variables forward and backward that we introduced in the SimpleElastoBacklash model for readability reasons are not present, only the corresponding Boolean expressions. model ElastoBacklash "Backlash connected in series to linear spring and damper (backlash is modeled with elasticity)" extends Modelica.Mechanics.Rotational.lnterfaces.Compliant; parameter SIunits.Angle b = 0 "Backlash size parameter"; parameter Real c = l.eS "Spring constant (c>O), N.m/rad"; parameter SIunits.Angle phi_relO 0 "Angle with zero spring torque"; parameter Real d = 0 "Damping constant, N.m.s/rad"; SIunits.Angle phi_dev "Angle deviation from zero posIt; SIunits.AnguiarVeiocity w_rel "Relative rotation speed between flange_b and flange_a"; protected SIunits.Angle b2 = b/2 "Half backlash"; constant SIunits.Angle b min = l.e-10 "minimum backlash"; equation w_rel = der(phi_rel); phi_dev = phi_reI - phi_reID; tau = if b2 > b min then II Slack behavior enabled (if phi_deY > b2 then II Forward angle gives c*(phi_dev - b2) + d*w_rel II positive torque else (if phi_deY < -b2 then II Backward angle gives c*(phi_dev + b2)+ d*w_rel II negative torque else 0) II Slack gives zero torque )
else c*phi_dev + d*w_rel; end ElastoBacklash;
IISlack
behavior disabled if b/2{False,False},Epilog->expl} FatinJ 'Ihi.nki.tg ...'0' ...
(1.1··.. · j"lJ" 1....r..}... L...;,,!0L.,j r'" 1...1..... tool .1'"
r-l
r-j [-1 r--l r: LJ LJ ..... ....J L..
...1
nl.r- LJn r-----__ n [1
l....
L.
FatinJ 'Ihi.nki.tg Fatin3 'Ihi.nki.tg FatiIg 'Ihi.nki.tg Fatirg 'Ihi.nki.tg
Figure 13-70. Activity diagrams of the five dining philosophers-eating or thinking, and hungry in between.
No deadlock occurs--this cannot happen since we use the mutex for resource access. In this case, with normally distributed thinking times, each philosopher gets a chance to eat. However, if the thinking times are constant, starvation can easily occur. For example, one of the philosophers will never get any food since a pattern arises where two pairs of philosophers alternate between thinking and eating. By setting the sigma parameter to zero all thinking and eating times become constant and starvation occurs (Figure 13-71). Here we use the Mathematica command interface to MathModelica, that provides advanced scripting functionality in terms of the whole Mathematica language. Simulate [DiningTable, {t, 0, SOO} , ParameterValues -> {sigma == O}]; expl = Apply [Join, {Map[Function[i, Text ["Thinking", {550, 4*i}, {-I, O}]],Range[n[O]]], Map[~unction[i, Text ["Eating", {SSO, 2+4*i}, {-I, o}]] ,Range [n[O]]] }] ; Map{Function{i, phil[[i]] .state(tl + 4*i ] , Range[n[O]]]; p!otSimulation[%,{t,O,SOO}, Legend->False, Axes->{False,False},Epilog->expl]
Chapter 13 Discrete Event, Hybrid, and Concurrency Modeling 475
FatinJ 'Ih:inkirg 1
t
I ! l....J
t._fL..! -
_.J--l_r-tJ-1J--Lr-U·-lJ-··-Lr-LJ1J--1J···LJ1_ _ _rJ-1J··t_fl.. rl.J--tJ--L_Tl_J···1_.r··Lfl.J··1..r'-·
FatinJ 'Ih:inkirg FatinJ 'Ihi.nkirg FatinJ 'Ihi.nkirg EatinJ 'Ihi.nkirg
FigUre13-71.Activity diagrams of the five dining philosophers where one is starving.
13.6 Summary This chapter presented the important concepts of discrete events, hybrid continuous-discrete modeling, and modeling of concurrent systems. We started by discussing real-time systems and defining the notion of event based on conditional equation semantics. Then we again described the difference between discretetime and continuous-time variables, and made an in-depth presentation of the synchronous data flow principle for Modelica. We showed how events are created internally or externally to Modelica followed by presentations of a number of event-related built-in functions and operators. We explained how to handle events, e.g. using ifequations or when-equations, and described when to use event priority, event synchronization and propagation, and how to handle multiple events at the same point in time. A number of formalisms and model examples for discrete systems were presented, together with their Modelica representations These included sampled systems-both periodic and aperiodic, finite state automata, cellular automata modeling the game of life, models for stochastic processes applied to a server with a queue, the discrete event systems specification formalism (DEVS) expressed in Modelica and applied to a job shop model, as well as Petri nets expressed in Modelica and modeling a job shop system. We described hybrid system modeling and simulation together with two examples: a hybrid tank model with a discrete controller and a mode switching model comprising a DC motor transmission with elastic backlash. Finally we presented concurrent access to shared resources as exemplified by the dining philosophers problem.
13.7 Literature Synchronous data flow languages and the corresponding synchronous data flow principle is described in (Halbwachs 1993). A short overview of a number of discrete and hybrid formalisms and their relation to the object-oriented modeling language Omola can be found in (Andersson 1994). Petri nets are described in (peterson 1981), and the first Modelica library representing Petri Nets is presentented in (Mosterman, Otter, and Elmqvist 1998). The first DEVS representation in Modelica is presented briefly in (Bunus and Fritzson 2(00), traditional DEVS in (Zeigler 1984; Zeigler 1990), whereas hybrid Modeling in Modelica based on the synchronous data flow principle is described in (Otter, Elmqvist, and Mattsson, 1999). Stephen Wolfram presents cellular automata and their use as a general representation (Wolfram 2002). Synchronous state charts can be translated to equation-based Modelica (Ferreira and de Oliveira 1999), and asynchronous state charts to algorithmic Modelica (Pereira-Remelhe 2(02).
477
Chapter 14 Basic Laws of Nature
When modeling a system it is essential to use the appropriate laws of nature that govern the behavior of the different parts of the system. These laws are often expressed as equations that can be stated in Modelica classes. However, even if application models usually are built by combining model components from libraries of predefined classes and functions, it can be useful to expose the basic equations of each application domain to gain an increased understanding of the basic mechanisms behind the behavior. This is the purpose of this chapter.
14.1 Energy Conservation The principle of conservation of energy is one of the most fundamental laws of nature. It can be formulated as follows: •
The amount of energy in a closed system can neither be created nor destroyed.
Here we talk about energy in the general sense, since matter is equivalent to energy according to Einstein's famous law: (14-1)
where E is the energy, m is the mass and c is the speed of light. A consequence of the principle of conservation ofenergy (or similarly for charge, mass, etc.) for a closed system is the following: •
When energy (or charge, mass, etc.) flows together at a certain point, without storage at that point, the sum of all flows into that point is zero.
This is the background for the Modelica sum-to-zero rule for flow variables at connection points. In the electrical domain this corresponds to Kirchhoff's current law, and in the mechanical domain Newton's second law that the sum of all forces acting at a specific point is zero if there is no acceleration. Energy is always transported using some carrier, which in the case of electrical current is charged particles, and in the case of translational or rotational mechanical systems is linear or angular momentum respectively. Different domains will usually have different flow quantities, since they normally use different carriers. The concept of potential is a measure of the level of energy. The choice of a potential quantity for a particular domain must always be such that at connection points all potential variables of connected components are equal. This is essential for the equality rule regarding potential (nonflow) variables in Modelica, that the variable values are equal at a connection.
478 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Table 14-1 summarizes possible choices of energy carrier together with associated potential and flow quantities for a few common physical domains, as well as a selection of corresponding Modelica libraries. Table 14-1. Energy carriers with associated potential and flow quantities for a set of common physical domains.
Domain Type
Potential
Flow
Carrier
Modelica Library
Electrical Translational 1D
Voltage Position
Electric current Force
Electrical Mechanical.Translational
Rotational 1D
Angle
Torque
Mechanical 3D
Position (3D) and Rotation angle (3D) Magnetic potential Pressure Temperature Chemical potential
Force (3D) and Torque (3D)
Charge Linear momentum Angular momentum Linear and angular momentum Magnetic flux
Magnetic Flow, Hydraulic Heat Chemical
Magnetic flux rate Volume flow rate Heat flow rate Particle flow rate
Volume Heat Particles
Mechanical.Rotational MechanicaI.MultiBody
HyLib, Pneul.ib, etc. Thermal, etc. (ThermoFluid)
In the rest of this chapter we will present a selection of the basic laws of nature for the above-mentioned physical domains as well as for some additional domains.
14.2 Analog Electrical Circuits Analog electrical circuits consist of passive components such as resistors, capacitors, inductors, transformers, etc., as well as active components like transistors and amplifiers. Here we give the basic equations governing some of the simpler components in electrical circuits. Several of these components were introduced already in Section 2.11, page 41. The corresponding Modelica library called Modelica. Electrical.Analog is presented in Section 16.5.1, page 620. The basic analog electrical quantities are the voltage quantity v(t) (V-Volt) for potential and the flow rate quantity current i(t) (A-Ampere). These are used in the basic equations of analog electrical systems as well as in interfaces in the form of connector classes. An ideal linear resistor is described by Ohm's law, where the constant R is the resistance (ohm) of the component: v(t)
=R· i(t)
(14-2)
An ideal capacitor is defined by the equation below, where the voltage change is proportional to the current through the capacitor, and the constant C (F-Farad) is its capacitance: i(t) = C· !!...v(t)
(14-3)
dt
or using the shorter notation i(t) = Cv(t)
«o for time derivative: (14-4)
The voltage over an ideal inductor is proportional to the change in current i(t), with the constant L (henry): v(t)
= L· !!...i(t) dt
(14-5)
Chapter 14 Basic Laws of Nature 479 A nonlinear resistor can be described as follows:
v(t) = hI (i(t»
(14-6)
or i(t)
=h2 (v(t))
(14-7)
The power dissipation (in some cases also including conversion to electromagnetic field energy) of an electrical component is defined by the product of the voltage drop over the component and the current through the component:
P(t) = v(t)· i(t)
(14-8)
Kirchhoff s laws describe connected components in electrical circuits. The sum of the voltages (both positive and negative) around a loop is zero: (14-9) Kirchhoff s current law states that the sum of all currents (with sign) into a node is zero:
(14-10) Both relationships are illustrated in Figure 14-1.
is
Figure 14-1. Illustration of Kirchoff's laws. The sum of the voltages (with sign) around a loop is zero, e.g. as for Vh V2, V2, V4 in the circuit to the left. The sum of the currents (with sign) into a node in a circuit is zero, as illustrated by the currents if, i2 , ts. i4 , is in the circuit to the right.
An ideal transformer is a component that transforms voltage and current in such a way that their product is constant, disregarding the fact that the products have opposite signs because we have defined the current always to be into the positive pin of each side, for the usual reasons of connectivity and consistency. If we instead would define the direction of the current i 2 to be out of the transformer, both products would have the same sign. (14-11)
480 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
~ 01 Figure 14-2. An ideal transformer. The transformer is ideal since we assume that properties such as resistance, stray inductance, etc. are negligible, which is often the case for many practical purposes. The relationships between the voltages and the currents are given by the two equations below. The voltage V2 is decreased by a factor n, whereas the current i2 is increased a factor of n compared to VI and i1 respectively. The factor n is a real number (really a rational number) called the turns ratio, being the relation between the number of turns in the two coils of the transformer.
1
v 2 =-,v1 n
(14-12)
i2 = n- i 1 The current directions shown in Figure 14-2 make a positive current it cause a positive current i2, which is common in most textbook presentations of transformers. However, the corresponding Modelica library component IdealTransformer shown in Section 16.5.1.3, page 621, has the opposite direction of the current i2 since we have defined the current to be always into the positive pin of each side, for the usual reasons of connectivity and consistency. This causes a minus sign to appear in the equations involving ;2 in the Modelica class. A transformer with finite inductance is a more realistic model since the coils in a transformer typically behave as inductors:
(14-13)
Here L I , L2 , and M are the primary, secondary, and coupling inductances respectively. The corresponding Modelica model appears below:
model Transformer "Transformer with inductance" extends Modelica.Electrical.Analog.lnterfaces.TwoPorti paramete'r SIunits. Inductance Ll=l "Primary inductance"; parameter SIunits.lnductance L2=1 "Secondary inductance"; parameter SIunits.lnductance M=l "Coupling inductance"; equation vl = Ll*der(il) + M*der(i2); v2 = M*der(il) + L2*der(i2)i end Transformer; II from Modelica.Electrical.Analog.Basic.Transformer The EMF (Electro Motoric Force) converter is one of the more interesting components in the electrical library since it is a transducer that converts electrical energy to mechanical rotational energy (Figure 14-3). This class is an idealized model of the most important properties of a voltage-to-rotation converter excluding resistance, inductance, and inertia. It is both electrical and mechanical, but is placed in the Electrical.Analog .Basic library.
Chapter 14 Basic Laws of Nature 481
rotation axis
--_._ ... _.._._. __..
~
_ _ _w - - 1
flange_b.tau r,,(t)
Figure 14-3. EMF--Electro Motoric Force converter.
The three most important equations of the EMF class are given below. The rotational speed cu(t) is of course equal to the derivative of the rotation angle flJb(t). The voltage v(t) is proportional to the rotational speed (O(t). The torque rb(t) is proportional to the current ;(t) through the coil. The EMF class has two Pin type connectors that transmit voltage v(t) and current ;(t), and a rotFlange_b connector that transmits absolute angle 'Pb(t) and torque t"b(t). m(t) =
tPb (t)
v(t)
=k . m(t)
t b (t)
= -k . i(t)
(14-14).
The Modelica EMF class from the Electrical.Analog .Basic library is shown below. It is used e.g. in the DC Motor application described in Section 15.1, page 524. model EMF "Electromotoric force (electric/mechanic transformer)" import Modelica.Electrical.Analog.lnterfaces; import Modelica.Mechanics.Rotational.lnterfaces.Flange_b; parameter Real k(final unit="N.m/A")=l "Transformation coefficient"; SIunits.Voltage v "Voltage drop between the two pins"; SIunits.Current i "Current flowing from positive to negative pin"; SIunits.AngularVelocity w "Angular velocity of flange_btl; Interfaces.PositivePin p; Interfaces.NegativePin n; Flange_b flange_hi equation v p.v-n.v;
o
p.i+n.i; i p.i; w der(flange_b.phi) ; k*w = Vi flange_b. tau = -k*i; end EMF i / / from Modelica .,Electrical.Analog .Basic. EMF
14.3 Mechanical Translational 1D The dynamics of mechanical translational systems in one dimension are described by the equations covering this application domain. These equations are Newton's laws together with a few additional laws for specific translational components like springs, dampers, etc. The corresponding library is Modelica. Mechanical. Translational, described in Section 16.7.2, page 630. The basic concepts for this library together with a few important classes are presented in detail in Chapter 5, page 153. Note that the generalization to three dimensions, i.e., the dynamics of mechanical systems consisting of multiple bodies moving in three dimensions, is discussed in Section 14.8, page 502.
482 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica This domain uses the following basic quantities: force fit) (N-Newton) as the flow rate quantity and position s(t) (m-meter) as the potential (nonflow) quantity. These two quantities are used both in a number of equations, as well as in interfaces defined by connector classes. The common quantities velocity v(t) (mis-meter/second) and acceleration a(t) (m2/s-meter2/ second,) are defined as follows: v(t) = s(t) (14-15) a(t) = v(t) Newton's second law applies, i.e., the sum of all forces on a rigid body is equal to the constant mass of the body multiplied with its acceleration: m- a(t)
=II; (t)
(14-16)
;
This law is used, e.g. by the SlidingMass class in the Mechanics. Translational library, and can be reformulated as follows:
!!.-(m. v(t» = Ifi(t) dt ;
(14-17)
The term m- v(t) is often called the momentum or impulse of the rigid body. In an equilibrium situation when the body is at rest there is no acceleration, making it possible to simplify Newton's second law so that the sum of the forces is zero: (14-18)
The force f(t) exerted by an ideal elastic spring is defined by the following equation:
f(t)
= c- (s(t) -
(14-19)
so)
where c is the spring constant, s(t) is the spring length, usually expressed as the position of one of the spring flanges, and So is the length of the spring at rest when it exerts no force. This equation occurs in the Spring class described in Chapter 5, page 154, and belongs to the Mechanics. Translational library presented in Section 16.7.2, page 630. The friction force between a body and a surface on which the body is sliding in the general case can be expressed as a function h of the velocity:
I(t) = h(v(t»· IN
(14-20)
where v(t) is the relative velocity between the surfaces sliding against each other, and. IN is the normal force to these surfaces. In machines the normal force is often constant and therefore known, e.g. due to pre-tension of bearings or because the normal force I N is the controlled pressure force of a clutch or brake. The simple case of dry friction force between a body and a surface is described by the following version of the function h:
+ ,u(1 vI) if v(t) > 0 h(v(t» = lo(t)
{
ifv(t) = 0
(14-21)
-,u(lvl) ifv(t)(t) =
I'l"; (t)
(14-27)
i
This law is used, e.g. in the Inertia class in the Rotational library and is depicted in Figure 14-4. It can be reformulated as follows, where the term J. aJ(t) is often called the angular momentum of the body:
!!....(J .co(t)) = Lt"j(t) dt
(14-28)
;
In an equilibrium situation when the rotational mechanical system is at rest, i.e., nonrotating, the sum of the torques is zero: (14-29) - - - . w =der(phi)
flange_b.tau flange_a.phi
f1ange-aT
T'
._ ..__ ...-_..__.._. __ .~ rotation axis
flange_b.phi
g a n e- b
484 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica Figure 14-4. A rotating mechanical body with inertia.
The equation for an elastic torsion spring is the rotational counterpart of the previously presented translational spring: (14-30) where c is the torsion spring constant.The applied torque~ (t) is proportional to the difference between the current angle ({J(t) and the equilibrium angle ({Jo when no torque is applied.
Figure 14-5 A mechanical gear, with gear ratio = r2lrl.
An ideal mechanical gear transforms torque and rotational movement. The approximation that the gear is ideal means that the wheels have no inertia and that no elasticity, friction, damping, or backlash has been taken into account. See the IdealGear class in the Mechanics. Rotational library, in which the direction of the torque flow quantity t2 is opposite to what is shown in Figure 14-4 due to flow direction into the flange.The following equationsapply:
fIJ. = ratio ° flJ2 1 TI =--. T2 ratio
(14-31)
Here the gear ratio = r'llr. according to Figure 14-5 is the same as the relation between the circumferences of the gear wheels. By differentiating the first equation and multiplying with the second equation, we obtain: WI
= ratio- aJ 2
(14-32)
T] oWl =T2 °OJ2
14.5 Flow Systems and Hydraulics Flow systems consist of components containing a flowing substance such as fluid or gas, with typical applications in hydraulics and process industry. In this section we are treating only incompressible fluids for which the volume is not affected by the pressure. Gases are excluded since they are compressible, as well as compressiblefluids which are morecomplicated to model mathematically. In the followingwe will discuss volume flows. For incompressible fluids, mass flows can be obtained from volume flows by multiplying with the density p. The basic quantities are the pressure p(t) (N/m 2 ) potential quantity and the volume flow rate quantity q(t) (m 3/s). These are used in flow equations as well as in interfaces in the form of connector classes. Usually the pressure difference between ports of a component is used rather than the absolute pressure. The pressure difference p(t): p(t)
= PI (t) -
P2(t)
(14-33)
Chapter 14 Basic Laws of Nature 485
between the two ports of a flow component such as a flow resistance, where PI and P2 are the input and output pressures respectively. A flow resistance component with laminar (not turbulent) fluid flow of incompressible fluid through a thin tube with friction against the walls is depicted in Figure 14-6. Such a component is, for example, modeled by the class LamResNoStates in the HyLibLight. Components. Basic library, Section 16.9, page 641.
PI
P = Pt- P2
P2
Figure 14-6. Linear flow resistancecomponentwith laminarflow. The flow rate is denoted by q, the pressuredifference by p, the input and output pressures by PI and P2 respectively. The relation between pressure and flow rate for a flow resistance with laminar flow is approximately given by d' Arcy's law: p(t) = RI ·q(t)
(14-34)
Here Rf (s.Pa/m'-second'Pascal/meter3) is called the flow resistance. In case of steady laminar flow, Hagen-Poiseuille's relation is valid for cylindrical pipes, for which Rican be obtained as follows:
R f
= 12811L
(14-35)
1tD4
Here D is the diameter, L is the length of the pipe, whereas " is the dynamic viscosity of the fluid. The laminar flow resistor equation is often formulated using flow conductance Qf =1/RI (m3/(s·Pa) as in the class LamResNoStates: q(t) = Q!. p(t)
(14-36)
For a tube that contains a sudden change in area, e.g. an orifice as in Figure 14-7, the flow becomes turbulent, which happens when Reynolds number Re is greater than Recrit::: 2300. For turbulent flow, the pressure difference is approximated by: p(t) = H . q(t)2 sgn(q(t))
(14-37)
where H is a constant.
Pl~
P2
Figure 14-7. Nonlinearflow resistancefrom turbulentflow caused by a suddenchangeof the area of the tube, e.g, an orifice, a bend, or a valve. Consider flow through a tube of length 1 with a rather wide cross-section area A, as depicted in Figure 14-8. In this case we make the approximation of no flow resistance against the walls of the tube. The pressure difference p(t) between the ends of the tube will create a force p(t)·A that accelerates the liquid, which has a mass p' I-A, where p is the density. Newton's second law gives:
d p(t)· A = P .t . A ·-v(t)
(14-38)
dt
where v(t) is the velocity of the liquid, which corresponds to a fluid flow rate q(t) obtain:
=v(t)·A
(m 3/s). Thus we
486 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica d p(t) =Lf . -q(t) dt
(14-39)
where L f = p·11A. This relation is the flow counterpart of the electrical inductor equation. The constant L r is called the inertance of the tube, with units (kg/m4). length I
.s.; PI
larea A ':.4
P =Pv: P2
P2
Figure 14-8. Frictionless flow rate q(t) through a tube of length I and cross-section area A, with pressure difference p(t).
A tank is a component which is a storage place for fluid, being the flow domain counterpart of an electrical capacitor that is a storage place for charge. The volume of the liquid in the tank depicted in Figure 14-9 is h-A, with a gravity force p·h·A·g acting on the mass of the fluid, giving a pressure p(tJ= p·h·g at the bottom of the tank. Differentiating this equation, and using q(t) = h(t)· A, we obtain: q( t) =
d
(14-40)
Cf . dt P(t)
where Cf = A/p·g (m
4s 2
/kg) is the fluid capacitance of the tube.
areaA"" level h
1'--t_an_k
4
q
Figure 14-9. A tank works as a fluid store, here with capacity h·A, analogous to an electrical capacitor which behaves as a charge store.
There are laws analogous to Kirchhoff's laws in the electrical domain that describe the connection of flow components. The sum of the pressure changes (positive and negative) around a flow system loop is zero: (14-41) This is illustrated by the flow system example shown in Figure 14-10.
- - -...
~-----
P7
Figure 14-10. Pressurechanges PI to P7 over a series of connectedflow subsystems. The sum of all pressure changes (with sign) around a completeloop is zero. Likewise, the sum of all flows (with signs) into a node is zero since matter is neither created nor destroyed: (14-42)
Chapter 14 Basic Laws of Nature 487
Figure 14-11 shows five flows into the same junction.
Figure 14-11. Fluid flows q. to q5 at the junction of several pipes. The sum of all flows (with sign) into one junction is zero. Analogous to the well-known electrical transformer, there are flow transformers that can transform a pair of pressure and flow rate quantities into another pair of pressure and flow rate quantities. An ideal flow transformer, e.g. as depicted in Figure 14-12 makes this transformation without loss of energy. PI
ql--+ area A, Figure 14-12. A flow transformer. An ideal flow transformer preserves the product of pressure and flow rate, and is described by the following equations: PI (t)· qi (t) = P2 (t)· q2(t)
PI (I)
=0 . P2 (I)
I qi (I) = - ' q2(I) a
(14-43)
where the quotient a defined below determines the relation between the pressures and flows before and after the transformer. (14-44) Transducers translate between pairs of quantities from different domains. A flow transducer such as a hydraulic pump depicted in Figure 14-13 translates between the mechanical quantities force and velocity to pressure and flow quantities, or vice versa:
fl(t)=A'P2(t) v1(t ) = A ' Q2(t ) where A is the area of the piston.
(14-45)
488 Peter Fritzson Principlesof Object-OrientedModeling and Simulation with Modelica
Area A Figure 14-13. A hydraulic pump, a transducerbetween mechanical quantities and flow quantities.
14.6 Thermal Systems Thermal systems involve the storage and transport of thermal energy, which is internal kinetic energy in the form of microscopic movements and oscillations of particles such as atoms and molecules in a material. For example, the heating or cooling of a house involves transport of thermal energy and are influenced by the conduction of heat through the walls, radiation from the radiators, and convection of air in the rooms of the house. The laws describing these phenomena usually involve the temperature quantity T(t) (K-Kelvin) and the heat flow rate quantity q(t) (W-watt, or J/s-Joule/second). Modelica libraries for thermal system components are mentioned in Chapter 16, page 615. The temperature T(t) of an object influences the amount of thermal energy Ertt) stored in the object. The following equation describes the heat flow rate into or out of an object: q(t)
d =C ·-T(t)
(14-46)
dt
where C =m-e is the heat capacity of the object, c is the specific heat capacity of the material, and m is the mass of the object. Normally c is temperature dependent, but can be regarded as constant over limited temperature ranges for most materials. Equation (14-47) describes a heat capacitance and is the thermal counterpart of the equation that describes electric charge flow rate (current) into an electric capacitor. By integrating this equation we obtain an equation for the thermal energy Ertt) in the object
e; (t) = J(C.!!... T(t»dt
(14-47)
dt
For the cases where C is approximately constant we obtain:
s, (t) = C· T(t)
(14-48)
There are basically three ways of transporting thermal energy or heat: conduction, convection, and radiation. The mechanism behind heat conduction is diffusion, i.e., heat transfer that is caused by the microscopic motion of individual particles such as molecules or atoms. Heat conduction does not imply macroscopic motion of the particles themselves-rather the propagation of local motion (vibration) between microscopic particles which on the average (in solids) remain at the same place. Heat transfer can also take place on a macroscopic scale, by moving heated matter. This process is called convection. The third way of transporting heat is through thermal radiation, i.e., the emission and absorption of light.
14.6.1 Conduction Within solid matter heat is transported by conduction, which is based on the microscopic process of diffusion. In the case of one-dimensional heat flow this process is described by the heat equation, which is a well-known partial differential equation giving the temperature T(x,t):
Chapter 14 Basic Laws of Nature 489
(14-49) where A. is the heat conductivityof the material, c is the specific heat capacity, and p is the density. For a homogeneous block of solid material such as a rod, e.g. as depicted in Figure 14-14 the solution to this equation can be used to obtain the stationary heat flow rate through the object, given a temperature difference T caused by the temperatures T. and T2 at each end of the object: q(t)
=-A·A ( Tt (r) - T2 (t» =W .T(t)
(14-50)
d
where W = A.·A/d is the heat transfer coefficient (J/(K·s»), A is the cross-section area, and d the distance between the ends of the rod.
Figure 14-14. Component with heatresistance/conduction, with temperature difference Tand heat flow rate q. Analogous to Kirchhoff's voltage law for electrical systems, the sum of all temperature differences (both positive and negative)around a complete path within a system is zero: (14-51)
Since energy cannot be destroyed, the sum of all heat flows (with sign) into a node without energy storage is zero: (14-52) Both relationships are illustrated in Figure 14-15.
(b)
Figure 14-15. The sumof the temperature differences (with sign)along a patharound a system is zero, e.g, as for Tt,T2,T3, and T4 on the left.The sumof theheat flows (withsign)into the samenodeis zero, as illustrated by ql, q2, q3, q4, qs on the right.
490 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
14.6.2 Convection Thermal convection is heat flow on the macroscopic scale based on the fact that heat stored in any moving piece of matter moves together with that object. This process describes transfer of heat as a result of macroscopic movements rather than microscopic movements, which was the case for thermal conduction. For example, consider a room in a house. If we heat the floor of the room, the air close to the floor will be heated up through conduction. Its density will be reduced because it is warmer; therefore it will rise to the ceiling and transfer part of its heat to the ceiling. Colder air will move down to the floor to replace the air that moved up. This is a typical convection phenomenon. For buildings in general, convection takes place between the air and the walls, floors and ceilings inside buildings as well as outside. Convection is described by the following equation: q(t) = a . A· T(t)
(14-53)
where T(t) = T t(t)-T2(t), i.e., the temperature difference between the two objects or surfaces, a is the convective heat transfer coefficient, and A is the area perpendicular to the heat flow where the heat flow takes place.
14.6.3 Radiation The third way of transporting thermal energy is through radiation. The atoms and molecules of a material in solid, fluid, or gas form continuously. emit and absorb radiation. For example, the walls of a house absorb some solar radiation, become heated up, and emit radiation. There is emission from radiators and continuous heat exchange between walls. The Stephan-Boltzmann Law governs the radiation, i.e., energy flow, emitted from a surface with the temperature T(t): (14-54) where (J is the Stephan-Boltzmann constant, 8 is the emission coefficient of the surface, and A is the surface area. A dark surface has higher emission coefficient than a white one. The radiation exchange between a surface (1) of area A and a fictitious ideal black body (2) with the same surface becomes: (14-55) For an ideal black body the emission coefficient 62 = 1. A fictitious black body is useful, e.g. when modeling a room using the so-called two-star approximation: instead of explicitly modeling all combinations of radiation interactions between a number of objects, e.g. all walls and other objects in a room, all radiating surfaces are connected to and interact with a fictitious massless black body.
14.7 Thermodynamics Thermodynamics is a part of natural science in which the storage of energy, the transformation of energy between different forms, and the transfer of energy (and mass) between subsystems is studied. One of the primary energy forms dealt with in thermodynamics is thermal energy, also mentioned in the preceeding Section 14.6, page 488, about thermal systems. Mass flows are often part of thermodynamic models, involving model components such as those described in Section 14.5, page 484, regarding flow systems. The transformation and transfer of the following four main forms of energy is typically studied in thermodynamics: •
Internal thermal energy, associated with temperature and due to microscopic random motion of constituent particles such as atoms and molecules.
Chapter 14 Basic Laws of Nature 491
•
•
Macroscopic kinetic energy, due to macroscopic motionof chunks of material. Potential energy, e.g. due to the positionof a subsystem in a gravitational or electromagnetic field,
•
or due to internal pressurein a subsystem, etc. Chemical energy, due to internal molecular and atomicbonds in the material.
In thermodynamics we formulate equations that relate transformations and transfers of energy to certain material properties. These properties include temperature, pressure, or enthalpy which isa property specifying a combination of thermal energy and pressure-related potential energy of the material. The engineer's goal when studying thermodynamics is usually to design some large-scale system, anything from a refrigerator to a power plant. The materials in such large systems can be regarded as continuums where the individual motion of molecules and atoms is averaged into quantities such as temperature, pressure, etc. The continuum approximation used here is made in macroscopic thermodynamics, in contrast to statisticalthermodynamics wherethe individual motion of molecules is important.
14.7.1 Thermodynamic Systems and Control Volumes In thermodynamics we speak about thermodynamic systems, their surroundings, and control volumes embeddedin systems, as depictedin an abstract way in Figure 14-16below.
energy
energy
Surroundings Figure 14-16. A control volume allows transfer of energy and mass across its boundaries, whereas a closed
system contains a definite quantity of matter andonlyallows energy transfer to andfrom its surroundings. We have the following definitions: • • • • • •
A thermodynamic system is a definite quantity of matter, usually contained within some closed boundary. An example is a cylinder containing a gas or fluid. A system can usually exchange energy and matter with its surroundings, and can be either open or closed. An open system can exchangeboth energy and matter with its surroundings. A closed system can only exchangeenergy with its surroundings. An isolated system does not exchange energyor matter with its surroundings. A system may contain subsystems. The surroundings of a system is all matter(and radiation) externalto the system.
A control volumeis a simpleopen systemdefined as follows: • •
A control volume is a volume in space consisting of a single phase or pseudo-phase (see below). The boundary can be physical or imaginary. A control surface is the boundary surfacethat completely surrounds the control volume.
Note that a system can contain several control volumes. When modeling a particular problem we must decide whethera control volume or an open/closed system is appropriate. If there is a mass flow across the boundary of a regionconsistingof a single phase,a control volumeshould be used, otherwisea system.
492 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica 14.7.1.1 Continuum Postulate and System Properties
As mentioned briefly above, in engineering thermodynamics, also called macroscopic thermodynamics, we use the continuum postulate that the material is continuously distributed throughout the region, and as a consequence has uniform properties in this region. This allows us to characterize the material in a system or control volume by only a few measurable quantities such as temperature, pressure, volume, average position, velocity,etc. The matter in a system or control volume can exist in severalphases: solid, liquid, or gas. A phase is a quantity of matter that has the same homogenous chemical composition throughout the region in question, i.e., with spatially uniform intensive properties (see below).
•
Sometimes we generalize phase to pseudo phase where properties are not completely uniform but are represented by averaged intensive properties for the purpose of simplified modeling. Regarding the properties of the matter, in thermodynamics we have two general classes of thermodynamic properties: intensive and extensive, as well as specific properties: •
An intensive property does not depend on the mass of the system. Temperature, pressure, density,
and velocity are examples of such quantities. Intensive properties cannot be summed when subsystems are broughttogetherinto single system. An extensive property depends on the mass of the system. Volume, kinetic energy, and momentum are examples. Extensive properties are summed when several subsystems are brought together to a single system. A specific property is obtained by dividing an extensive property by the mass, thus becoming independent of the massof the system.
•
•
For example,the specificvolume v is obtainedby dividingthe volume V by the mass:
v
v=-
(14-56)
m
Extensive properties (apart from the mass m) are usually denoted by uppercase letters, whereas lowercase letters are used for the corresponding specificproperties.
14.7.2 Thermodynamic Equilibrium and Thermodynamic Processes The continuum postulate mentioned in the previous section allows us to characterize a system by a few propertyvalues. This assumption is dependent on thermodynamic equilibrium of a system:
•
•
Thermodynamic equilibrium of a system means that its thermodynamic properties such as temperature, pressure, etc. are .uniform throughout the system. The properties may change with time as long as this uniformity or homogeneity is preserved. A system being in nonequilibrium meansthat the system has a spatialnonuniformity of some of its properties, which also may change with time. For example, if the temperature is suddenly increased at the comer of a region, spontaneous redistribution is assumed to occur until all parts of the region are at the same temperature, which meansthat the system has returned to an equilibrium state.
The system undergoes a thermodynamic process when it changes from one equilibrium state to another through a series of successive states: •
A quasiequilibrium process occurs when the system is passing from state to state at most has infinitesimal deviations from equilibrium, i.e. each successive state can be regarded as being in equilibrium. For example, expansion and compression of gases in an internal combustion engine can be approximated well by quasiequilibrium processes.
Chapter 14 Basic Laws of Nature 493
--------------------
A nonequilibrium process occurs when the system goes from one equilibrium state to another through a series of nonequilibrium states. A typical example is combustion for which very fast changes occur nonuniformly at a reaction surface that propagates throughout the region. The uniformity assumption cannot be maintained at all times.
•
The basic assumption behind a quasiequilibrium process is that the spontaneous redistribution of quantities such as temperature and pressure after a small change is much faster than the changes of quantity ·values caused by the process itself, which means that the uniformity approximation is still reasonably valid. The surroundings play no part in the notion of equilibrium. However, it is possible that the surroundings do work on the system, e.g. via friction. Also in that case, to be a quasiequilibrium process it is only required that the properties of the system be uniform at any instant. A system that undergoes a quasiequilibrium process that returns to the same state is called a cycle: A thermodynamic cycle is a process consisting of series of quasiequilibrium processes for which the system from an initial state after going through the cycle will return to the same state.
•
A typical cycle is depicted in Figure 14-17. p
4
3
v Figure 14-17. A thermodynamic cycle.
It is common that a process cycle has a subprocess in which one of the thermodynamic quantities remains unchanged. Such a subprocess is labeled by the prefix iso: • • •
An isothermal process is one in which the temperature is held constant. In an isobaric process the pressure is held constant. An isometric process is a constant-volume process.
We will now take a look at the properties of so-called pure substances, i.e. with homogenous composition.
14.7.3 Compressible Pure Substances A pure substance is homogeneous, i.e, has the same chemical composition throughout a region. It may exist in more than one phase: solid, liquid or gas, but all phases must have the same chemical composition. For example, water is a pure substance - only one kind of molecule, but air is nonpure - a mixture of different kinds of gas molecules. Air is homogeneous in its gas phase, but not necessarily in its liquid and solid phases.
14.7.3.1 Ideal and Nonldeal Gases When the vapor of a substance has relatively low density the interaction between the molecules is low enough to fulfill the conditions of an ideal gas, meaning that the well-known ideal gas law holds:
P·V=n·R·T
(14-57)
494 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica where P is the pressure, V is the volume, n is the number of moles'" of the substance, T is the temperature and If is the universal gas constant, which has the same value 8.314 (kJ/(kmoI.K» for all gases. The ideal gas law can also be expressed as follows:
P·V=m·R·T
(14-58)
where m is the mass of the system,and R is the gas constant for the particulargas:
Ii
(14-59)
R=M
Here M is the molar mass, i.e. the mass of a mole of the substance:
M=m
(14-60)
n For example, for standard air the value of Mis 28.97 (kg/kmol), and R is 287 (J/kg). When the pressureis high enough,the assumptions behind the ideal gas law are not fulfilled since other kinds of interactions between the gas molecules come into play. For example, the van der Waals equation of state is intended to account for the volume occupied by the gas molecules and for the attractive forces between the molecules. This law is an example of a nonideal gas law: p=R.T
v-b
.s:2
(14-61)
v
where P is the pressure, R is the gas constant, v is the specific volume as defined by equation (14-56), and a and b are constants which are related to properties of the particular gas. There are other forms of gas laws that are more accurate, e.g. for higher pressure.
14.7.4 Work and Heat Work and heat are two forms of energy that can flow across a system boundary. A common and simple definitionof work W, with energy units (Nm-newtonmeter) or (J-Joule), is the following: (14-62) W=F·l
where W is the work done by moving an object a distance I against a force F. In thermodynamics we use the convention that work done by a system on its surroundings is positive22, i.e. energy is flowing from the system into the surroundings. For example, a system consisting of a cylinder containing a gas expanding against a piston is doing positive work, whereas negative work is the case if the piston is compressingthe gas. 14.7.4.1 Quasiequilibrium Work
There are many kinds of work that can occur in different systems for different engineering situations. One example is the work done to move a boundary against a pressure force, e.g. as depicted in Figure 14-18 below. We have quasiequilibrium work if the movement is slow enough compared to molecular movementsso that the system is approximately at equilibriumat all times.
of a substance is 6.0225 '1023 entities, typically molecules, thatmake up the substance. 22 Notethat thisis opposite to thedefinition of positive flow for Modelica connector quantities of a component, where positive valueof a connector flow variable is into the component. However, theinternal quantities of a system component are usually defined independent of theconnectors. 21 A mole
Chapter 14 Basic Laws of Nature 495
dl ••• 0 •• 00 •• 0 •••• 0 ••• ••••• ••••••• • 0 •• 0 •• ••••••••• • 0 •••• 0 •••
::::::::::::::::Oas:::::::::::::::
.
•
•
•••
•••••••
•
0
0
0
.
••••••••
•••
0
••
0
•••
Figure 14-18. A system consisting ora gas filled cylinder doing work on the surroundings by pushing up a piston.
The infinitesimal work dW done by the system when the gas expands is the force p. A multiplied by the distance d/: (14-63)
dW=P·A·dl
where P is the pressure, A is the piston area, and d/ is the distance moved by the piston. Since the infinitesimal change in volume is dV = A .dl , we get the total work by integrating p. dV : (14-64) Thus the work exerted by the system when expanding from volume VI to volume V2 is the integral of the pressure as a function of volume.
14.7.4.2 Nonequlllbrium Work It must be emphasized that only the work done by a quasiequilibrium process can be computed by the integral in equation (14-64). In the nonequilibrium case the work must be obtained using other relations) e.g. conservation of energy, to be discussed in the next section.
control volume rotating shaft
paddle wheel
Figure 14-19. A thermodynamic example system with a control volume and a rotating shaft with an attached paddle wheel that performs nonequilibriurn work on th.esystem when the weight attached by the wire around the wheel causes the shaft to rotate.
An example of a system with nonequilibrium work is a paddle wheel rotating in a control volume filled with a gas or fluid, as depicted in Figure 14-19. The homogeneity assumption is not fulfilled around the rotating paddle wheel, where there is turbulence and local variations in pressure and velocity of the substance. For the system depicted in Figure 14-19 the work done by the paddle wheel can be found from the distance the weight is lowered multiplied by the gravity force together with the principle of conservation of energy, where we neglect the rotational energy of the rotating shaft and paddle.
496 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
14.7.5 First Law of Thermodynamics-Conservation of Energy One of the fundamental laws of nature is the law of conservation of energy. In the context of thermodynamics, when the effects of heat transfer and internal energy changes are included, this is called the first law of thermodynamics. This means that in a cycle the heat energy transfer ~Q is equal to the work ~ W done for the system, i.e. no change in total energy:
(14-65) In our example with the falling weight in Figure 14-19, a direct consequence of the first law is that the heat transfer to the gas or fluid in the control volume is exactly equal to the work done by the falling weight.
14.7.5.1 Main Energy Forms In the beginning of Section 14.7.1 we briefly mentioned the most important forms of energy dealt with in thermodynamic system models. Of those, thermal energy and chemical energy are two forms of internal energy, We summarize the three main energy forms:
• • •
Internal energy, denoted U or specific internal energy u = U / m for a system with mass m (we include possible nonnegligible radiation in the notion of mass). Kinetic energy, e.g. m- v 2 /2 for a substance of mass m moving with macroscopic speed v. Potential energy, e.g. m- g . z due to the elevation z of a substance with mass m in the gravitational field.
14.7.5.2 Enthalpy Enthalpy, denoted H, is an energy term that is a combination of internal energy U and work done by an expanding volume of a substance in a constant pressure situation. The enthalpy of a substance has physical relevance since it occurs in models of many engineering situations. The specific enthalpy h=H/m is actually a property that has been measured and tabulated for many common substances. The enthalpy H of a system, typically being a substance in fluid or gas form, is defined as follows: (14-66) H=U+P·V where U is the internal energy of the substance in the system,P is the pressure, and V is the volume. The specific enthalpy h is obtained by dividing by the mass m of the system: (14-67)
h e u-r P>v
=
where u is the specific internal energy, and v V / m is the specific volume of the substance. Consider a system for which the kinetic energy changes and potential energy changes are neglected and all other kinds of work are absent. An example of such a system is the cylinder containing a gas depicted in Figure 14-20 to which heat is slowly added under constant pressure, i.e. a quasiequilibrium process. Then the first law of thermodynamics, i.e, conservation of energy, gives:
(14-68) where ~Q is the added heat, ~W is the work done on the piston by the volume expanding against constant pressure, VI is the internal energy before the process of adding heat and the volume expansion, and U2 is the internal energy after the process has finished.
Chapter 14 Basic Laws of Nature 497
..
., ...........
... o.- . .. . ................... .. .. . ................... ••
0
............. . ............ . ................. ................... , , ................... " . t •••••••••••••••••• '0 •••••••••••••••••
,
•••••••••••••
••••
0
•••••
0·
0
•••••••••
••
••••• ••••
•
••••
0
0
••
'0'
••
_0
0
•••
0
•••••••
••••••••••
0
•••••••••••••• 0 ••• •••• 0 ••••• 0 ••••••
. •
•
0"
••••
.
•••••••••••••••
••••••
0
00
••••
0.0
•••
••••••••••••••
,
•••••••••••• 0 •••••• •••••••• ••••••• • 0"·
•••••••• 0 ••••• t •• , 0 •••••••••••••••••• ••••••• 0 to ••••• _0 ••
:::::'::::::::~~:::::::::::::::: ... .
.
:::::::.:::::::Qa;~::::::::::::::: .................
.
~Q
..0 . . . . . . . . .o.. . • . . • . •
•
'"
••••••••
•••••••
::::::::.:::::::@::::::::::::::::. .
..,
.
~Q
Figure t 4-20. A system where heat is added under constant pressure. The increase in enthalpy equals the added heat energy for the system. The cylinder system with expanding volume performs work in raising the piston a distance z against the force, given by p. A , created by the constant pressure P acting on the piston surface area A:
AW=P·A·z
(14-69)
By observing that the change in volume (V2 - VI) = A· z, where V2 is the volume after the expansion and VI is the volume before the expansion, and substituting into the previous equation, we obtain the following expression for the work ~W·: (14-70) By slightly rewriting the first law of thermodynamics from (14-68) we obtain:
AQ=AW+U2-U1
(14-71)
which reformulated using (14-70) becomes: ~Q =(U
-». V)2 -(U +p. V)l
(14-72)
We note that the energy expressions on the right hand side before and after the expansion are identical to the definition of enthalpy according to (14-66). Thus we obtain the equation for conservation of energy stated for a system going through a constant-pressure equilibrium process: (14-73) where ~Q is the heat energy added to the system. For a variable-pressure process, the difference in enthalpy loses its physical significance. However, enthalpy as an energy term is still useful in engineering applications and remains a property as defined by equations (14-66) and (14-67). In a nonequilibrium constant-pressure process H 2 - HI would not equal the heat transfer. 14.7.5.3 Latent Heat and Steam Tables
The amount of heat energy that must be added to a substance at constant pressure in order that a phase change should occur is called the latent heat. For an equilibrium process, according to equation (14-73), it is equal to the change in enthalpy of the substance before and after the phase change. The substance must be in saturated conditions in the two phases. The specific latent heat is a material prcperty that has been measured and tabulated for many common substances. For example, the specific melting heat is the heat necessary to melt a unit mass of the substance: (14-74) where hi is the enthalpy of the saturated liquid and hs is the enthalpy of the saturated solid. Likewise, the heat ofa vaporization is the heat required to completely vaporize a unit mass of saturated liquid:
498 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica (14-75) where hg is the enthalpy of the saturated gas andh, is the enthalpy of the saturated liquid. When a solid changes phase directed to a gas, sublimation occurs. The melting heat and the heat of sublimation are rather insensitive to temperature or pressure changes. However, the heat of vaporization and related properties is stronglypressure dependent, and has been measuredand tabulatedinto so-called steam tables for water and many other common substances.
14.7.5.4 Mass and Energy Conservation In Control Volumes
Recall our previous defmitions of thermodynamic systems and control volumes respectively, in Section 14.7.1 on page 491. Only energy is allowed to cross the boundariesof a closed system, whereas both mass and energy can cross the boundaries of a control volume. The restriction that only energy crosses the boundaries of a closed system is acceptable for many practical problems of interest,includinga simplified analysisof the power plant system schematically depicted in Figure 14-21 below.
--. Steam (high-energy)
System boundary Win
Pump
Figure 14-21. A schematic picture of a power plant system consisting of four control volumes: pump, boiler,
turbine, and condenser. However, for a more complete analysis we need to study the components of the power plant. These are control volumes and not closed systems in the thermodynamic sense since mass flows into and out of these
components, and they can be described by a single phase (i.e., one set of intensive thermodynamic properties).
Figure 14-22. A generic control volume with mass flows and energy flows.
A rather genericcontrol volume that representsthe propertiesof many specific controlvolumes is depicted in Figure 14-16. We will develop relations involving mass flow rate and the common, thermodynamic
Chapter 14 BasicLaws of Nature 499 quantities for this control volume based on.conservation of mass and conservation of energy. More details regarding this control volume are available in Section 15.2.4 on page 534. Conservation of mass means that the change of mass Sm in the control volume must equal the difference between the mass ilm;n entering the system and the mass amou, leaving the system since no mass can disappear: (14-76)
By observing the mass change during a finite time increment ~t we obtain the average mass flow rate &n I lit . If we let the time increment become infinitely short, lit -4 dt, we obtain the relation for the mass flows of the control volume: dm
.
-=m;n
dt
.
(14-77)
-m oul
The principle of conservation of energy for the control volume, abbreviated c.v., can be stated as follows:
Changeof Energy Energy Netenergy energyin c.v. = entering c.v. - leaving c.v. + transferred to c.v. Ae,v. AE;n AEout L1Q-~W
(14-78)
where AQ is the heat energy transferred to the control volume and aW is the net work done by the control volume on the surroundings. Remember that the total energy E of a system is composed of kinetic energy Ek;n' potential energy E POI' and internal energy U: (14-79)
E=Ekin+Epot+U
Thus, the terms for energy changes tiE;n and M out during a certain time increment & are composed of terms for kinetic energy mv 2 /2, potential energy mgz, and internal energy mu :
M
M
-
in -
2 v~
ilm in
+ Sm in g Z;n + .1min
- Sm OUIV;UI
out -
2
U;n
(14-80)
+
Sm
out
g Zout + Smout
Uout
where ~m;n is the inflowing mass-fluid or gas-during the time increment !it, v1n is the velocity of the inflowing mass, g is the gravitational constant, zin is the vertical position of the inflowing mass, and uin is the specific internal energy for the inflowing substance. Analogous definitions apply to the quantities for the outflowing mass used in the second equation of (14-80). The work aW that the control volume performs on its surroundings during the time increment ~t is composed of two parts: the.work due to the pressure needed to move the fluid or gas into and out of the control volume, sometimes called flow work, ,1 Wflow' and other forms of external work, .6We , done by the expanding control volume to move the piston as well as work done by the rotating shaft, sometimes denoted shaft work, aWs' included in aWe. This can be expressed as:
aW = L1 Wflow + l!.We
(14-81)
or in the following form where the expression for the flow work is stated explicitly: AW
= Pout A out vout f!t -
r; A;n v;n lit + ~ We
(14-82)
where Pout ~ut is the pressure force caused by the pressure Pout against which the outflowing tluid or gas is moving through the output pipe with cross-section area Aout and the term v ou: ·at is the distance the fluid or gas is moving with velocity v out during the time increment at . The following equation relates fluid or gas flow velocity to mass flow rate:
500 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
A.v = A·dx = dV = dmldt =_ dt dt dmldV p
(14-83)
where A is the cross-section area of the pipe, v is the fluid or gas velocity, dx is the distance increment covered during the time increment dt, the volume increment dV corresponds to the distance increment, dm is the mass within the volume increment transported during the time increment dt, p is the density, and mis the mass flow rate. By substituting the above expression into (14-82) we obtain the desired form of the equation for the work IlW:
IlW= Pout m tit-P;n rho Jlt+JlW out p. In e Pout In
(14-84)
Recall the energy conservation equation (14-78) for a control volume:
tiE e . v . =tiEin -tiEout
+~Q-~W
(14-85)
By substituting the derived expressions for energy and work we obtain the complete energy conservation equation relating the energy change tiE e.v . for a control volume during a time increment ~t to inflows and outflows of mass and energy:
(14-86)
14.7.5.5 Energy Flow, Internal Energy, and Enthalpy The previously derived energy conservation equation (14-86) is easily converted into the energy equation for control volumes that relates energy and mass flows, by dividing both sides by 6.t and letting the time increment become infinitesimally small, l.e, ~t ~ dt :
P;n ') . (v;ut Pout) Q. W· --=m;n (v;~ -+gZin+u;n+-I-m out --+gzout+uout+-- + - e dt 2 Pin) 2 Pout
as.; .
(14-87)
Using our previous definition (14-66) for the enthalpy H we obtain the specific enthalpy h:
H
h=-= m
U+p·V P P =u+--=u+m mlV p
(14-88)
Substituting the specific enthalpy into (14-87), we obtain the enthalpy form of the energy equation:
dE v. V;n • - c.= min ( 2 dt
Vout 2+ g Zin + h;n )- rn· out(2 - - + g Zout + hout
l
2)
+Q· -
· We
(14-89)
For many control volumes, such as the one depicted in Figure 14-22, there are negligible changes of kinetic and potential energy since the fluid or gas does not move or change level very much within the control volume. Thus the energy equation can be simplified by eliminating the terms for changes in kinetic and potential energy:
dE e.v. _ . hin -m· hout + Q. - W·e ---min out dt
(14-90)
Chapter 14 Basic Laws of Nature 501 The total energy in the control volume is the sum of the kinetic energy the internal energy U:
Ee.v. =Elcin + E pot + U
E/Cin'
the potential energy
E pot'
and
(14-91 )
If we assume that the changes in kinetic energy and potential energy are zero and use the above equations (14-90) and (14-91), we obtain an equation for the internal energy of the control volume assuming negligible changes of kinetic and potential energy: (14-92) The specific internal energy can be expressed as follows assuming the specific heat capacity of the substance is constant within a temperature range close to some constant temperature To:
u
u=-
(14-93)
m
u = Uo +cv(T -To) where Uois the specific internal energy at some constant temperature To and c, is the specific heat capacity of the substance at that temperature. For steady flow, which is a very common situation when a gas or a vapor is flowing, we have no change of energy and no storage of mass inside the control volume: dE
----f:.!:...
dt
=0
(14-94)
tit =min = mout simplifying (14-89) into the energy equation for steady state flow:
· Q. - m·(h h W e -
-
in -
out
+g
(
Zin - Zout
)+-(Vi~- - - I -V;ut) ')
2
(14-95)
)
where we have not assumed negligible potential and kinetic energy changes. Regarding a control volume through which liquid flows it is better to use the previously developed form (14-87) of the energy equation. For steady state liquidflow with Pout = Pin = P, neglecting the heat flow rate (Q =0) and internal energy changes (U =0), we obtain:
W·e
= m.(1';n - Pout + g ( z;n _ P
Zout
)
~- V;ut +( v- -) ) 2
(14-96)
which is the form of the energy equation commonly used for a pump or a hydroturbine. If the heat flow rate Q or the internal energy changes U are not negligible, just include them in the above equation.
502 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
14.8 Multibody Systems What is a multibody system? It can be defined as a system consisting of a number of interacting bodies or substructures (Figure 14-23 and Figure 14-24). A multibody system can be almost anything from an atom containing a nucleus and electrons, to star systems with gravitational interaction between bodies, as well as man-made three-dimensional mechanical systems such as vehicles, airplanes, and industry robots. In the following, we restrict ourselves to multibody systems subject to Newtonian physics, i.e., excluding microscopic quantum mechanical systems such as atoms. We also restrict ourselves to rigid bodies and thereby exclude deformable bodies that may change shape and size. Our goal in this section is to explain the basic concepts and derive the most important equations for multibody systems in the form they appear in the Modelica MBS library.
Figure 14-23. A vehicle such as a bus is a multibody systemwith a numberof movingand fixed parts. The basic quantities associated with the bodies in the multibody system are the following 3-vector valued quantities (shown in bold font): potential (nonflow) quantities position s, velocity v, and acceleration 8, angular position or degree of rotation 9, angular velocity (0, and angular acceleration also denoted a or Z, as well as the flow quantities force f and torque 1'. These quantities are defined precisely and explained in the following sections.
ro,
Figure 14-24. Exampleof a multibody system with force elements and joints constraining movements and transmitting forces between the bodies. The motion of the bodies (or subsystems) is fundamental to the understanding of a multibody system. The field of mechanical multibody systems can be divided into three areas: rigid-body mechanics being briefly presented here, structural mechanics, and continuum mechanics. The term rigid-body implies that the distance between any two particles of the body remains constant at all times. The motion of a rigid body moving freely in space can be completely described by six generalized coordinates, three positions and
Chapter 14 Basic Laws of Nature 503 three rotations, whereas for a deformable body a large number of coordinates (large dimensionality) is needed. Structural mechanics might be seen as a subtopic of continuum mechanics primarily dealing with deformation, whereas continuum mechanics in general deals with general body motion, often resulting in mathematical models with problems such as nonlinearity and large dimensionality.
14.8.1 Reference Frames and Coordinate Systems The configurations of the bodies in the multibody system are characterized by values of measurable quantities such as positions, velocities, and accelerations. These values must be related to some coordinate system or frame of reference, e.g. as described by classes such as Frame, Frame_a and Frame_b in the Interfaces sublibrary of the Modelica MBS library. Figure 14-25 shows two coordinate systems. The reference frame X I X 2 X 3 to the lower left consists of the orthogonal axes Xl, X 2, and X 3 based in the origin point 0 of the system. The orientation of the axes is defined by the unit vectors it, i 2, and h pointing along the respective axes. An arbitrary vector, e.g. depicted in Figure 14-25, can be expressed in this coordinate system using its three components along the respective axes:
r/ r/p, rip, r;p
;
rp
=Tipi ·• It + r2pi .. '2 + r3pi .. 1 3
(14-97)
In a cartesian coordinate system this can be stated using mathematical vector notation:
(14-98)
or using the more compact curly braces vector notation:
; ;} r p; = {i 'lp' r2p , r3p
(14-99)
Note, however, that even though equations (14-97) and (14-98) appear equivalent, there is a subtle difference. Equation (14-97) is always true as stated, whereas (14-98) is relative to a particular cartesian coordinate system and might look different if another coordinate system is chosen.
iJ
O~---4~---~
it
Figure 14·25. Reference frame X t X 2 X 3' also called the inertial coordinate system, and the body coordinate system X~X~X~ for body i, conceptually consisting of arbitrary point-like particles pi . In general, two types of coordinate systems are needed in multibody systems: •
A global or inertial frame of reference, also called the inertial coordinate system or inertial frame. 'The inertial frame can be represented by an instance of the class InertialSystem in the Modelica MBS library. The unit vectors it, i2, and h of the inertial frame depicted in Figure 14-25
504 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
•
are fixed in time, i.e., they have constant magnitude and direction, and the origin 0 of the system does not move. A body coordinate system, or body frame of reference, attached to each body in the system, that translates and rotates with the body. Such frames can be represented by instances of the classes i i Frame_a and Frame_b in the Modelica MBS library. The unit vectors iii, i 2 , and i 3 of the body coordinate system of body i have changeable orientations, and the origin d is subject to translational movement.
The reason to have a body coordinate system attached to each body is that many local relationships and formulas related to the body become much simpler when expressed in the body coordinate system. The vectors expressed in the body frame can always be transformed into the global inertial coordinate system through translational and rotational coordinate transformations, which is needed when quantities from different bodies are related to each other.
14.8.2 Particle Mechanics with Kinematics and Kinetics The subject of dynamics involves the study of the motion of particles and bodies, and can be divided into two subareas: •
•
Kinematics studies motion without regard to the forces that cause it, i.e., with focus on geometric aspects. Kinematic quantities are translational and angular position, velocity, and acceleration, which become "potential" nonflow variables in Modelica models. Kinetics deals with motion including the forces that produce it. Force-related kinetic or dynamic quantities are force and torque, which are represented by flow variables in Modelica models.
In order to understand the kinematics and dynamics of bodies in a multibody system, it is important to understand the motion of the particles that comprise the body. Therefore we start with a short discussion of the kinematic and dynamic properties of particles. 14.8.2.1 Particle Kinematics
A particle has no dimensions and therefore can be represented by a point in three-dimensional space. Therefore, the motion of a particle can be treated as translational motion of a point relative to a frame of reference. The position vector r of a point p in a coordinate system as depicted in Figure 5-33 can be expressed as follows: r
= 'i
. i 1 + r2 • i 2 + r3 • i 3
(14-100)
which in a cartesian .coordinate system can be stated using vector notation: (14-101)
Figure 14-26. Positionof a particle P with respect to a coordinatesystem.
Chapter 14 Basic Laws of Nature 505 The velocity v of a particle represented as a point is the time derivative of the position vector of that point. This can be expressed as follows in an inertial coord.inate system where the unit vectors it, i 2, and h have constant magnitude and direction:
. d .• .. .• v =r = - r = '1 'I t +'2 '1 2 + '3 '1 3 dt
(14-102)
The acceleration of the particle becomes:
.
d
..•
a = v =- v = Ii dt 14.8.2~2
'1 1
..•
..•
+'i '1 2 +'3 '1 3
Particle Dynamics
The motion of a particle is determined by Newton's second law:
. d f =p=-(m'v) dt
(14-103)
where f is the applied force and p is the momentum. For nonrelativistic cases where the mass m is constant, this can be expressed as an equation relating the force vector f to the acceleration vector a:
f=m.a
(14-104)
This corresponds to the following three scalar component equations: II
=m . aI' /2 = m . a 2 , /3 = m . a 3
(14-105)
14.8.3 Rigid-Body Mechanics Rigid bodies have masses that are distributed in space, i.e., not just point masses. A rigid body can be thought of as consisting of a very large number of particles, all related by fixed relative translations and rotations. Therefore a rigid body as a whole can be characterized by three translational and three rotational coordinates, six in total. Figure 14-25 depicts a rigid body i in three-dimensional space, together with the global inertial coordinate system X tX 2X 3 and a body local coordinate system X~X~X; whose origin 0; is rigidly attached to some point in the body, and which translates and rotates with the body. The position of i an arbitrary point Pp of the body can be defined by the vector r pi = {rlpi, r2p', r3pi} in the global coordinate system as depicted in Figure 14-25, and defined as the sum of two vectors: (14-106) where 0; = tOt;, 02;, 03;} is the position of the origin 0; of the body i system, and the relative position vector i up = {Utpi, U2pi, U3pi}, both expressed in the global coordinate system. However, the relative position is more conveniently obtained as the fixed vector 0 1 ={Uti , U2;, U3 /} in the local body coordinate system since it denotes a flxed rigid vector relative to the origin 0 1• If the local system unit vectors i t i , i 2/, and i 3i are expressed in the global coordinate system, we obtain up' as follows: (14-107)
The rotational transformation from the local coordinate system to the global inertial coordinate system can be represented by a rotation matrix Si, as further discussed in Section 14.8.4. Since up i is relative to the and we keep the same scale, only the rotational transformation remains and we obtain: origin
o
(14-108)
506 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica Putting everything together, with the translation taken care of by the vector 0;: (14-109)
14.8.4 Rotation Matrix The rotation matrix s' is used to perform rotational transformations of vectors expressed in the local body i coordinate system to the global inertial system. There are several different ways of deriving this rotation matrix, including Euler angles or Euler parameters. Such methods have computational and modeling advantages but will not be described here since they are more complicated than the simple method of directioncosines which is used by the ModelicaMBS libraryand presented in the next section. 14.8.4.1 Direction Cosines
Consider the local body i coordinate system or frame and the global inertial frame. The origins of both frames have been placed at the same point to eliminatetranslation as depictedin Figure 14-27.We want to derive the coordinatetransformation of a point u' = {UI', U2', U3'} expressed in the globalframe of reference to the same point 0' = {iit i, ii 2i, U3 i } expressed in the local frame , and vice versa. Let il', i 2i , and i 3' be the orthogonal unit vectorsof the local body i frame X~X~X;, and ii, i 2, and i 3 the orthogonal unit vectorsof the inertialframeX I X 2 X 3 •
Figure 14-27. Angles for direction cosines between the x,' axisandthethree inertial system axes.
Let Pit P2, and P3 be the angles between the x,' axis and the three inertial frame axes Xl, X2, and X3 respectively, as depicted in Figure 14-27. The direction cosines CII, C12, and Cl3 of the XI; axis with respect to the three inertial frame axes X I, X2, and X3 can be obtained as follows by taking the cosines of the angles or the scalar productbetweenthe unit vectors:
cll
=COS(PI) =i~ · il
C I2
= COS(P2) = i~ · i 2
(14-110)
c n = COS(P3) =i~ · i 3 In a similar way, the direction cosines C21, C22, and C23 of the X2; axis and C31, C32, and C33 of the X3' axis with respect to the inertial frame axes X., X2 , and X3 can be computed. Using these relations one can define the unit vectors i t i , i 2i , and hi in termsof the unit vectors it, i 2, and i 3: It
.;
=Clli.t + Cl2.12 + Cn .' 3
1·12
• + C 12 • +C • = C 2111 Z2 Z31 3
+
· · 1•i C32 1z 3 = C311t
(14-111)
• + C3313
We now consider the three-dimensional vector u' with components Ut', U 2 fi3i in the local frame: ',
i U2 , U3;
in the inertial frame and Uli,
Chapter 14 Basic Laws of Nature 507
(14-112) Using the fact that the product between orthogonal unit vectors is 0 if they are different and 1 if they are identical, we obtain:
(14-113)
which in matrix notation appears as:
II
Cl 2
c l3
C 21
C 22
C 23
C 31
C 32
C 33
-i
u1 -i
=[C "2 -i "3
u1i u2i u3i
(14-114)
that is: (14-115)
ii' = Cu' Since for orthogonal matrices such as C, the inverse of a matrix C- 1 = C matrix, we obtain:
T
,
is equal to the transpose of the (14-116)
Thus, our desired rotational transformation matrix S, also denoted R -I , for transformations from the local body i frame to the global inertial frame is: S=C T (14-117) The opposite transformation, the rotation matrix R for transformations of vectors from the global inertial frame to the local body i frame, used in the new Modelica multi-body library (see Section 15.10, page 587), then becomes:
R=C=S-I
(14-118)
The function V2=MultiBody.Frames.resolve2(R, vl) for transforming a vector vl from frame 1 to frame 2 is intended for vector transformations in this direction, e.g. from the inertial frame to the local body frame.
14.8.4.2 Euler and Cardan Angles In the previous section we formulated a rotation matrix based on direction cosines of the angles PI, P2, and
P3 between the local body frame axes and the three inertial frame axes.
However, from a physical modeling and application point of view it is usually more natural to express the rotational transformation as a series of successive rotations around the local body coordinate axes. This approach to constructing the rotation matrix is called Euler or Cardan angles, depending on the order these rotations are applied. These angles are different from the angles used in the direction cosine formulation described in the previous section since the a rotation around one local coordinate axis causes the direction of the other two local coordinate axes to change. Assume that the axes of the local body frame are initially aligned with the global inertial frame, and that the body is then rotated, described by a vector {91l ,912,(fJ3} for the three successive rotation angles. To rotate the local body frame coordinate system from its initial configuration aligned with the inertial frame to some arbitrary desired orientation using the Cardan angle approach-rotation sequence {l ,2,3 },
508 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica we first rotate around the x axis (the first axis) by an angle qJJ, then around the resulting y axis (the 2nd axis) by an angle qJ2, and finally around the resulting z axis (the 3rd axis) by an angle l{J3. The third step is shown in Figure 14-28 assuming the first two rotations are zero. The Euler angle rotation sequence is {3,1,3}.
JIC-----~
Xl
Inertia) frame
Figure 14-28. Rotating the Xli and X2i axes in the local coordinate frame by an angle lfJ3 around the X3i axis as a step in the CardanlEuler angle rotation sequences. The respective rotation matrices denoted RJ, R 2, and R 3, are defined as follows using Cardan angles:
RI
;(~ CO.~qJl Si~qJl)' R ;(C~~qJ2 ~ -Si~qJ2), R :(~;iSn~3 ;:~~) 2
o - sm fIJI
cos 'PI
3
0
sin lfJ2
coslfJ2
0
0
(14-119)
1
Each of these three rotation matrices can be obtained by applying the MBS library function MultiBody. Frames. axisRotation (i, angle) to the arguments (1, qJI)' (2, ({J2)' or (3, tJ'3) respectively. The total rotational transformation matrix R = R 3 • R 2 • R I (which is defined in the MBS class MultiBody. Parts. Body) for rotating the local body frame to its desired orientation then becomes: COSqJ2 COSqJ3
R: -COS.qJ2 sinqJ3 (
cosqJt sinqJ3 +sinqJl sinqJ2 COSqJ3
COSqJl COSqJ3.-sinqJl
sinqJ2 sinqJ3
- sin fIJI cos flJ2
sin f{J2
sinqJI sinqJ3 -cosqJt
sintp2 cos 9'3 )
sinqJl COSqJ3 +COSqJl sinqJ2 sinqJ3
(14-120)
cos ({Jl cos flJ2
This rotation matrix R is based on Cardan angles, i.e. the rotation sequence {1, 2, 3 }. An absolute vector u' expressed in the inertial frame can be transformed into the relative vector iii expressed in the local body frame using the rotation matrix R: (14-121) This rotation is used, e.g. in the Modelica MBS library, in class MultiBody. Parts. Body. The rotation matrix in the other direction, rotating the local body frame back to the orientation of the inertial frame, is obtained as usual by taking the inverse (i.e., the transpose) of the orthogonal matrix R: (14-122) The inverse transformation applied to a local body vector, i.e., of the vector iii expressed in the local body frame into its representation u' in the inertial frame, is obtained by applying R-Ior by successively 1 applying the 3 inverse rotations, starting with R 3 • i ; - R- IU
U -
-
-
I- i R-IR-IR1 2 3 U
(14-123)
Chapter 14 Basic Laws of Nature 509
14.8.4.3 Euler Parameters and Quaternions The singularities that occur when computing derivatives of rotations for certain Euler angles can be avoided if a 4-vector representation q = { q. ' q2' q3' q4 } of four interdependent variables is introduced instead of our previous 3-vector Euler angle representation. These 4 variables are dependent on each other since a rotation matrix represents 3 degrees of freedom. This representation is known under two names: Euler parameters or Quaternions-note that the Euler angles presented in the previous section is a different representation. The rotation matrix R can be computed as follows in terms of these four parameters:
2(q; + q;) -1
R= 2(qlq2-q3q4)
2(qlq2 + q3q4) 2(qlq3 - q2q4) 2(qi+q;)-1
2(q2q3+qlq4)
2(qlq3 + q2q4) 2(q2q3 - qtq4)
2(qi + q;)-1
(14-124)
or expressed using matrix and vector operations:
R =(2q; -1)1 + 2ql-3q;-3 - q4Q~3
(14-125)
where I is the 3x3 identity matrix, ql-3 is a column vector of elements 1-3 of the q vector, and Q~3 is the skew matrix (see (14-138) , page 511) formed from the vector Ql-.3. These definitions are available in the function MultiBody. Frames. fromQ in the Modelica MBS library, see Section 16.8.9, page 637 and in Appendix D. We will not further discuss this representation, and refer the reader to appropriate literature. The Modelica MBS library has an option to use quaternions, see the note in Section 15.10.11, page 610.
14.8.5 The 4 x 4 Transformation Matrix Previously we showed (14-109) that the position r' of an arbitrary point P on the rigid body could be expressed in the global inertial frame as: (14-126) where 0 1 is the position for the origin of the local body i coordinate system or frame, s' is the matrix for rotationai transformations from the local frame to the global frame, and 0# is the position of the point P expressed in the local body i frame relative to the origin This transformation can be expressed compactly using a 4 x 4 transformation matrix 8 4; that takes care of both rotation and translation, where we introduce the 4-vectors r~ and ii~: i-i (14-127) r4; = S4' U4
a.
This equation is shown in component form below where the matrix S~ is constructed from S' ando':
r/1 S:1 S:2 S:3 r.l2 S~1 S~2 S~3 = r!3 S~l S~2 S~3 0
0
0;
-i
0; 2
Ut -i U2
0; 3
U3
1
-;
(14-128)
0
The inverse equation: -i
_(Sl4 )-1. r ;
U4 -
4
(14-129)
The inverse matrix (S~ )-1 is not equal to the transpose (S~) T since it is not orthogonal, but can be constructed as follows:
510 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
(S~)-l=((Si)1
_(SiJ10i)
{O,O,O}
(14-130)
1
where the inverse rotation matrix ~i)' = ~i) since it is orthogonal. The 4 x 4 transformation matrix formulation is common in virtual reality software packages and in certain multibody system packages, but currently not used by the ModelicaMBS library. 14.8.5.1 Coordinate System Kinematics
In this section we develop the equations for frame or coordinatesystem kinematics. These equations relate the kinematic quantities position r, velocity v= r , and acceleration a= r between an arbitrary local frame and the inertial frame of reference. The developed equations are used in a slightly different form to relate quantities between two local frames, which, for example, is common for mechanical elements such as joints that consist of two parts. Two frames are related by a translation vector,e.g. 0 in Figure 14-29, and a rotation about some axis that can be expressed in the inertial frame.
x3'
X2
inertial frame
xl
0 ~-----~ Xl
Figure 14-29. A localframe related to the inertial frame by a translation vector 0; anda rotation matrix Si, with the relative position vector r rei of the point P expressed in the inertial frame.
Since the expressions for position, velocity, and acceleration of an arbitrary point P can be easily obtained just by adding the corresponding relative and frame quantities expressed in the inertial frame according to the equationsbelow, we will for a while ignore the vector 0 and focus on the relative vector rrel. r -
_
i 0 +rrel
•
-.!
•.
··i
r=o r =0
•
(14-131)
+rrel .•
+rrel
The rotational transformation matrix S transforms the relative vectorrrel expressed in the local frame i to the global inertial frame: rrel
=s' ·-rrel
(14-132)
By taking the time derivative we obtain the relative velocity vector Vrel: V rei
·
= rrel =
s·; · -rrel. + S;":" · rrel
(14-133)
The rotation matrix s' describes the change in orientation, i.e., relative angles,of the local frame compared to the inertial frame. The derivative Si describes the angular change in orientation per unit time, i.e., rotational movement. Rotation is always around some axis. The direction of that axis is defined by introducingthe angular velocity vector mi, which can change orientationover time (Figure 14-30).
Chapter 14 Basic Laws of Nature 511
Figure 14-30. Rotational part of the movement of point P expressed as cross product angular velocity vector and the relative position vector.
(0;
X frel between the
One can show that the part S; . frel of the velocity vector v rei caused by rotation of the frame around an axis through the origin 0; can be expressed as the cross product between an angular velocity vector oi expressed in the inertial frame ( m; in the local frame) and the relative vector f rei (or rrel expressed in the local frame):
Si -f rel = (0 i O
o
Xf
rel
= s' . (-i m x -f rel )
(14-134)
Thus, the total relative velocity vector of the point P expressed in the inertial frame becomes: V rei
=f rel =mi Xf rel + s' .~f rel
(14-135)
o
The velocity vector expressed using vectors in the local body frame after some rearrangement: (14-136) Here rrel denotes change of the vector rrtl not related to rotation around the origin since that rotation is already expressed by the rotation of the local frame itself. It is rather, e.g. change of length. Now we want to derive the expression for the acceleration, and for this purpose will need to transform the cross products in terms of matrix multiplications by skew symmetric matrices. A general mathematical result is that any cross product, e.g. ro x r , can be expressed as a matrix multiplication by a so-called skew symmetric matrix W: (14-137)
mXf=W·f
where
W=
0 (
-
(03
(JJ2l
C03
0
-rot
- CO 2
rot
0
(14-138)
Applying this result to the cross product with the rotation vector 0) i
Xf rel
= w' .f rel = w' .Si. f rel
0)/:
(14-139)
Substituting into the equation for the velocity vector: V rei
=
o
f rel
= ro
i
;
X f rel
-
;
+8 . f rel = W ·(8 . f rel )+8 . rrel ~
I
i
~
(14-140)
Differentiating the above equation:
(14-141) Analogous to the previous (14-134) result expressed as:
So; . .:.r rei
S; .rrel =m; xrrt l we obtain S; .rrtl =m; xrrt l , which
=ro ; X r rei = w' . f rei = W; . V rei 0
0
can be
(14-142)
512 Peter Fritzson Principles of Object-Oriented.Modeling and Simulation with Modelica
~~te~ substi~ution into. ~he previo~s acceleration equation, using f rel S' . f rel =W' · V rei' and S' · f rel = W' . rrel and rearranging terms we obtain:
=s' .f rel ,
V rei
•• ; .:.:. i • i i i 8 re1=rrel=S ·rrel+ 2W ·Vrel+W ·rrel+ W · W ·rrel
=S; ·-V rei' (14-143)
We obtain the desired form of the equation for the relative acceleration vector by converting back from matrix multiplication by to cross product by (Oi:
w
8 rei
••
= r rei
; =Si · .:.:.rrei + 2m i x V rei + ro.; X rrei + ro iX (ro X r rei)
(14-144)
To summarize, the vector equations for the absolute position r, velocity v, and acceleration a for an arbitrary point P appears as follows expressed in the inertial frame related to the relative vectors in the local frame when the translational part has been added and the relative vectors together with the rotation vector are expressed in the local body i frame:
r=o i + Si·rrel
v = 0 1 + s' ·('frel + 0); a
(14-145)
xrrel)
=0; + S; · (frel + 2m i x Vrei + cO i X rrel + m; X (
0);
X rrel »
We should mention that the special notation a is often used in the literature for the angular acceleration vectortn , but z is employed in the Modelica MBS library: a =z =ro (14-146) 14.8.5.2 Equations Relating Two Local Frames
Why would you need to relate quantities in two different local frames? A common case is that a body in a multibody system itself consists of several bodies that can move in relation to each other, each with its own frame of reference. Another case is the existence of two or more frames on the same rigid body. In both cases we need to relate quantities such as positions, velocities, and accelerations of one frame to the corresponding quantities in another frame. There is also a need to transform dynamic quantities such as forces and torques when applied to one part of a body to the equivalent forces and torques if applied to another part. The goal of this section is to develop the general form of the equations relating two local frames as they appear e.g. in several Modelica MBS library classes such as Interact, Interact2, and TreeJoint in the sublibrary Interfaces, and in the class FreeMotion in the Joint sublibrary. These relations are relevant for all Joint classes, since those classes describe objects containing two coupled parts, each with its own frame of reference (Figure 14-31).
aa
d'
Frame a
Frameb
Inertial frame 0.1--------1.. Xl
Figure 14-31. A body consisting of two movable parts,each with its own frame of reference. The equations relating two local frames are obtained in a very straightforward way, e.g. just by changing subscripts and superscripts, from the equations developed in the previous section.
Chapter 14 Basic Laws of Nature 513
I
Inertial frame 0
b
~-------t~
Figure 14-32. Two frames related by the relativepositionvectorr:'el and the relative rotation matrix S,el. The relative rotation matrix
Srel
transforms a vector expressed in frame a to frame b:
Srei =(Sb)-l·sa
(14-147)
This is easy to see since an arbitrary vector iia in frame a is transformed into the inertial frame by Sa. ii , and is transformed back from the inertial into frame b by the inverse of Sb. The kinematic relationships relating the origins of the two frames (from (14-109» to the inertial frame are: a
b
f0
=f 0 +sa-a . r rei
(14-148)
a
r;
where is the vector for the absolute position of the origin of frame b expressed in the inertial frame, is the absolute position of the origin of frame a, and r::;, is the relative vector from frame a to frame b expressed in frame a, as depicted in Figure 14-32. The relative translational motions between the origins of two frames are:
r;
-a
V rei
=
':'a
-a arel
= ~a f rel
rrel
(14-149)
a
where rr~' is the relative vector from the origin of frame to the origin of frame b expressed in frame a, and v~el together with i~el are the corresponding velocity and acceleration vectors. The equations relating the absolute velocities v and the rotational velocities (J) of the two frames are: -b V -b CO
=
S
(-a
rei' V
-a -a) + -a V rei + ro X rrel
= Srei' (-a ro + -a) rorei
(14-150)
where Vb is the velocity of the origin of frame b expressed in frame b, va is the velocity of frame a expressed in frame a, v~el is the relative velocity vector from the origin of frame a to frame b expressed in frame a, (I) a is the rotational velocity vector of frame a expressed in frame Q, 0) b is the rotation velocity vector of frame b expressed in frame b, co~el is the relative angular velocity (rotation) vector between frame b and frame a corresponding to the rotation matrix Srei and expressed in frame a. Next we state the equations relating the absolute acceleration a and the angular acceleration ro (denoted by z in the Modelica MBS library) of the two frames, expressed in frame b on the left-hand side and in frame a on the right-hand side: 0 -a ~a -0 -a (-a -a» a = S ret' (-a a + -a0rel + 20) x V ret + 0) X fret + (i) X (i) X f re1
-b
lOb = Srel . (ro a + ro~el + roa X ro~el)
(14-151)
514 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
.
derived from (14-145) and (14-150) using v~el = rr~' and a~el = rr~' The following two equations relate the vectors representing the dynamic quantities force and torque applied at the origins of frame a and frame b respectively: =s., ·fa -b S (-a -a -fa) T = rei' T - rre/ X -b
f
(14-152)
where fa and f" are the force and torque applied at the origin of frame a expressed in frame a and f band i b are the same force and torque transformed to be applied at the origin of frame b expressed in frame b. The same equations apply for transforming forces and torques in the opposite direction, from frame b to frame a.
14.8.5.3 3D Rigid-body Kinematics Here we develop the kinematic equations needed to state the dynamic equations of rigid bodies in the next section. It was previously shown (equations (14-145» that the global position vector r and the corresponding velocity v and acceleration a of an arbitrary point P of a body a (previously denoted body i) with a reference frame a, e.g. as in Figure 14-33, are given by:
r = o" + sa . rr~' V
=oa +Sa . (V~el + roa xrr~l)
8=Oa +sa .(i~e/ +2(Oa xV~el
(14-153)
+m a xr~, +o>a x(m a xFr~')) o:
o:
where rr~1 is the relative vector from the origin to point P, oa is the position of the origin in the inertial frame, Sa is the rotational transformation matrix from frame a to the inertial frame, and m 0 is the rotation vector of frame a expressed in frame a.
o~-----~
Figure 14-33•. Rigid body with a point P relative to a coordinate frame a with origin O' fixed in body a. However, for all points P in a rigid body the relative vector rr~' expressed in frame a is fixed since the essential property of a rigid body is that it does not change shape, i.e., v~el =r~, 0 and i~el =rr~' =0 , giving the following simplified equations:
=
r = o" +Sa · rr~'
v=oa +Sa ·('roa xrr~')
(14-154)
a=oa +Sa ·(ro a xrr~' +m a x(m xr~,» Q
where r, v, and a are the absolute position, velocity, and acceleration vectors of point P in the inertial system. This also can be expressed as:
Chapter 14 BasicLawsof Nature 515 r=oa+r~l
=oa +ro axr~l a =oa + lila xr~l + roa x(ro a xr~l)
V
(14-155)
with all quantities defined in the inertial system. 14.8.5.4 3D Rigid-body Dynamics Now we want to express Newton's equations governing the dynamics of a rigid body, which, for example, are stated in the old Modelica MBS library class BodyBase in the sublibrary Interfaces, inherited, for example, by the classes Body and Body2 in the sublibrary Parts, or in the new MBS library stated directly in the class MultiBody. Parts. Body. First recall (14-154) for the acceleration a of an arbitrary point P in a rigid body. We express this equation in the local frame a, using a = Sa . iia ando" = Sa . After eliminating we obtain:
sa
i; .
(14-156) where i a is the acceleration of the point P, which in the following is chosen to be the center of mass of the body, denoted em, and i~ is the (translational) acceleration vector of the origin of frame a, both expressed in frame a.
o~-----~
Figure 14-34 Body with mass m, coordinate frame a as wellas external force fa and torque i a being appliedat the origin point of frame a, and a relativevector rc':n from the originof frame a to the centerof mass of the body.
According to Newton's second law of motion applied to rigid bodies, a force (conceptually) applied at the center of mass of a rigid body equals its mass multiplied by the acceleration of the center of mass: -a
f em
=111·-a 8 cm
(14-157)
r:
The force vector (but not the torque) is the same translated to be applied at the origin of frame a on the rigid body, i.e., m =fa , as depicted in Figure 14-34. Using equation (14-156) for the acceleration m we obtain:
i:
(14··158) where fa is the force vector applied at frame a, i a is the acceleration of frame a, fll a is the rotation vector of frame a, and fc~ is the vector from the origin of frame a to the center of mass, where all these quantities are expressed in frame a.
516 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica The next issue is to derive the rotational part of the equation of motion for a rigid body, also called the Euler equation, i.e., the relation between the torque T a around a point O', the angular acceleration vector a , the rotation vector m a , the moment of intertia matrix I, etc., all expressed in the local body frame a:
m
(14-159) Let us for a while return to the basic definitions. Since a rigid body can be viewed as consisting of many particles we will recall certain relations valid for particles. The torque T around a point 0 created by a force f applied to a particle at a distance r is defined as: T=r
xf
(14-160)
where T, f, and r as usual are vector quantities. Next we introduce the notion of the angular momentum vector L with respect to a point 0 for a particle of mass m moving with velocity v as depicted in Figure 14-35, and therefore having momentum p = m- v . The angular momentum is defined by a vector cross product:
L=rxp=in.rxv
(14-161)
where r is the position vector of the particle relative to the point
o.
Figure 14-35. Vector relationbetweenangularvelocity m and angular momentum L for a particle. A rigid body can be viewed as consisting of many such particles.
The following relation holds between the torque and the angular momentum:
(14-162) This relation is just a consequence of Newton's second law of motion
r =p, as shown below:
L=~L =~(rxp) = r xp-t-r xp = vx(m· v)+rxf =rxf = 't dt
(14-163)
dt
=
Here we have used the fact that the cross product of a vector to itself is zero, v x v 0, the above definition of torque T rxf, and Newton's second law of motion r = p. Next we generalize from a particle to a rigid body based on its definition as a system of particles with fixed relative positions. The total angular momentum vector L of a rigid body:
=
L= IL; = Ir;xp; = Im;.r;xv 1
(14-164)
i
where L; is the angular momentum of one of its particles. Using (14-155) and noting that only the rotational part co x r; of v I which is perpendicular to r i contributes to the cross product, we obtain:
L=
Im; ·r; x(mxf;) =Im; ·f;
X (-f;
xee) = Im; ·R; ·(-R;· W) =I· co
(14-165)
;
where Wand R; are skew matrices corresponding to the vectors m and r;. Here we have used standard mathematical identities for vectors and skew matrices:
Chapter 14 Basic Laws of Nature 517
erxr, = -r; x oi r; xm =R;· W
(14-166)
=R;
-R;
The matrix I, called the momentof inertia matrix or mass matrix of the body t is defined as:
1=
Lm; ·R; ·R;
(14-167)
or as an integral by taking the limit of many small particles, and substituting form of the momentof inertia matrix becomes:
m, =p . dV. The integral (14-168)
The matrix I is constant for a rigid body, depending only on its shape and mass density. The following relation holds also for a rigid body defined as a system of particles: (14-169) where 1: = Tl + T2 + T3 +... is the total external torque relative to the same point exerted by the external forces acting on the particles of the body. The reason is that the internal forces between any pair of particles have the same (or opposite) direction as the relative position vector between the particles, which means that their cross product is zero. Since I is constant, we obtain:
· d . T=L=-(I·ro)=I·ro dt
(14-170)
This equation can be expressed in quantities of i
sa 'T a =!!.-(sa .La)=sa dt
a and 'La in the local body frame a:
.ta +sa .La =sa .I.i)a +sa .La =Sa .I.i)a -s- .(ii)"a xLa )
(14-171)
where we have used the relations r e S" ·iaand L=sa .[a, and have applied (14-134) to the vector LOgiving Sa.'[a=sa·(roaxLa). By removing the rotation matrix and using I:a=I·roawe obtain:
sa
(14-172) Finally we add the term ~~ x fa since the force C is applied at a position ~':n relative to the center-of-mass a
(14-173) To summarize, the Newton-Euler equations of motion for a rigid body as expressed in a local frame a attached to a rigid body of mass m are as follows: a fa =m- (a O+ mO xEem + ro a x(rooxroem ) iO = 1. ro a + (0 a x(I . (0 a ) + rc':n X fa
(14-174)
where f is the force vector applied at the origin of frame a, i a is the acceleration of frame a, 0) a is the rotation vector of frame a, roO is the angular acceleration vector (also denoted z) of frame a, and ~~ is the vector from the origin of frame a to the center of mass. These quantities are all expressed in frame a. The matrix I is the moment of inertia of the body with respect to its center of mass. These equations appear in the same form in the old ModelicaAdditions MBS library class BodyBase in the Interfaces sublibrary. That class is the base class for rigid bodies and is inherited by the class Body in the old Part s sublibrary: 0
518 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica fa ta
+ cross(za, rCM) + cross (wa, cross (wa, reM»); I*za + cross (wa, I*wa) + cross (rCM, fa);
= m*(aa =
,ro
where fa, aa, za, rCM, wa, ta, I correspond to fa ,aa a ,rcc:n,iii a ,"T a ,I respectively. In the new MBS library described in Section 15.10, page 587, and Appendix D, the corresponding equations appear at the end of the Modelica. Mechanics. MultiBody. Parts. Body class in the following form:
°-
m*(Frames.resolve2(frame a.R, a 9 0) + cross (z_a, r_CM) + cross(w_a, cross (w=a, r_CM»); frame a.t
I*z_a + cross (w_a, I*w_a) + cross (r_CM, frame_a. f) ;
The call Frames.resolve2(frame_a.R, a_O - 9_0) is just an application of the rotation matrix R, expanding to frame_a.R* (a_O-g_O), which transforms the acceleration vector a_O-g_O from the inertial frame to the local frame.
14.8.6 Constrained Motion In general, each body in a multibody system has six coordinates or degrees of freedom, three translational and three rotational. Thus, a multibody system consisting of n bodies will have 6n degrees of freedom. However, the motion of bodies in a multibody system is often constrained by couplings such as mechanical joints between bodies. In theory such constraints can be expressed as algebraic equations relating state variables from both bodies connected by the joint in addition to the usual set of equations of motion. However, because of these constraints our "standard" state variables are no longer independent. For reasons of computational effectiveness and numerical stability as well as mathematical conciseness, it is in practice usually a good strategy to express the variables as functions of a number of "generalized coordinates" or variables, where the number corresponds to the actual number of degrees of freedom for a multibody system. For example, consider a small multibody subsystem consisting of two bodies. This system has 6·2 = 12 degrees of freedom when each part can move independently. However, consider a system of two bodies connected via a revolute joint as depicted in Figure 14-36. Part 2 can move only according to one rotational degree of freedom relative to part 1, which gives a total of 7 degrees of freedom for this minimal multibody system.
Inertial frame 0 } - - - - - - - I . Xl
Figure 14-36. A multibody subsystemconsisting of two movable parts connected via a revolute joint that just adds 1 degree of freedom, giving this subsystem a total of 7 degrees of freedom. The origins of frame a and frame b coincide.
In the multibody system with two bodies connected by a revolute joint there is only one "generalized coordinate" or variable relating part 2 to part 1, namely the angle 'P. All the rest is fixed. We place the origins of frame a and frame b at the same point, giving:
Chapter 14 Basic Laws of Nature 519 b
fO
= f Oa
rr~' == 0 v~el
=0
el
=0
a:
(14-175)
where we use the notation from Section 14.8.5.2, page 512. The placement of the origins at the same point considerably simplifies equations (14-150), (14-151), and (14-152), which appear as below in simplified form:
S
-a
-b V
= -a :"
-b
=S rei' (-a + -a) COrel
(0
(J)
-b
a =
S
-a rel'a
rob =Srel . (ro -b
f
=Srel·f
-b 't
=
a
+ ro~l + roa x ro;el)
(14-176)
-fl
S rei' -a T
The above equations appear in the Modelica class Revolute that belongs to the Joint sublibrary of the old ModelicaAdditions MBS library: r_rela zeros (3) ; v_rela = zeros (3) ; a_rela = zeros(3}; rOb = rOa; vb S_rel*vai wb S_rel*(wa + w_rela); ab S_rel*aa; zb S_rel*(za + z_rela + cross (wa, w_rela»); fa transpose(S_rel)*fb; ta transpose(S_rel)*tbi
ro
where z = and (8 rei) -1 = (S rei) T. Corresponding, but slightly different equations appear in the new MBS library in Modelica. Mechanics. MultiBody. Joints. Internal. Revolute. The relative rotation vector ro:el is determined by the relative angle f{J between the two frames and a unit vector lio that defines the axis of rotation: -a (l)rel
'-a =qJ' n
"":"'a
= tp- n
(l)rel
"-a
(14-177)
As previously, the relative rotation matrix Srel transforms a vector expressed in frame a to frame b:
s rei = (Sb)-l ·sa
(14-178)
If the angle qJ=O the frames will coincide completely and STet becomes the identity matrix. The relative rotation matrix can be expressed in terms of the angle rp and the normal vector for the rotation axis: (14-179) where E is the identity matrix, 'Po is a rotation angle offset (usually selected to be zero), and N° is the Q skew matrix of ii • In the class ModelicaAdditions. MultiBody . Revolute of the old MBS library this appears approximately as: qq
=
q - qO*PI/ 1 8 0 i
520 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica S_rel = [nn]*transpose([nn]) + (identity(3)-[nn]*transpose([nn)))*cos{qq) skew(nn)*sin{qq)i
where the angles q and qq are in radians and the parameter offset angle qO is measured in degrees. The column matrix [nn] derived from the vector nn represents iio . The skew matrix Na is represented by skew (nn) .
Let us derive the above equation (14-179) for the relative rotation matrix defined by a given normal vector iio and a relative angle rp , where we temporarily ignore rpo. By the definition of relative rotation the position r b of point b is obtained by rotating point a:
=Srei· -a r The vectors r b and i a are depicted in Figure 14-37:
(14-180)
-b
r
Figure 14-37. Vectors and anglesrelated to a revolute joint. We can also express i
b
r b by adding the relative vector L\f :
= L\i + fa
(14-181)
The ~f vector can always be represented as a sum of two orthogonal vectors h2 and ~F= h 2 +h t
hI: (14-182)
The radius of rotation h can be calculated as follows:
(14-183) Ir"I· sin(a) = 1n"l-li"l· sin(a) = In" Xi"1 By construction (cross product) hI is orthogonal to both ii and its direction is given by the unit vector ii" x i Ilii" x i" I. The length Ihd can be found from the right-angled triangle BeH as h· sin( cp). By
h=
a
a
combining the relations for the direction and length we obtain:
I'
hI = ;"Q X~"a h- sin(cp) =
n xr
Similarly, vector is given by:
(ii" xi" ).sin(cp)
h2 is orthogonal to both iia
and
(14-184)
hI' which are orthogonal to each other. The length
Ih 1= h -h ·cos(cp) = h· (I-cos(cp) 2
Therefore
lii
21
(14-185)
h2 is given by:
h2 = ii" x (ii" xi" ). h. (I-cos(cp)= ii" x (ii" xi" ). (l-cos(cp) h
At this point we need to recall the relations for a skew matrix N a , for any vector i:
(14-186)
Chapter 14 Basic Laws of Nature 521
(14-187)
Let us now summarize the relations derived so far:
r = -a r + ~r- = -a r + -h, + -h 2
-b
hI = (n a xf a ). sin(qJ) = N" .'fa . sin( 0, i.e., the flowing gas or fluid transfers energy out of the control volume into an external system via the shaft.
Turbines, for which
538 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
•
Compressors, including our fan rotor example, for which into the control volume via the rotor blades.
w, < 0 , i.e., the shaft transfers energy
The shaft work is introduced here but temporarily set to zero. It will be used and redefined later when a shaft that can be connected to a fan rotor is added to our example control volume model, see Section 15.2.6, page 550. The other part of the external work includes work done by the piston when expanding the volume of air an increment dV against a pressure P during a time dt , which is P . dV , giving: Wpiston
= p. V
(15-14)
Ws =0
By some formula manipulations, previously shown in Section 14.7.5.4, page 498, we obtain the following form of equation (approximately (14-84), page 500, but divided by lit --+ 0) for the total power Wexerted by the control volume, i.e., the work per time unit:
W· =~ut.mout Pout
.r«:min + w·
(15-15)
e
Pin
where P;n' Pinand Pout, Pout are the pressures and densities of the fluid or gas at the inlet pipe and outlet pipe of the control volume, respectively. That form is used in the previous (Section 15.2.4.1, page 535) derivation of the energy equation (15-9) for conservation of energy, where we now have put back the terms for heat flowQ, and external work,
We: dU . . .. -=hin min -hout mout +Q-We
(15-16)
dt
The control volume model is further refmed by inserting the equations (15-14) and (15-16) describing work and energy balance. Furthermore, an equation for the heat flow rate Q= 0 is inserted, as well as an equation creating a change of the volume V at time t = 0.5 to illustrate the work done on the piston when the volume changes:
I0-3
,t s 0
v= {10- (I + t - 0.5) 3
In the refined model below,
,t
(15-17)
> 0.5
Qis represented by Qdot, We by Wdot_e, and Wsby Wdot_s:
model BasicVolume import Modelica.Slunits.*; parameter SpecificlnternalEnergy u 0 parameter SpecificHeatCapacity c_v parameter Temperature T 0 parameter Mass m 0 parameter SpecificHeatCapacity R Pressure Pi Volume V; Mass m(start=m_O)i Temperature T; MassFlowRate mdot_in, mdot_out; SpecificEnthalpy h_in, h_out; SpecificEnthalpy hi Enthalpy H; SpecificlnternalEnergy U; InternalEnergy U(start = u_O*m_O); BeatPlowRate Qdot; Power Wdot_e, Wdot_s;
209058; 717; 293; 0.00119; 287;
II Air at T=293K
II Addedl II Added I
Chapter 15 Application Examples 539
equation II Boundary conditions V = le-3 + 0.1.-3*(1£ time>O.5 then time else 0); mdot_in O.le-3; mdot_out O.Ole-3; h_in 300190; II Air at T=300K h out h; 17 Conservation of mass der(rn)=rndot_in-mdot_out; II Conservation of energy der(U)=h_in*mdot_in-h_out*mdot_out+Qdot-Wdot e; Wdot_e - Wdot_s = P*der(V); II Specific internal energy u (ideal gas) u=U/m; u=u_O+c_v*(T-T_O) ; II Specific enthalpy h H=U+P*Vi h=H/rn; II Equation of state (ideal gas) P*V=rn*R*T; end BasicVolume;
II
Added part
II II
Added part Added
We simulate the model and plot the mass m and pressure P as functions of time, using the Mathematica command interface to Mathmodelica:
Simulate [BasicVolume, {t,O,lO}J plm=PlotSimulation[m[t] , {t,O,l},DisplayFunction->Identity] ; plp=PlotSimulation[p[t] , {t,O,l},DisplayFunction->Identity] ; Show[GraphicsArray[{plm,plp}]] ; -jn
I t.)
- P(t)
110000 108000 106000 104000 102000
0.00128 0.00126 0.00124 0.00122
~~~........-....~.....o-........,--,-,-~t
0.2 0.4 0.6 0.8
1
Figure 15-11. The mass steadily increasesdue to a constant inflow that is greaterthan the constant outflow, whereasthere is a discontinuous drop in pressure at t=O.5 due to the instantaneous change in volumeat that time. We also plot the temperature T as a function of time (using a Mathematica-style command):
PlotSimulation[T[t], {t,O,lO}];
340 330
.//,.r'r'r'
320
//
310
-:
/'
/'
/"
~._,
//
•.
2
4
6
, •.
~
L .. ,
8
..
,.,
r.
t
10
Figure 15-12. Temperature T for the control volume.
540 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
15.2.5 Connector Interfaces to the Control Volume So far we have been increasing the realism of our control volume model by gradually adding additional equations. However, the model is not a system in the sense that the total amount of mass in the system is conserved. We need to add some external components that should interact with the control volume, i.e., build a system model that includes the control volume model. However, a well structured system model should have explicit interfaces between the components of the system. The interfaces of the control volume should reflect interaction with the surroundings, typically involving the following quantities: • • •
Mass/energy transport Mechanical work Heat
Note that some variables are internal to a component, e.g. P, V, U, u, T, H, h, m, etc., while other variables such as P;n' min' hin , etc., are used to exchange information at interfaces by interacting with the surroundings including other connected components. Take a look at our control volume model once more, as depicted in Figure 15-13.
min
u
f1n hin
h out
T
V
h
Pout
p
U
m
mass flow connector
Figure 15-13. The control volume model with explicit mass flow connectors added at the inlet and the outlet.
A slight change has been made compared to the previous figures: two small squares representing mass flow connectors have been added at the inlet and the outlet. In this way the interfaces for mass flow between the control volume and the surroundings have been made explicit, thus allowing better structuring of systems containing the control volume.
15.2.5.1 Mass Flow Connector Class In order to introduce mass flow connectors we need a connector class containing the variables that describe interaction at the massflow inlets and outlets of the control volume. Not only mass is flowing, the flowing substance also has some energy content represented by its enthalpy. Moreover, the pressure influences the interactions of the flowing substance at the inlets and outlets. Therefore the following variables need to be included in the interface:
• •
•
Mass flow rate m , represented by the Modelica variable mdot. Specific enthalpy h, a measure of the energy content per mass unit in the substance, represented by the Modelica variable h. Pressure P, represented by the Modelica variable P.
The corresponding connector class for mass flow, called FlowConnector, appears as follows:
Chapter 15 Application Examples 541 connector FlowConnector import Modelica.Slunits.*; Pressure P; SpecificEnthalpy h; flow MassFlowRate mdoti end FlowConnector;
To allow consistent signs at connections we also need the sign convention for flow variables in connector class instances that belong to a model component: •
Sign convention: positiveflow is into a component!
It should be pointed out that this definition of a connector only allows one-directional flows, i.e., the flow may not change its direction during simulation.
at such an interface
15.2.5.2 Basic Control Volume with Mass Flow Connectors and Separate Ideal Gas Model
In order to create a control volume model with mass flow connectors, the new connectors inlet and outlet have been added to the control volume model below together with equations relating the internal variables in the control volume to the interface variables in the new connectors. Note that the sign convention for flow variables in connectors is apparent in the following equation: mdot_out = -outlet.mdot;
The reason for the minus sign is that the flow direction for variables in a connector, e.g. out let, is always into the component to which it is attached, whereas positive values of the variable mdot_out means flow out of the control volume. In order to improve the modularity and re-usability of the model we are also going to separate the equations which are specific to the assumption of ideal gas from the other thermodynamic equations. Easy replacement of the physical property model requires more elaborate schemes, but this separation gives an idea what kind of decisions help in making a model more reusable. This form of the ideal gas model is slightly modified compared to the equations before, because we want to make the model independent from the mass and volume of the control volume. We introduce the specific volume, v:
v
V=-
m
which is used in the ideal gas law in the model below: model IdealGas "Property model for a simple ideal gas" import Modelica.Slunits.*; parameter SpecificlnternalEnergy u_O=209058; II Air at T=293K parameter SpecificHeatCapacity c v = 717; parameter SpecificHeatCapacity R-= 287; parameter Temperature T_O = 293; Pressure P; SpecificVolume v; Temperature T; SpecificlnternalEnergy U; equation u=u_O+c_v*(T-T_O) ; II Linear model for inner energy P*v=R*T; II Equation of state: ideal gas end IdealGas; model BasicVolume "Control Volume with Mass Flow Interfaces" import Modelica.Slunits.*; extends IdealGasl II Added I PlowConnector inlet, outlet; II Added! parameter Mass m_O = 0.00119; Mass m(start=m_O) ;
(15-18)
542 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Volume Vi MassFlowRate rndot_in, mdot_out; h_in, h_out; SpecificEnthalpy SpecificEnthalpy h; Enthalpy H; U(start=u_O*m 0); InternalEnergy HeatFlowRate Qdot; Wdot_e, Wdot_s; Power equation II Interface relations mdot_in • inlet.mdot; II Added I h_in • inlet.h; II Added I P • inlet.P; II Added I mdot_out • -outlet.mdot; II Added I Note the sign convention! h_out • outlet.h; II Added I P outlet.P; II Added 1 h • h_out; II Added I II Conservation of mass der(m)=mdot_in-mdot_outi II Conservation of energy der(U)=h_in*mdot_in-h_out*mdot_out+Qdot-Wdot ei Wdot_e=P*der(V)+Wdot_si H U+P*Vi u U/mi II Specific internal energy (ideal gas) v vIm; II Specific Volume h HIm; II Specific enthalpy end BasicVolurne;
Now we have constructed a bare-bones control volume that contains all the physics which is needed in a simple control volume model, but in doing so we have a model that can not be simulated as it stands, the model is underspecified. This is typical for object-oriented modeling: in order to improve the reusability of a model, some details have to be left open. For testing the above control volume model, we have to specify the volume V, the heat transfer from/to the environment Qdot and the work Wdot_s. If a model is underspecified and three equations are missing, it is common to say that the model has three "degrees of freedom": three additional equations are needed to make the equation system solvable so that the model can be simulated. Unspecified variables in the connectors are treated differently depending on their prefix. Unconnected flow-variables are automatically set to 0, (see Section 5.7.5.3, page 171). This is useful for testing complex flow sheets, because it makes it possible to simulate flow sheets as they are developed when a some connections are still missing. Our test model for the basic control volume model now becomes: model BasicVolurneTest "testing our general volume" extends BasicVolume; equation 1/ Boundary conditions: they are normally defined II by the neighboring models inlet.h = 300190; 1/ Specifying the remaining 3 degrees of freedom V = le-3 + 0.le-3*(if time> 0.5 then time - 0.5 else 0); Qdot = 0.0; Wdot_s = 0.0; end BasicVolumeTest;
We plot the temperature T and the pressure P as functions of time: simulate (BasicVolumeTest, stopTime=lO) plot({T, U}, xrange={O,2})
Chapter 15 Application Examples 543 -T
---u
:::1 270
260 250
------- .. _-.. -....... 0.5
"'-1
Figure 15-14. Plot of the temperature and internalenergy variables of the controlvolumecomponent of the
system. Now we have a reusable, tested, basic control volume. The next step is to create models for the boundary conditions, we call them sources and sinks, and to create models that determine the mass flow between different control volumes, for example a valve or orifice. 15.2.5.3 Pressure Source and Pressure Sink
In this section we introduce pressure source and pressure sink classes with properties such that the PressureEnthalpySource class has constant output pressure and constant specific enthalpy for the flowing substance, and the Pre s sureS ink class specifies constant input pressure. Both of these two kinds of sources and sinks uses the FlowConnector class (see Section 15.2.5.1 on page 540) to specify their interfaces, containing pressure P and specific enthalpy h as "potential" variables, and mass flow rate m as a flow variable. h=h o
&~
PressureEnthalpySource
PressureS ink
Figure IS-15. The PressureEnthalpySource class specifies sources that produce mass flow at constant pressure and specific enthalpy, whereas PressureSink specifies flow sinks at constant pressure.
The Modelica code for the PressureEnthalpySource and PressureSink classes is as follows: model PressureEnthalpySource "Constant pressure and enthalpy source" import Modelica.Slunits.*; FlowConnector outlet;
parameter Pressure parameter SpecificEnthalpy equation outlet.P=P_O; outlet.h=h_O; end PressureEnthalpySource;
P_O=1.0eS; h_O=300190;
model PressureSink "Pressure sink, constant pressure" FlowConnector inlet; parameter Modelica.Slunits.Pressure P_O=l.OeSi equation inlet.P=P 0 end PressureSink;
544 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica 15.2.5.4 Simple Valve Flow Model This first version of the valve model, depicted in Figure 15-16, has just three variables: the input pressure P;n , the output pressure Pout' and the mass flow rate m.
SimpleVaJveFlow Figure 15-16. Very simple valve flow model. The model in its current form is unusable as a model building block since both the input and the output pressure are fixed to constant values in the model. Also, the model does not yet have any connector interfaces. The following constitutive equation relates the pressure difference over the valve to the mass flow:
p. A2 '(~n -Pout) = riz2
(15-19)
where p is a constant, A is the cross section area of the inlet and outlet, P;n is the pressure on the inlet side, Pout is the outlet pressure, and m is the mass flow rate. The Modelica code for the model appears as follows: model SimpleValveFlow import Modelica.Slunits; parameter SIunits.Area A = le-4; parameter Real beta = S.Oe-5; SIunits.Pressure P_in, P_out; SIunits.MassFlowRate rndot; equation II Boundary conditions P_in = 1.2e5; P_out =·1.0e5; II Constitutive relation beta*AA 2*{P_in - P_out) ~ mdot A2; end SimpleValveFlow;
We simulate the model and plot the mass flow m, which is not very exciting since the constant pressure difference gives rise to a constant mass flow. simulate {SimpleValveFlow, stopTime=l); plot{mdot)i
0.0002
0.00015
0.0001 . - - - - - - - - - - - - - - - -
0.00005
t 0.2
0.4
0.6
0.8
1.0
Figure IS-17. Simulation of the very simple valve flow model.
Chapter 15 Application Examples 545
15.2.5.5 Basic Valve Flow Model with Connector Interfaces and Conservation of Mass and Energy
The second version of the valve model extends the simple model with explicit connector interfaces and adds equations for conservation of mass and energy, which represent the fact that there is no mass and energy storage within the valve. This basic valve flow model, depicted in Figure 15-18, is more realistic than the previous version - good enough to be used for simple flow system modeling applications.
ValveFlow Figure 15-18. Complete valve flow model with conservation of mass and energy - in this case no storage of mass and energy within the valve. The equation for conservation of mass with no mass storage within the valve component: (15-20) or expressed in Modelica syntax:
o
=
inlet.mdot + outlet.mdot;
min
m
where represented as inlet. mdot is the flow into the inlet (positive sign) and out represented as outlet. mdot is the flow out of the outlet (negative sign), i.e., it would be positive sign for flow in the opposite direction into the outlet connector. Analogously, the equation for conservation of energy (15-10) combined with the fact that there is no storage of internal energy U within the valve, (dU I dt = 0) , can thus be simplified to the following form: (15-21) or in Modelica syntax:
o
=
inlet.mdot*inlet.h + outlet.mdot*outlet.h;
where we have the same mass flow quantities as in the mass balance equation (15-20), hin represented as inlet. h is the specific enthalpy of the substance flowing into the inlet, and houl represented as ou t 1et . h is the specific enthalpy of the substance flowing out of the outlet. By including flow connectors together with equations (15-20) and (15-21) we obtain a more realistic and configurable valve flow model with connector interfaces and conservation of mass and energy: model ValveFlow import Modelica.Slunits; FlowConnector inlet, outlet; II AddedJ parameter SIunits.Area A le-4; parameter Real beta = 5.0e-5; SIunits.Pressure Pin, Pout; SIunits.MassFlowRate mdot; equation II Interface relations P_in = inlet.PI II Added I P_out = outlet.P; II AddedJ mdot = inlet.mdot; II Added I o inlet.mdot + outlet.mdot; II Added: Conservation of mass (n.o storage) II Conservation of energy (no storage) o inlet.mdot*inlet.h + outlet.mdot*outlet.h; II Added I beta*AA 2*{P in - Pout) = mdot A2; II Constitutive relation assert(P_in-- P_out>O,HError: model not valid for backflow"); II Added! end ValveFlow; I:
I:
546 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica We have also added an assert at the end of the model. This construct is syntactically an equation since it is allowed in an equation section, but does not add any equation to the system of equations to be solved. It is just used to assert certain conditions that must hold for the valid region of operation of the model, i.e., expressing the fact that the model is only valid if P_in-P_out>o which means that the flow direction must be into the inlet and out of the outlet, not in the opposite direction.
15.2.5.6 System and Valve Model with Interfaces and Externally Controlled Flow There is still something missing in our previous valve model from Section 15.2.5.5 above: the ability to control the valve. Without the ability to control the opening in the valve, thus controlling the flow through the valve, it is not very useful. Even the simplest water tap can control its flow. Therefore we introduce an input port u on the valve for a control signal as depicted in Figure 15-19.
u
Pin
Pout
«: ControlledValveFlow Figure 15-19. Valve with controlled flow via an externalinput signal u influencing the cross section area of
the opening. The Modelica code for the ControlledValveFlow model appears below, where we have introduced the u connector for a control signal that influences the cross section area of the opening in the valve and thereby the flow through the valve.
model ControlledValveFlow import Modelica.Slunitsi import Modelica.Blocks.lnterfaces; FlowConnector inlet, outlet; Interfaces.Reallnput UI parameter Modelica.Slunits.Area A = le-4; parameter Real beta = S.Oe-S; SIunits.Pressure P_in, P_out; SIunits.MassFlowRate mdot; equation II Interface relations P_in = inlet.Pi P_out = outlet.Pi mdot = inlet.mdoti II Conservation of mass (no storage) o = inlet.mdot + outlet.mdoti II Conservation of energy (no storage) o = inlet.mdot*inlet.h + outlet.mdot*outlet.h; II Constitutive relation beta*(A*u)A 2*(P_in - P_out) = mdotA2i assert(P_in - P_out>O, "Error: model not valid for end ControlledValveFlowi
II
Added!
II
Added partl
ba~kflqw");
Now we want to make a.small test of our recently developed models of pressure source, pressure sink, and controlled valve components. We put together a test system model called CtrlFlowSystem, consisting of a ctrlFlowModel with an attached pressure source, a pressure sink, and a step signal component producing the control signal.
Chapter 15 Application Examples 547 model CtrlFlowSystem import Modelica.Blocks.Sources; PressureEnthalpySource pressureEnthalpySource(P_O=1.2e5)i Sources.Step step(offset=l,startTime=O.S,height=-O.5); ControlledFlowModel ctrlFlowModel; II Negative step signal PressureSink pressureSinki equation connect (pressureEnthalpySource.outlet, ctrlFlowModel.inlet); connect (ctrlFlowModel.outlet, pressureSink.inlet); connect (step.y, ctrlFlowModel.u) i end CtrlFlowSysterni Using the Mathematica command interface to MathModelica, we simulate the test system and plot the flow through the valve: Simulate (CtrlFlowSystem, {t,O,l}J i PlotSimulation[ctrlFlowModel.mdot[tJ ,{t,O,l},PlotRange->{O,O.00011}J; -
ctrlFlowModel.mdot
o. 00010
...------------,
0.00008 0.00006 0.00004 0.00002
t 0.2
0.4
0.6
0.8
1.0
Figure 15-20. Simulation of a controlled flow valve attached to a step control signal. The simulated and plotted result flow depicted in Figure 15-20 is correct but not very interesting since the flow through the valve is directly proportional to the input step signal. This version of the valve flow model with external control is used in the pneumatic cylinder system with external valve control described in the next section.
15.2.5.7 Reusing the Control Volume Model in a Pneumatic Cylinder In the previous section we added external interfaces for mass flow interaction between the control volume and t.he surroundings. However, there are other possible interactions between the control volume and external components: • •
The piston at the top of the control volume can move up or down, i.e., use a translational connector. A rotating shaft with an attached rotor can rotate, i.e., use a rotational connector.
Since both the translational and rotational movements usually are performed against some force or torque, work is done and energy is transferred into or out of the control volume. In this example we only look at translational movement.
548 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica mass flow connectors piston with translational connector ::::::::::::::::::.:.~:::
:::::::::::::::::::::~:::
::::::::::::::::.:.:
....:::
.•.
::::::::!!.::::::.:.:-.:.:: :::::::::::::::.:.: :::
F 1-----
:.'::::::::::::::::::~:::
Figure IS-21. The control volume with three external interfaces: two mass flow connectors and one mechanical translational.connector to the piston. Regarding the translational movement of the piston as a consequence of changing volume, we add -an equation for the volume in the control volume model and add an equation for the translation force transmitted to the piston:
V = Vo + A · Strans
c: =-(P-Po)·A
(15-22)
where V is the volume of the control volume, Vo is the initial volume, A is the area of the piston, P is the pressure inside the cylinder, Po is the pressure in the environment, S trans is the vertical translational movement and Jtrans is the force on the piston. The corresponding equations in Modelica syntax appear as follows:
v = v_a
+ A*flange_trans.s; (P - P_O)*A = flange_trans.f;
where Strans is represented by flange_trans. s, which is the position variable in the flange_trans connector of type Translational. Interfaces. Flange_a from the Modelica .Mechanics library, and Jtrans is represented by the force flange_trans. f in the same connector. The cylinder volume model that inherits from the previously developed BasicVolume model with these additions included appears as follows: model PneumaticCylinderVolume "a simple model of a pneumatic cylinder" import Modelica.SIunits.*; import Modelica.Mechanics.Translational; II Modified states P and T extends BasicVolume(P(stateSelect=StateSelect.prefer, start=P_O), T(stateSelect=StateSelect.prefer, start=T_O»; Translational.lnterfaces.Flange a flange trans; parameter Area A =le-2 "cylinder cross section area"; parameter Volume V_O=le-3 "cylinder volume in home position"; parameter Pressure P_O=1.0eS "environment pressure"; equation V V_O + A*flange_trans.s; (P - P_O)*A -flange_trans.f; II No dissipative work here Wdot s 0.0; II No heat flow Qdot 0.0; end PneumaticCylinderVolume; Most of the additions to the model are straightforward: the volume is now variable and depends on the piston position, the force in the piston rod is related to the pressure difference inside and outside the cylinder (we use absolute pressures inside the volume), and we neglect dissipative work and heat loss. Note the modification to the basic control volume: for the pneumatic cylinder it is more natural to have the pressure and temperature as initial conditions and dynamic states. This is achieved via the modification P (stateSelect=StateSelect . prefer, start=P_0) - see Section 18.2.6, page 686, concerning StateSelect, and the equivalent modification for T.
Chapter 15 Application Examples 549
15.2.5.8 System with a Pneumatic Cylinder - Combined Thermodynamic and Mechanical System, Extracting Mechanical Work from the Control Volume The cylinder volume model with three connector interfaces-one mechanical and two mass flow connectors-that was defined in the previous section can now be connected to external components to create a pneumatic cylinder system, as depicted in Figure 15-22.
step
inSource
--. --.
controlValve
P ::
Gas
_---m--&iWV'iHl
-. -.
fixed
outSink
Figure 15-22. A pneumatic cylinder system consisting of a gas filled cylinder doing work on the spring/damper by pushing against a piston. The air comes from a high-pressure reservoir and is released to lower pressure through the controlled valve.
The corresponding Modelica code for the pneumatic cylinder system appears as follows: model PneumaticCylinderSystem "System to test the pneumatic cylinder model" import Modelica.Slunits.*i import Modelica.Mechanics.Translationali import Modelica.Blocks.Sources; PneumaticCylinderVolume cylinder(V_O=le-2,P_O=2.0eS, T_O=340.0)j PressureSink outSink(P O=1.0eS)i ValveFlow outValve(A=le-2); PressureEnthalpySource inSource(P_O=3.0eS); Translational.Fixed fixed(sO=1.0) i Translational.SlidingMass pistonMass(L=O.l, s(stateSelect=StateSelect.always, start=1.55» Translational.SpringDamper springDamper(d=500, s_relO=O.5, c=5000.0} i ControlledValveFlow controlValve(A=le-2)i Sources.NStep step(offset=l, startTime=5,height=-O.99); equation connect (outValve.outlet, outSink.inlet)j connect (cylinder.outlet, outValve.inlet); connect (cylinder. flange_trans, pistonMass.flange~b); connect (pistonMass.flange_a, springDamper.flange_b); connect(springDamper.flange a, fixed.flange_b); connect (inSource.outlet, controlValve.inlet); connect (controlValve.outlet, cylinder. inlet) ; connect (step.y, controlValve.u); end PneumaticCylinderSystem;
i
The composition of a translational mechanical model, the piston, that by itself requires two states to model its dynamic behavior, position and velocity, and a variable-volume control volume that requires three states, in this example pressure, temperature and volume, poses numerical problems unless index reduction is performed on the model and the right states are chosen for the numerical integration, see Section 18.2.3,
550 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica page 675, concerning the notion of index and index reduction. The volume of the control volume depends on the piston position (pistonMass. s) and therefore one of the two states (volume and position) depends on the other one. This is the reason for the s (stateSelect = StateSelect. always, start=l. 55) modification of the piston mass. All other modifications in the model are to set the parameters and start values to reasonable values for a pneumatic cylinder.
simulate (PneumaticCylinderSystem, stopTime=15)i plot (pistonMass.s) ; plot (cylinder.Wdot_e) ; plot(cylinder.p);
1.55 1.5
;--4-!"i78--io--i2--14-
\\
-so -100
1.45
1.35
-150
"
-200
8
10
12
14
"-------------
-250
II ~
t
200000 180000
\
160000
\
140000 120000
2
4
\
6
8
10
12
14
Figure 15-23. Simulation of a pneumatic cylinder system with a controlled flow valve attached to a step control signal.
15.2.6 System with Dissipation and Heat Sources-A Room with Heat- and Mass Transfer to the Environment Now we are ready for the second extension to our basic control volume-transfonning it into a room with convective heat transfer to the environment. We are also going to look at the effect of dissipative shaft work, including mechanical work done by a rotating shaft, i.e., shaft work Ws • In our case the work is dissipated and ultimately transformed into heat. When the work is not dissipated, the shaft work represents a "turbine" system for the case when the control volume fluid or gas causes the shaft to tum and perform work, i.e., W s > 0, or might be a "compressor" when the rotating shaft causes the rotor wheel to turn and move the gas, i.e., Ws < 0 .
o c===Ie=======~ o Figure 15-24. A rotor wheel attached to a rotating shaft. In our room example, the work of the fan accelerates the air, but the air dissipates the kinetic energy via turbulence to heat. The model is simplified and directly transforms the electric input power to the fan into heat. The cooling effect of the fan comes not from the temperature, which is actually increased slightly by the fan, but through increased evaporative cooling due to higher air speed.
The energy transfer aspect of the fan out of or into the control volume through the shaft work done by the rotating fan wheel, has already been taken into account in the control volume model previously described in Section 15.2.5.2, page 541 with the shaft work variable Wdot_s. The complete system of the room including the fan is depicted in Figure 15-25 below:
Chapter 15 Application Examples 551
Wall
~ .
~
. '
~.
R.oomWlthFtiD .'.'. .......:. ·i···;····\'.':'.>'.:
PressureEnthalpySource windwardSide
4(J()i(~liti~)i .
~ ~
~ FixedT
Convection PressureSink, downwindSide
Figure 15-25. House with fan, air flow input through window, and air outflow through door. The room air is also in thermal contact with the wall, which in tum is in contact with the environment. The pressure at the window and the door can be different depending on the wind direction. The Modelica code for the modified control volume, the RoomWithFan model, appears below. New parameters are introduced to compute the room volume and switch on and off the heating loads, e.g. a computer, and the fan. The model is also prepared for thermal interaction with its environment using a connector from the Modelica. Thermal library. This connector is for purely thermal interaction between components without a convective mass flow and is defined as: connector HeatPort "Thermal port for I-dim. heat transfer" import Modelica.S1units; SIunits.Temperature T "Port temperature"; flow SIunits.HeatFlowRate Q_dot "Heat flow rate (positive if flowing n + "from outside into the component)"; end HeatPort;
Using this connector, we can model interaction between the room air, the room wall and the environment. Because the time constants of temperature changes in buildings are very slow, we introduce a new time variable to observe time in hours. With this model we could investigate how many hours it takes to cool down the room to almost environment temperature. We also introduce variables for the time when we switch on heat loads or the fan. The connectors in the original model are now reused for the air leakage through the window and the door. model RoomWithFan "Simple room model, built on top of BasicVolume" import S1=Modelica.Slunits; extends BasicVolume(p{stateSelect=StateSelect.prefer, start=1.0eS), T(stateSelect=StateSelect.prefer, start=T_O»; HeatPort heatPort "heat interaction with environment"; parameter 51.Power maxHeatLoad = 400.0 "max power value of heat sources"; parameter SI.Power fanPower 200 "power of fan in Watts"; parameter Real etaFan 0.75 "fan efficiency"; parameter SI.Length length 5.0 "room length"; parameter S1.Length width 4.0 "room width"; parameter SI.Length height 2.5 "room height"; parameter SI.Time fanOn 3600.0 "time when fan is switched on"; parameter S1.Time heatOn 7200.0 "time heat source is turned on"; Boolean heatPowerOn "on/off flag for heat load"; Boolean fanPowerOn "on/off flag for fan"; S1.Conversions.NonSlunits.Time hour time hour "time measured in hours"; equation - -
552 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica heatPort.T = T; time_hour = SI.Conversions.to_hour(time) ; V = length*width*height; heatPowerOn = if time > heatOn then true else false; fanPowerOn = if time > fanOn then true else false; Qdot = (if heatPowerOn then maxHeatLoad else 0.0) + (if fanPowerOn then (l-etaFan)*fanPower else 0.0) + heatPort.Q_dot; Wdot_s = if fanPowerOn then -etaFan*fanPower else 0.0; end RoomWithFani Now we have a modified control volume, but we are lacking models for the heat capacity of the wall, and the convective heat transfer from the room air to the wall and from the wall to the environment. All the models we need in this case are already available in the Modelica. Thermal library. It is always useful to have an idea about the magnitudes of the model parameters that determine the dynamic model behavior. In the case of our room model e.g., it is helpful to know where most of the heat is stored. An approximate computation reveals the heat capacity for the air in the room is:
C=VPCv
J
~50xl.2x717=43020-
K
(15-23)
Assuming that the room wall consists of brick stone and the floor is concrete, both with heat capacities of c ~ 2000 , and we estimate the total weight of the brick wall and floor that are thermally connected to the room at approx. 1000 kg, we realize the heat capacity of the air is only around 2 % of the total heat capacity. This clearly indicates that we can not hope to capture the thermal behavior of the room without adding a simple model of the wall heat capacity. The model in the the Modelica. Thermal library is a simple, lumped model of a heat capacity: (15-24) where the summation of the heat flows is accomplished automatically via the flow semantics, see equation (14-52), page 489, and the sum-to-zero flow summation rule for flows described in Section 5.3.1, page 148. In this case the heat capacity C is a property of a solid body and computed as:
C=m·c
(15-25)
with the mass m and the specific heat capacity c. Another simple thermal model that we need is for the convective heat transfer. It establishes a linear relation between the temperature gradient between a solid body and a fluid, and the heat flow Qdot : (15-26)
The thermal conductance G, is determined via an external signal and can be set to a constant or derived form a detailed heat transfer model. The main remaining task is to compose the system model from our new room model and to determine the coefficients in the components correctly. This is not an easy task for real buildings, because it is often difficult to get reliable values for the mass and specific heat capacity of the materials in the wall. Heat transfer coefficients are also difficult to determine. The external heat transfer coefficient vary substantially depending on the wind conditions. We are going to use estimates which are roughly at the right order of magnitude-values also vary a great deal in reality. model RoomlnEnvironment "Room in environment, pressure-driven air flows" import Modelica.Thermal.HeatTransfer; RoomWithFan room(P(start=1.022eS)); ValveFlow window (A=le-3, beta=O.5); ValveFlow door (A=le-3, beta=O.S); PressureSink downwindSide(P_O=O.99Se5); PressureEnthalpySource windwardSide(P_O=1.OSe5, h_O=3.102eS);
Chapter 15 Application Examples 553
room_wall; HeatTransfer.Convection wall(T(start=290.0),C=2.5e3*eOO.O) ; HeatCapacitor wall_env; HeatTransfer.Convection T env(T=310) ; HeatTransfer.FixedTemperature Modelica.Blocks.Sources.Constant k=inner(k={30}) ; Modelica.Blocks.Sources.Constant k_outer(k={300}) ; equation downwindSide.inlet); connect (window.outlet, room. outlet) ; connect (window. inlet, connect (door.outlet, room. inlet; connect (windwardSide.outlet, door. inlet) ; room.heatPort); connect(room_wall.solid, wall.port) ; connect (room_wall.fluid, connect (wall_env.solid, wall.port) ; connect (k_outer.y, wall_env.G) ; room_wall.G) ; connect (k_inner.y, T_env.port} ; connect (wall_env. fluid, end RoomlnEnvironmenti We can now perform a number of simulation experiments with this model and look at the system variables. In order to get a realistic feeling for the speed of the processes, we chose hours as the units of time for plotting. With the given initial conditions, we can first expect the room temperature to approach the environment temperature of 310 K. Even after five hours, the equilibrium temperature i3 not yet reached. We can also see that the fan with 200 W of power causes about half of the temperature rise in the room as the heating load of 400 W. The dissipated mechanical power and the direct addition of heat have the same result on the system temperature.
simulate(RoomlnEnvironment,stopTime=14); plot (room.T, xrange={O,14}); plot(room.P, xrange={9,12}); 293.175 293.15
102258
293.125
102256
293.1
102254
293.075 293.05
102252
293.025
102250
~..--.-..............~-----...o-~............................................--~~---t
2
4
6
8
10
12
14
t
-+----,....~----------_._-
9.5
10
10.5
11
11.5
12
Figure 15-26. Simulation of a room in a house with fan, air flow input through window, air outflow through door, and convection through wall. Plot of temperature (left) and pressure (right)
Another observation from the pressure plot is that the pressure disturbances are very small. The temperature gradients cause the pressure to rise for a short time, but then the pressure flows of to the environment and the pressure always returns to the equilibrium pressure of ~ 1.02208 bar. To get more of a feeling for this system, the reader is encouraged to plot additional variables and experiment a bit with the model.
15.3 Chemical Reactions We have previously presented simple thermodynamic systems (Section 14.7 and Section 15.2), governed by mass balance and energy balance equations. In such systems the amount of matter in each species is preserved even though phase transitions may occur.
554 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica However, when dealing with chemical reactions, molecules of one species of matter may react with the molecules of a second species, thus forming a third species i.e., a different substance. This has a number of implications for the behavior of systems including chemical reactions. Traditionally, the literature of chemical reaction dynamics has been divided into two main areas (not mentioning the large number of different application areas in chemistry): • •
Chemical reaction kinetics. Chemical thermodynamics.
Chemical reaction kinetics traditionally deals with substance concentrations and their time derivatives. It typically ignores energy conservation, even though internal microscopic energy i.e., chemical potential usually has a large influence on the probability of a reaction to occur. On the other hand, the literature on chemical thermodynamics concentrates on the energy balance in chemical reactions, but usually covers only equilibrium thermodynamics and ignores dynamic behavior. In this short example of modeling chemical reactions using ModeIica, we will focus on the chemical reaction kinetics and ignore energy conservation. However, in large realistic models, especially when chemical reactions interact with other modeled phenomena, it is usually necessary to include energyrelated terms.
15.3.1 Chemical Reaction Kinetics of Hydrogen Iodine The dynamics of a chemical reaction are a roughly governed by three factors: • • •
Mass balance Reactant concentration Energy conservation
As stated in the previous section, in the following we will just deal with chemical reaction kinetics and ignore energy conservation. First we will focus on conservation of mass, and later on the effects of concentrations. A chemical reaction represented by a reaction formula transforms the chemical species on the left-hand side of the arrow, called reactants, to the species on the right-hand side of the arrow, called products: reactants ~ products
(15-27)
Consider a chemical reaction between hydrogen gas and iodine gas to form hydrogen iodine: (15-28) The double-sided arrow indicates the presence of reactions in both directions, which can be written as two separate reaction formulas:
H 2 +1 2 -s zm 2HI~"2
(15-29)
+1 2
The first reaction states that one molecule of hydrogen together with one molecule of iodine can react. In this reaction the atoms may regroup to form two molecules of hydrogen iodine. The second reaction is the reverse: two molecules of hydrogen iodine are transformed to one molecule of hydrogen and one molecule of iodine. In both reactions the mass balance is preserved. The number of atoms of each type on both sides of the arrow is the same. An integer number of molecules is involved in the reaction since no fractional molecules exist. The second issue concerns how frequently a reaction occurs on the microscopic level. In order for a reaction to take place, all involved molecules must be at the same place at the same time. The probability
Chapter 15 Application Examples 555 of a molecule of a certain species being in a small volume of space is proportional to the concentration of the species. Thus, assuming statistical independence, the probability of all involved molecules being in the same small volume at the same time is proportional to the productof their concentrations. Thus, for the reaction between hydrogen gas and iodine gas, the reaction rate is as follows: (15-30) where the notation [H2] and [12 ]denotes the respective concentrations of hydrogen and iodine molecules, and k1 is the reaction rate proportionality constant. Analogously, the reaction rate for the reverse reaction of two molecules of HI is given by (15-31) below: (15-31) The reaction rate proportionality constant is often written above the arrow of the reaction it represents, as in (15-32) and (15-33): kl
(15-32)
H 2+1 2--t2ID k2
2HI~"2
(15-33)
+ 12
Putting the reaction rate expressions in (15-30) and (15-31) together, we can formulate the differential equations for the whole reaction system:
(15-34)
Note that the reaction rates are influenced only by the concentrations of reactants in each reaction, not by the products. Concerning the first equation, the production rate of H2 from HI is given by k 2 • [HIf according to (15-31), whereas the consumption rate of to ill in the reverse reaction is k, . [H2 ]. [1 2 ] according to (15-30). The second equationis almost identical, based on the same reasoning. The third equation gives the rate of forming HI from H, and 12• The term 'Ik, .[H2 [1 2 ] includes a factor of two since a pair of molecules "2 and 12 gives rise to two molecules of HI. Analogous reasoning applies to the second term. We finally put the three reaction rate equations from (15-34) into a Modelica class to prepare for simulation (Figure 15-27).
"2
1
type Concentration = Real(final quantity = "Concentration", final unit = "mol/m3"); class Hydrogenlodide parameter Real kl = 0.73; parameter Real k2 = 0.04; Concentration H2(start=5); Concentration 12 (start=8) ; Concentration HI (start=O) ; equation der{H2) k2*HI A 2 - kl*H2*I2; A2 der(I2) k2*HI - kl*H2*I2; der(HI) 2*kl*H2*I2 - 2*k2*HI A 2 ; end Hydrogenlodide;
We simulate for 100 seconds and plot the results.
556 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica simulate (Hydrogenlodide, stopTime=100) plot{{H2, 12, HI}, xrange={O,s})
___- - - - - - - - - - - - H I
8
6 4
------------- I
2
2
- - - - - - - - - - - - - H2 1
2
3
time 4
5
Figure 15-27. Concentrations of hydrogen, iodine, and hydrogen iodine based on the chemical reaction between the involved reactants. It is easy to observe that after an initial transition phase, a steady-state condition is reached when the concentrations are constant. In steady-state all derivatives are zero. We substitute zero for the derivative in the first equation of (15-34), obtaining: (15-35) After a slight rearrangement:
[mf
k1 . [ ] = - = constant ["2 ] 12 k2
(15-36)
Thus, the relation between the concentrations in steady-state is constant, irrespective of the initial concentrations.
15.4 Biological and Ecological Systems In this section we will present a few examples of models of biological and ecological systems. As we previously stated in the section on deductive versus inductive modeling (Section 12.1.1, page 382), biological systems are usually quite complex. Normally little exact knowledge is available about such systems, which would be needed for detailed physical modeling. This forces researchers to use inductive models based on experimental observations rather than physical intuition of system dynamics, which has the disadvantage that the models are difficult to validate for predictions outside the observed range. A combined approach is possible, where some approximate physical knowledge is combined with adapting model coefficients based on experimental observations. Such an approach will be explored in the subsequent models where we will investigate a continuous-time model for population dynamics and a discrete-time cyclic growth model for the energy forest.
15.4.1 Population Dynamics In this example we will study the dynamics of populations of animals in an idealized ecological system. We assume that a population contains P individuals. In general, the change rate of the number of animals in a population is the difference between the population growth rate and its death rate:
P=growthrate-deathrate
(15-37)
Chapter 15 Application Examples 557 where P is the rate of change of the number of individuals in the population. It is natural to assume that the growth rate and the death rate are proportional to the size of the current population:
growthrate = g . P
(15-38)
deathrate =d . P
where g is the growth factor and d the death factor for the population. These factors can be assumed to be constant if the same amount of food per individual is available independent of the size of the population, and no sudden lethal illnesses affect the population. These assumptions are of course valid only for a reasonable size of the population, since the food supply is never infinite in a closed system and illnesses sometimes occur. Putting (15-37) and (15-38) together gives: (15-39)
P=(g-d)·P
Solutions to this equation give an exponentially increasing population if (g - d) > 0 or exponentially decreasing if (g -d) < We represent this equation in the model class PopulationGrowth below:
o.
class PopulationGrowth "Growth factor of population"; parameter Real 9 = 0.04 parameter Real d = 0.0005 "Death factor of population"; Real P(start=10) "Population size, initially 10"; equation dar (P) (g-d) *P; end PopulationGrowth; The model is simulated and the population size P plotted:
simulate (PopulationGrowth, stopTime=100) plot(P) -- p
500 400 300 200 100 t
---J--.-_ _--'-~~--'-----~----"--~-o--I_~__'__
20
40
60
80
100
Figure 15-28. Exponential growth of a population with unlimited food supply.
As expected, Figure 15-28 shows an exponentionally increasing population. We should, however, remember that exponential growth can never persist indefinitely in a closed system with a limited food supply.
15.4.1.1 A Predator-Prey Model with Foxes and Rabbits Now we would like to study a more interesting system consisting of two interacting populations of predators and prey animals. The simplest model of this kind is the so-called Lotka-Volterra model. In this case, the predators are foxes and the prey animals are rabbits. The rabbit population of size R is assumed to have an unlimited food supply. Therefore equation (15-39) applies regarding the birth-related growth rate of the rabbit population, giving a positive growth term gr' R , where g r is the growth factor for rabbits. On the other hand, the fox population of size F feeds on the rabbits. The rate of rabbit deaths can be assumed to be proportional to the number of foxes due to increased hunting pressure, and to the number of rabbits due to the higher probability of success in hunting, giving a rabbit death rate due to foxes of
558 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
d if F . R , where d if is the death factor of rabbit~ due to foxes. Putting the growth and death rates together gives the total rabbit population change rate R as defined by equation (15-40) below: 0
(15-40)
R=g,.R-dif·FoR
. The growth of the fox population of size F is proportional to the rate of rabbits consumed, i.e., those that die because they were hunted by foxes--which is the death rate term d if · F · R mentioned in the previous equation. The efficiency of growing foxes from rabbits is determined by the growth factor g fr ' giving a fox population growth rate term g fr · d rf . R · F . The fox population also has an intrinsic death rate d f . F proportional to the size of the fox population by the fox death factor d f . By combining these two terms we obtain equation (15-41): (15-41) where F is the total change rate of the fox population. We have made a Modelica class below called LotkaVolterra, which includes both equations (15-40) and (15-41), together with all variables and constant proportionality factors. The two state variables Rand F for the sizes of the rabbit and fox populations respectively are represented by the Modelica variables rabbits and foxes:
class LotkaVolterra parameter Real g_r =0.04 "Natural growth rate for rabbits"; parameter Real d_rf=O.OOOS "Death rate of rabbits due to foxes"; parameter Real d_f =0.09 "Natural deathrate for foxes"; parameter Real g_fr=O.l "Efficency in growing faxes from rabbits"; Real rabbits (start=700) "Rabbits, (R) with start population 700"; "Faxes, (F) with start population 10"; Real foxes (start=10) equation der(rabbits) = g_r*rabbits - d_rf*rabbits*foxes; der(foxes) = g_fr*d_rf*rabbits*foxes - d_f*foxes; end LotkaVolterra; The model is simulated and the sizes of the rabbit and fox populations as a function of time are plotted in Figure 15-29:
simulate (LotkaVolterra, stopTime=3000); plot ({rabbits, faxes}, xrange={0,1000}); -
rabbits
-_. foxes 5000
4000
_._.&_.__ K.__~..._.K._...K..__K-._...c.../\~' ~____ 200
400
600
800
Figure 15-29. Number rabbits--prey animals, and foxes-predators, as a function of time simulated from the PredatorPrey model. The Lotka-Volterra model has a rather special property: the solution variables, i.e., the rabbit and fox population sizes, do not approach steady-state values as time goes by. Instead, they approach periodic
Chapter 15 Application Examples 559 steady-state values-the solution oscillates. The shape of the oscillation is very characteristic for LotkaVolterra models and corresponds rather well to several experimental population studies of predators and prey animals. However, this does not prove our partly inductive model equations to be correct, only that they seem to have certain approximate physical significance.
15.4.2 An Energy Forest Annual Growth Model for Willow Trees An energy forest is another example of an ecological system for which it is interesting to study growth and mortality. In particular, in the case of energy forest models we would like to simulate and predict the biomass output of the system depending on solar radiation and other growth factors. In the example to be described shortly we will study a small willow (Salix spp.) forest. Research on such forests as a renewable energy source has been conducted in Sweden since the 1970s. Traditionally, purely inductive statistically based models have been used to make predictions of forest productivity. Such models are problematic since they are site and condition specific, and usually cannot be used at new sites or under new conditions. The modeling style used for this example is partly an inductive modeling approach based on experimental observations of factors for growth, mortality, radiation absorption, etc., and partly deductive physical modeling based on approximate physical relations for transformation of energy from solar radiation to stored chemical energy in terms of biomass in the willow forest. This requires fewer and more easily assembled input data than in the statistical approach, but still represents the interaction between environmental factors and forest growth in a realistic way. The simple basis for the willow forest growth model to be described shortly is an assumed linear relationshi p between the solar radiation absorbed by the forest and the produced biomass: (15-42)
w v e -a-R
where w is the biomass produced by the willow forest, e is the efficiency with which the forest uses the absorbed radiation to grow wood, a is the fraction of the solar radiation absorbed by the forest, and R is the incoming solar radiation.
15.4.2.1 Model Description The productivity of a forest of willow can be fairly well described by a discrete-time model in Modelica, with a time resolution of one year. This is a more realistic model than would be a continuous-time one since growth primarily occurs periodically during the summer season of the year, and not continuously all the time. The model includes the following aspects: • • • •
Annual growth proportional to the incoming solar radiation. Constant annual mortality fraction as well as additional mortality caused by fungi certain year(s). Radiation use efficiency and absorption factors depending on the willow shoot age. Periodic harvesting.
First we formulate the difference equations that are the basis for the model, and later the Modelica model including these equations. The annual increment in stem biomass for a willow forest equals the difference between the growth and the removal of biomass:
w, -
w
'-1
= WGrow,h t
_
w Mort t
_ wHarves' ,
(15-43)
where w, is the standing living stem biomass at the end of the year, t denotes the current year, and t-l the previous year. The increase in biomass is the annual stem growth (w~rOWlh) and the removal of biomass is the annual stem mortality ( W,Mort ) combined with the stem biomass removed by harvest (w,Harvest ).
560 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica We also need to consider the time (in years) from when the willow shoots appear until they are harvested. The cyclic shoot age (c) in years is the age of the shoots that appeared at the plantation or after the most recent harvest: c = 1,2,
(15-44)
1,2,3,4, 1,2,3,4, ...
Harvest occurs at the end of a growth cycle, i.e., two years after plantation or after each four-year growth period starting at the most recent harvest. The shoot age is increasing until harvest, after which new shoots appear. In our model the time condition for harvest is expressed as follows:
(15-45)
c=landt>1
Which, strictly speaking, indicates the immediate beginning of the next growth cycle except the first. However, the time difference between the end of the previous cycle and the immediate beginning of the next cycle is essentially zero, which makes it possible to use this condition formulation as the time condition for harvest. As mentioned previously, the annual stem growth (W~rowth) of the willow forest is proportional to the fraction of global radiation (R:bsorb ) absorbed by the leaves during a growth season and the efficiency by which this energy is used: Growth
Wt
=Ec . RcAbsorb
(15-46)
where Ec ' which is dependent on the cyclic shoot age c, is the efficiency with which the willow forest utilizes the absorbed radiation in production of new wood. The efficiency decreases somewhat as the shoots grow older. The fraction (a c ) of the solar radiation absorbed by the leaves is also dependent on the shoot age c. As the shoots grow older they are able to absorb a slightly larger fraction of the incoming radiation. RAbsorb c
=a
c
· Rt
(15-47)
Every year a mortality fraction (m ,) of the forest dies (w~ort ) due to a certain level of shoot mortality. The shoots that die make the willow forest less dense. w
Mort
-
I
-
{m t • (1- h)· (wt _ 1 + w~rOWlh) ,c = 1and t> 1 mI . (wI-I + wGroWlh) I
,
(15-48)
otherwise
Remember that the cyclic shoot age c is defined in relation to the most recent harvest, except before the first harvest when the shoot age is defined in relation to the plantation year. The harvest usually takes place every fourth year. A fraction (h) of the standing stem biomass w t _ 1 at the end of the previous year, along with the dead biomass ( Wt~rrtAcc ) accumulated since last harvest, is then removed from the system: Harvest
W
I
={h0
• w,_1
MortAcc + w,_ 1
, c = 1 and t> 1
(15-49)
, otherwise
where dead wood has been accumulating until it is harvested: MortAcc
w,
={
wIMOrl WMortAcc I-I
, C
+w
Mort t
= 1 and t > 1
(15-50)
,otherwise
The WillowForest Modelica model embodying all these equations appears below:
class WillowForest parameter Real h = 0.95 "Harvest fraction"; parameter Real [4] e = {.73, .80, .66,.55} "Radiation efficiency fraction";
Chapter 15 Application Examples 561
parameter Real [4] a = {.59, .73, .76, .74} "Intercepted radiation fract.ion"; parameter Integer [10] growthCycles = {1,2,1,2,3,4,1,2,3,4}; parameter Integer[lO] r = {2097, 2328, 1942, 2359, 2493, 2290, 2008, 2356, 2323, 2540} "Solar radiation(MJ/m2 ) 1985-1994"; parameter Real [10] m = {.1, .1, .5, .1, .1, "Mortality fraction 1985-1994"; .1, .1, .1, .1, .1} parameter Integer[10] mbiomasses = {786, 1091, 539, 980, 1139, 589, 723, 1457, 1004, 845} "Measured biomass 1985-1994"; Integer t (start = 0) "Years since the forest was planted"; "Year in growth cycle"; Integer c "Total standing biomass in forest (g/m 2 ) ,, ; Real w(start = 60) Real wGrowth, wMort, wHarvest "Biomass for growth, mortality and harvest"; Real wMortAcc (start = 0) "Accumulated dead biomass by mortality"; Real wBiomass "Biomass produced during a year"; "Measured biomass for current year"; Integer mbiomass equation when sample(O, 1) then t = pre(t)+l; mbiomass = mbiomasses[t]; II Harvest first time after two years, then every fourth year c = growthCycles[t]; w = pre(w) + (wGrowth - wMort - wHarvest); wBiomass = wGrowth - wMort; wGrowth = e[c] * arc] * r[t]; II A fraction m of the forest dies every year wMort = if (c == 1 and t > 1) then (I-h) * met] * (pre(w) + wGrowth) else met] * (pre(w) + wGrowth); II A fraction of the forest is removed at harvest wHarvest
= if (c == 1 and
t > 1) then h*pre(w) + pre(wMortAcc) else 0; II Dead biomass accumulates by mortality wMortAcc if(c == 1 and t > 1) then wMort else pre(wMortAcc) + wMort; end when; end WillowForest;
15.4.2.2 Model Application and Simulation The model was calibrated against measured annual data on living stem biomass of Modellskogen, located in Uppsala, Sweden. The data used in the simulation cover the period 1985-1994 (plantation year 1984) and include three harvests (Table 15-1a). Since the forest was not cut back during the plantation year the biomass value given for 1985 also includes the biomass produced during 1984. Biomass at plantation was 60 g/m2 • The measured fraction of global radiation absorbed by the forest (a), the radiation use efficiency (8) and the different mortality and harvest factors used in the simulation are shown in Table IS-lb. The mortality fraction (m) is in a normal year 0.10, but in 1987 the forest was infected by fungus and there was a calibrated extra mortality fraction of 0.40. Beginning at the end of 1986, a fraction h (90%) of the forest was harvested every fourth year.
562 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica Table IS-I. (a) Annual values for shoot age, incoming solar radiation, and stem biomass for Modellskogen forest. (b) Model inputs for the simulation of Modellskogen forest productivity. Year
Shoot
1985 1986
1a
1987 1988 1989 1990 1991 1992 1993 1994
Solar Radiation 2 (MJ/m )
Stem Biomass
2097 2328
846' 1091
2
1942 2359 2493 2290
539 980 1139 589
Ie lie
2008 2356 2323 2540
123 1451
Age 1
n' 12
112 111 IV2
f'
IV)
• The yearafterplantatioll
Parameter
(g m·2)
Value
Unit
0.13 0.80 0.66
Gd. w. MJ·1 Gd.w.Mr l Gd.w.Mj"1 Gd.w.MJ '
Radiation useefficiency s; tAle = 1 e; tAle = 2 e; tAle = 3 E; tAse =4
0.55
Intercepted radiation a; tAle =I a; tAle = 2 a; tAle =3 a; tAli = 4
1004 845
0.59 0.73 0.16 0.14
'.2.' First,secondand thirdcuttingcycle.
The WillowForest model was simulated and certain results were plotted as depicted in Figure 15-30, using the Mathernatica command interface to MathModelica: Simulate [WillowForest, {t,O,9.99}1 PlotSimulation[{w[tl , wGrowth[tl },{t,O, 9.99}1 PlotSimulation({w[tl,wHarvest[t), wMortAcc[tl},{t,O, 9.99}1 PlotSimulation[{wBiomass[t],mbiomass[tl},{t,O,9.99},AxesOrigin->{O,O}] -w(t) ·--wHarv(t) 4000 ortAcc (t)
-w[tJ
-- wGrowth (t)
-wBiomaest - biomasst
~:~ r l==1~J1J=l'-'--- -LtJ
3000 2500 2000 1500
rlo I
1000 5001
I
~-::::-J=t-~~",--,--
3000
,·-·L., I I
: : 1m 1
.......a.-_~_ _~----......-&.... 10
rU
--
__.1"-- ._
- ---_.-.
2
_..J
_.J---
__..
6
-
400
I
__.J _.-......-._-4
800 --.-
600
8
1---1
t.__.L-10
200
t
+---------'------t 10
Figure IS-30. (a) The total biomass and the annual increase in biomass plotted against time. (b) The total biomass, harvested biomass, and the annual accumulation of dead biomass plotted against time. (c) The annual net production of biomass and annual measured biomass plotted against time.
Figure 15-30c shows a fairly good correspondence between the biomass production computed by the simulation and actual measured values. In Figure 15-30a can we observe the effects of accumulation of biomass due to growth, effects of harvesting, as well as the fact that biomass growth seems to be highest the year directly after a harvest event.
15.5 Economic Systems Economic systems are abstractions of physical systems with human beings where only so-called economic aspects are studied, e.g. money flow, monetary value, production, consumption, etc. Complete economic systems are intrinsically quite complex, especially since they to a large extent depend on human behavior. On the other hand, since exact knowledge about the mechanisms in such systems is hard to obtain, many simplifying assumptions are usually made, resulting in very simple models. Such models can never be more than approximately valid and therefore have limited prediction power. However, it is not uncommon that simple economic models are used for predictions outside their area of validity. The subject area denoted national economy deals with the economic behavior of nations. Models of national economies often include variables such as GNP (Gross National Product), the total consumption of a nation, the total investments, and the government expenses of the nation. In particular, according to the simple Keynesian multiplier-accelerator model, the following approximate relation holds:
Chapter 15 Application Examples 563
GNP, = consumption,
+investments, + expenses,
(15-51)
where t denotes the current year. We also assume that the consumption for the current year (t) is proportional to the GNP for the previous year (t-l):
consumption,
=a . GNP,_I
(15-52)
Moreover, the investments of the current year are assumed to be proportional to the increase in consumption compared to the previous year:
investments,
=b
(consumption, - consumption.j.)
(15-53)
As we remarked previously, one can discuss the validity of these rather simple assumptions. However, there are also certain arguments in favor of these assumptions. We refer the reader to national economic literature for more detailed study. It is easy to make a simple Modelica model based on equations (15-51) to (15-53): class KyenesianModel parameter Real a = 0.5 "Consumption fraction"; parameter Real b = 0.5 "Investment fraction of consumption increase"; Real GNP (start=O) "Gross National Product"; Real consumption (start=O) "Consumption"; Real investments (start=O) "Investments"; Real expenses (start=O) "Government expenses"; equation when sample (0, 1) then GNP consumption + investments + expenses; consumption a * pre (GNP) ; investments b * (consumption - pre(consumption)); end when; when time >= 1.0 then II Increase expenses by 1 at year 1 expenses = pre(expenses)+l; end when; end KyenesianModel; Here we have made the rather unrealistic assumption that GNP, consumption, investments, and government expenses are all zero at the beginning of the first year. However, this can be easily changed and does not matter for the result when studying annual changes instead of absolute values. After one year we suddenly increase government expenses by 1. The proportionality factors for the consumption and investments are assumed to be 0.5, i.e., at a level of half of the GNP. We simulate the model and observe the effects on the other economic variables: simulate (KyenesianModel, stopTime=11} plot ({GNP, consumption} , xrange={O,lO}) A plot of the simulated GNP and the consumption is depicted in Figure 15-31.
r-----.r----"-----'1.
2
.,.
. .
I
GNP
r-----· 1
1.5 15 0.
! i
_lL~:_~conBumPtion 2
4
6
8
10
t
Figure 15-31. The GNP and the consumption after an increase of government expenses by 1 after I year.
564 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica It is interesting to observe the effects on the GNP and the consumption after the increase in state expenditures. After a few years the GNP has increased to a factor of 2 of the increase of government expenses, which is the so-called multiplier effect exhibited by this model. The immediate effect of the expense increase is that the GNP increases by the same amount. As a consequence, investments increase the year later. This causes a further increase in GNP and consumption. Eventually we arrive at a steady-state GNP level of 2 and a consumption level of 1.
15.6 Packet-Switched Communication Networks Packet switched communication networks playa very important role in modern society since they provide the basis for transport of data in widely used networks such as the Internet, local area networks, and a number of special-purpose networks. A packet-switched network can be described by a directed graph. The nodes in this graph represent routers, which are computers that forward information packets on their way from senders to receivers. The edges between the nodes in the network are either wired or wireless communication links. A sender is a computer that sends information packets into the network with a destination of some receiver computer node. Figure 15-32 schematically depicts a simple network that provides a connection between a sender and a receiver via a number of routers and communication links.
Figure 15-32. Schematic packet-switched communicationnetwork, with router nodes connected by communicationlinks, together with a sender and a receiver. The links between the nodes in the network have limited bandwidth, which can lead to traffic congestion. To handle minor traffic congestion the routers in the network have buffer storage capacity in order to store packets in case more packets are entering than leaving a router. However, if too many packets are entering a router during a short period of time, the buffer capacity may not be enough, which will lead to packets being dropped. Dropping packets is inefficient since information has to be resent. The congestion problem might be an indication that the sender is transmitting information at a higher rate than what the communication network can handle. The problem is solved if the sender adapts its rate of sending information through some control mechanism. On the. Internet a control mechanism denoted the Transmission Control Protocol (TCP) is used by the sender to regulate the send rate.
15.6.1 End-ta-End Communication Protocols There exist several variants of the TCP protocol with different properties concerning congestion handling, transmission efficiency, etc. All TCP protocol versions are end-to-end communication protocols, meaning that the network is regarded as a black box from the sender's point of view. Each package is sent all the way to a receiver
Chapter 15 Application Examples 565 node, which returns a small acknowledgment package for each received package. If a package is dropped due to congestion or some other reason, this will be eventually detected by the sender due to a missing acknowledgment package. In order to use the network resources more efficiently and thereby allow higher transmission rates, the TCP sender transmits w number of packages before waiting for acknowledgments for these packages. Therefore w corresponds to the number of unacknowledged packets the sender may have in the network, The w variable is called the TCP window size and controls the sending rat~ large value of the window size w means a higher sending rate. When the sender has received acknowledgments for all w packages, w is increased by I. If a packet is dropped, meaning that no acknowledgment for that packet has been received by the sender, the TCP protocol assumes that some congestion has occurred, i.e., the currently estimated bandwidth and window size values are too high. The algorithm tries to eliminate the congestion by reducing the sending rate. The reduction depends on which variant of the TCP protocol is used. In the following we will focus on two variants: • •
TCP SACK-Selective ACKnowledgment-a common protocol variant for wired links, where the receiver of data informs the sender about all packets that have arrived successfully. TCP Westwood-a more recent protocol variant very similar to TCP SACK introduced to better handle communication over lossy wireless links where random or sporadic losses are fairly common. This protocol uses bandwidth estimation for quick recovery after sporadic losses.
The TCP SACK protocol provides congestion avoidance, i.e., recovery after congestion, by decreasing the window size w by a factor of 2 each time a packet drop occurs, as depicted in the simple transition diagram of Figure 15-33, where we use the notation wf to indicate that there might be several packet flows between a sender and a receiver, here denoted by the subscript f drop!
Figure 15-33. Simplified transition diagram of congestion avoidance used in TCP SACK for which the window size WI is reduced by a factor of 2 when there is a packet drop. The TCP Westwood protocol has another way of updating the window size w/ after congestion or transmission loss. Instead of dividing the window size by a factor of 2, it is set to a new value based on the bandwidth estimate (BWE) for the link. This provides quicker recovery and better use of the available bandwidth after a packet drop. Both TCP protocols have congestion-control algorithms that use packet loss to detect congestion. Moreover, during a startup phase the TCP senders investigate the network capacity by gradually increasing the size of the window of packets that are outstanding in the network until the network becomes congested and drops packets. A TCP sender initially quickly grabs available bandwidth by exponentially increasing the window size. When the window size reaches a certain value called the slow start threshold, ssth, the increase becomes linear, which gives a gentler probing of the network bandwidth capacity. It is desirable to keep this threshold at a value that approximates the connection's "fair share" of the total bandwidth.
15.6.2 Types of Communication Network Models There are basically three classes of mathematical models used for simulating traffic flow based on TCP protocols on the Internet:
566 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica Discrete models, which directly implement the Internet protocols and simulate individual packets.
•
Such models give accurate simulation results but rather slow simulation speed, and are therefore limited to smaller networks. •
Continuous flow models, which approximate the packet transmission with a continuous flow and basically eliminate the network protocols. Such models describe average transmission rates at steady-state well but ignore events such as packet drops, and are thus less suitable for studying transient phenomena.
•
Hybrid models, which use continuous-flow modeling for average rates but also take transient
events such as packet drops into account. Hybrid models can capture the network behavior on time scales between discrete models and continuous flow models. They can be efficiently simulated for large networks and high traffic loads, but can still represent transient phenomenasuch as traffic congestionand packet drops. In the following we will give a short overview of a hybrid Modelica model of a simple packet-switched network in which two different TCP send protocols are compared.
15.6.3 A Hybrid Network Model Comparing Two Tep Send Protocols Our simple packet-switched networkexample is specifiedin Modelica using the hybrid modelingapproach mentioned in the previous section. We would like to simulate the model to compare the congestion behavior of such a network using two different TCP protocol variants: TCP SACK and TCP Westwood. The simple network,depicted in Figure 15-34, contains the following components: • • • •
Two packet senders, using the TCP SACK and the TCP Westwoodprotocol variants respectively. One router connectingboth senders to a wirelesslossy communication link. Another router connectingthe wireless link to two receivers. Two receiver components.
The communication ports used for connectingthe modelcomponents are defined in the next section.
.
,r-----------------------------------------------------
~
f
rep
Westwood
· recei ver1 : ,
.,
., . , ,,
:, , ,,, , ,
.
receiver2 ,
:_----------------------------------------------------. Figure 15-34. Simple network withtwosenders (TCPWestwood, TCPSACK), tworeceivers, a wireless link, and two routers.
Chapter 15 Application Examples 567 The Modelica code of the simple TCP communication network model appears below. We have configured the system with a packet length L=500, a maximum total bandwidth B_tot of 500*1250*2, i.e., max 1250 packets for each of the two flows, and a maximum buffer capacity CLmax of so packets. model TCPSACKvsTCPWestwood "TCP SACK versus TCP Westwood" Router21 router21; Router12 router12; Lossy_link_queue lossy_l ink_queue (B_tot=500*1250*2, ~max=50*500, L=500); TCP Westwood aTCPWestwood(L=500, send f to=l); II sender 1
TCP=SACK
aTCPSACK(L=500, send_f_f~o;=2, send_f_to=2); II sender 2
Receiver receiver1; Receiver receiver2; equation connect (aTCPSACK.o, router21.i2); connect (aTCPWestwood.o, router21.il); connect(router21.o, lossy_link_queue.i); connect(router12.i, lossy_link_queue.o); connect (router12.o1, receiverl.i); connect (router12.o2, receiver2.i) i end TCPSACKvsTCPWestwoodi
A simulation of this model is available in Section 15.6.9, page 577.
15.6.4 Communication Port Classes The Port class shown below defines the interface used for connections between instances of the components in the TCP network model. The class is declared partial to indicate that it is intended to be used as a parent class to Inport or Outport, even though it is complete. All components need at least one Inport or one Outport connector instance. Some components have several ports, e.g. the routers and the queue, whereas the senders and the receivers have only one Port each. The following variables declared in the Port class are propagated throughout the network model: • • • • •
The number of packet flows, n, in the network. The packet round-trip times, RTT, from the sender to the receiver and back for each flow. The drop-event indicator, d, for each flow. The flow rates, r [by tes/s], sending or incoming rates, for each flow. The bandwidth estimates, BWE, for each flow.
The Modelica code for the Port class and the equivalent Inport and Outport classes appear below. partial connector Port "Interface to all connector instances in the network" parameter Integer n=2 uNumber of flows"; Real r[n] "r[f] - flow rate byteslsec for flow f in connector"; Boolean d[n] "d[f] - true when drop occurred in flow fIt; Real RTT[n] "RTT[f] - Round Trip Time for flow fll; Real BWE[n] "BWE[f] - BandWidth Estimation for sender, flow fIt; end Port; connector rnport "Input version of Port" extends Port; end Inport; connector Outport "Output version of Port" extends Port; end Outport;
We will now tum to the network sender components, each having one Outport instance.
568 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
15.6.5 Senders The two hybrid TCP sender models, TCP SACK and TCP Westwood, have four different discrete states as depicted in Figure 15-35.
Figure 15·35. State transition diagram for the TCP SACKand TCP Westwood protocol variants. The states for each flow are the following:
•
• •
•
Slow start-the sender is initially in this state, in which the window size quickly increases exponentially up to the slow-start window threshold level, s st.h, after which a state transition to the congestion-avoidance state occurs. Congestion avoidance-in this state the window size increases at the slower additive rate specified by equation (15-55), and the system is prepared to handle congestion if it occurs. Fast recovery--when entering this state we try to recover quickly from a congestion event, by dividing the window size in half according to TCP SACK, or compute it from a bandwidth estimate according to TCP Westwood. Time out-this state is entered when a timeout occurs in the congestion-avoidance or slow-startup states. The window size is reduced to the very low value of 1 and a transition to the slow-start state is performed.
In all states except the timeout state the transmission rate rf for flow f is given by the following equation: wfoL
rf = - -
(15-54)
RTF!
where W f is the window size in packets, L is the packet length in bytes, and RTFf is the round-trip time for flow f. The formula just states that the transmission rate is the number of currently pending transmitted bytes divided by the round-trip time. The round-trip time is the time between sending a packet and receiving the corresponding acknowledgment. It is the sum of the physical propagation time and the queuing times, and is defined in the lossy link model described in Section 15.6.7, page 572. We will not discuss all the details of this model, but rather focus more on the important congestionavoidance state, which specifies additive increase of the window size W I according to equation (15-55) for probing the available bandwidth: .
wf = -
1 -
RTFf
(15-55)
where Wf is the additive window size increase rate. A simplified state diagram for congestion avoidance was previously shown in Figure 15-33, whereas the more realistic version of the state diagram is depicted in Figure 15-36.
Chapter 15 Application Examples 569
w pre
wI =_f-
2
or
Wf
= max(
BWE
/
.tarr: f , 2) 2
Westwood
SACK
Figure 15-36. State transitions in the congestion-avoidance state after a packet drop for the TCP SACK and TCP Westwood protocol variants.
When a packet drop is detected, the state is changed from congestion avoidance to fast recovery. When entering the fast recovery state in the TCP SACK variant, the instantaneous equation (15-56) is activated that reduces the window size by a factor of 2 compared to the previous value: pre
w - -fWf -
(15-56)
2
As mentioned previously, the TCP Westwood model is the TCP sender variant designed for lossy wireless links. This variant of the TCP protocol is quite similar to TCP SACK, except that the window size is not halved when packet drops occur. Instead the window size is set to a more realistic value using a bandwidth estimate, BWE" for flow f specified by the instantaneous equation (15-57). This enables fast recovery after a drop since a correct setting of the window size is obtained very quickly. The instantaneous equation is activated only at the transition to the fast recovery state, and appears as follows:
w = max(
BWE ·RIT min
f
/
f
2'
2)
(15-57)
where R1T,rIDn is the minimum round-trip time computed so far for flow f RTf,miD is a measure of the fastest possible round-trip with minimum delays from queuing in intermediate routers and other disturbances. The slow-start threshold ssth is also updated when entering the fast recovery state. The Modelica code for both the hybrid TCP SACK and the hybrid TCP Westwood model variants appears merged as a single TCPSender class below; there are very small differences between the two variants, When the Boolean variable tcpSACK is true, that variant is enabled; otherwise the TCP Westwood variant is active. model TCPSender Outport constant constant constant constant parameter parameter parameter parameter parameter parameter parameter parameter
"Hybrid Transmission Control Protocol, two variants: TCP_Westwood or TCP_SACK Selective ACKnowledgement"
0;
Integer slowStart=l; Integer fastRecov=2; Integer congestAvoid=3; Integer timeOut=4; Boolean tcpSACK = true "false means TCP_Westwood"; Integer n=o.n "Number of flows"; Integer a=l "Additive increase"; Real L=l "Packet size in bytes"; Integer send_f_from=l "This sender's first flow"; Integer send_f_to=n "This sender's last flow"; Real timeout th=4.0 "Window threshhold for entering timeout"; Real m[n]={2--:2} "log m in Slow-start"; II {1.S, 1.7, 2, 2.5, 2.7} "log m in Slow-start"; parameter Real RTO[n]=fill(O.200,n) "Retransmission TimeOut 200 ms"; discrete Integer state[n] (start=fill(slowStart, n)); Real ssth[n] (start=fill(65535.0/L, n)) "Slow start thresholds";
570 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Real w[n] (start=ones(n» "Communication window sizes, no of packets"; Real d_tim[n] (start=zeros(n» "Drop timer"; Real t_tim[n] (start=zeros(n» "Retransmission timer"; Boolean DelayD[n] (start=fill(false,n»" Delay induced Drop detected"; //TCP Westwood variables Real RTT_min[n] (start=fill(1.0, n» "Minimum Round-Trip Time"; Real BWE[n] "BandWidth Estimation for each flow"; equation for f in l:n loop if (f >= send_f_from and f 0 then -1.0 else 0.0; DelayD[f] = if d_tim£f] < 0 then true else false; when (o.d[fl and d_tim[fl o.RTT[f]) then reinit(RTT_min[fJ, o.RTT[f])i end when; else II Unused flows when initial() then reinit (w [f], 0); end when; o.r[f] = 0; der(w[f) = 0; der(ssth[f]) = 0; der(d_tim[f]) = 0; der(t_tim[f]) = OJ DelayD[f] = false; II 2 eqs used only by TCP_Westwood: BWE[f] = 0; der(RTT_min(f]) = 0; end if; end for; algorithm II State transitions for f in l:n loop if (f >= send_f_from and f = timeout th and (state[f] == slowStart or state[f] congestAvoid)) then state[f] := fastRecov; elsewhen (w[f] >= ssth[f] and state[f] == slowStart> then state[f] := congestAvoid; elsewhen (w[f] < timeout_th and edge(DelayD[f]) and (state[f] == slowStart or state[f] == congestAvoid) then state[f] := timeOut; elsewhen (t_tim[f] < 0 and state[f] fastRecQv) then staterf] := congestAvoid; elsewhen (t_tim[f] < 0 and state[f] timeOut) then state [f] : = slowStart; end when; else state[f] .- 0; end ifj end for; end TCPSender;
:=
Having presented the sender models, we will now tum to the quite simple receiver model.
15.6.6 Receivers A receiver, e.g. as depicted in Figure 15-37, has the sole function of receiving a stream of packets and returning acknowledgments. It has a single input port.
572 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica ....... _.1te eiver_
I
·
··· I
I
I
Figure 15-37. Receiver with one Inport. The Modelica code for the Recei ver model appears below: model Receiver "Receiver" Inport i; parameter Integer n=i.n; parameter Boolean d[n]=fill(false,n) "Drop d[f] true/false for flow f"; parameter Real RTT[n]=zeros(n) "Round Trip Times"; Real received[nl (start=zeros(n)) "received[f] bytes for flow f"; Real received_tot "Rotal received bytes, all input flows"; Real r_tot_in "Total reception rate bytes/s, all input flows"; equation der(received) = i.r; r_tot_in = sum(i.r); received_tot = sum(received); i.d = d; i.RTT = RTT; i.BWE = i.r; end Receiver;
The receiver is a very simple model class, which is not quite true for the communication link model to be described in the next section.
15.6.7 Lossy Wireless Communication Link Model We now arrive at one of the most important components of our network model, namely the intermediate lossy wireless communication link that represents both the physical links and the intermediate routers with queues for temporary packet storage, e.g. as schematically depicted in Figure 15-32, page 564. Several communication flows can be accommodated within the same physical network. Thus, our lossy link model needs to represent packet transmission and transmission delays over physical links and queuing of packets in intermediate routers, as well as stochastic sporadic transmission losses and bandwidth disturbances. In the following treatment of a mathematical model for the communication link we will make the simplification of a single router queue per flow instead of multiple queues, with no great loss of precision. We will treat the queue sizes, packet flow transmission rates, as well as a number of other quantities as continuous-time real-valued variables in our hybrid network communication model. However, even though the queues are stored in the routers of real physical systems, in the TCPSACKvsTCPWestwood model we have put the queuing mechanism in the communication link model for practical reasons. The variable qf is the number of bytes in flow f stored in the router queue for that flow, SI is the input send rate (bytes/s) of bytes sent into the queue of flow j, and rf is the output receive rate (bytes/s) of bytes received from flow j of the communication link by some external node(s). We can express these quantities summed over all flows as follows:
Chapter 15 Application Examples 573
«; =Lql f Stot
=LSI
(15-58)
f r,ot
= Lrf f
where q tot is the total number of bytes summed over all flows for packets queued in the network, S tot is the input total send rate over all flows sending bytes into the network, and 'tOI is the output total receive rate over all flows recei ving bytes from the network. The behavior of the communication link is dependent on whether the queue is full, qtot = qmax' or is not full, 0 ~ qtot < qmax , which is reflected in the state transition diagram depicted in Figure 15-38.
qtot
= qmax
OS; q,ot < qmax
droPf
z=L Figure 15-38. Two-state transition diagram of lossy communication link, where the not-full state contains three substates and the full state two substates. The total bandwidth of the outgoing link is equal to the constant Btot . If the total send rate into the input link Stot > Btot ' then a fraction of the packets must be temporarily stored in the queue of the communication link at the rate qI ' which is nonzero when the output rate is defined by the second or third equation that defines rf in (15-59). The variable z is the number of input bytes of the currently received packet that have been dropped. When the queue is not full, no bytes need to be dropped since they can be stored in the queue. However, when the queue is full, the drop rate is the amount that the total input rate exceeds the output transmission rate, as defined by the first equation of (15-60). A packet drop is generated when the variable z has accumulated a byte flow amount equal to the packet length L. The following equations represent the relations between the main quantities of the model for the two main states: •
The queue notfull state, 0 ~
qtot
< qmax :
i=O qf =sf -rf
, qtot
= 0 and
Stot
~
,qtot
= 0 and
S'ot
> Btot
Sf
rf = - Btot
Btot
(15-59)
Stot
-
qf Btot' otherwlse ·
«;
where the condition qtot =0 is represented as (~tot qror
Btot
(15-60)
qf
rf =--Bto,
«;
The following Modelica class Lossy_link_queue represents the previous relations and includes the following aspects of the lossy link: • • • • •
Packet flows, including reception of packages sent into the link and transmission of packages to be received by a node at the output. Queue handling, including queue storage rates, transmission rates, and the different states when the queue is full or not full. Drop regeneration, when the queue is full and input rates exceed the maximum transmission rates. Random generation of good state and bad state transmission quality intervals. In the bad state the probability for packet drops is fairly high. Computation of the round-trip timing R1Tf and bandwidth estimate BWE/ for each flow.
These properties are in most cases modeled by separate groups of equations in the class. However, the modeling of the two main states with their substates and conditional equations is somewhat more implicit. The Modelica code for the class Los sy_1 ink_queue follows below: model Lossy_link_queue "Wireless transmission link queue" Inport i "Port for flows from router into queue"; Outport 0; "Port for flows from queue into router"; parameter Integer n=max(size(i.r»"Number of flows"; parameter Real B_tot=lOA 7/8000 "Default Total Bandwidth"; parameter Real CL-max=57 "Max total queue size"; parameter Integer L=500 "Packet size"; parameter Real T=O.02 "Physical propagation delay for trip"; parameter Real eps=O.Ol "Threshold to avoid division by zero"; parameter Real 10ss_factor_good=O.OOOOl "Absolute loss level"; parameter Real loss_factor_bad=O.lO "If bad, fraction lost"; parameter Real Ig=8; parameter Real lb=4; Real Real Real Real Boolean
~tot(start=O)
Integer Integer Real Real Real Real
u_flow(start=l) "1 if underflow - integer used as fake boolean"; o_flow(start=O) "1 if input overflow - int used as fake boolean"; q[n] (start=zeros(n» "Number of elements from flow f in queue"; rand "Random variable for drop decision"; z(start=O) "Drop detection, dropped bytes"; RTT_initial "Initial RTT to prevent singularity at init time";
"Total number of bytes in queue"; s_tot "Sent from router to link - incoming total byte flow rate"; r tot "Received from link to ext router - no10ss total byte rate"; s-tot acc(start=O) "Total no of sent incoming bytes accumulated"; ~full(start=false); II true if queue full
II To get a lower sending rate than the bandwidth Real sen] "s[f] send rate from router into link, flow fn; Real r[n] "r(f] no loss receive rate into router from link, flow fIt; Real r_acc[n] (start=zeros(n» "Received bytes from link accumulated"; Boolean 10s8[n] "loss[f] true if loss in flow fIt;
Chapter 15 Application Examples 575 Real
rand_loss[n] (start=fill(O.5, n l l ,
Boolean GOOD STATE "Good commlink state with low loss factor"; Boolean BAD_STATE "Bad commlink state with high loss factor"; Real 9_tim(start=1) "Timer for good state duration"; b_tim(start=-l) "Timer for bad state duration"; Real Real loss_factor(start=O.OOl); equation s = i.r; II Send rate from router at input o.r = (1 - loss factor)*r; II Lossy receive rate to router at output s_tot sum(s)i r_tot = sum(r)i CLtot = sum(q); der(s tot_ace) = s_tot; a_flow if s_tot > B_tot then 1 else 0; II 1 if incoming traffic rate>max u_flow = 1 - a_flow; II 1 if s tot eps) then B_tot*q[fJ/q_tot II Queue not empty else a flow*B tot*s[f]/s tot + u flow*s[f]; II q empty der(q[f]) = if 0 then -1.0 else 0.0; II If positive, decrease der(b_tim) if b tim> 0 then -1.0 else 0.0; II If positive, decrease loss_factor = if GOOD_STATE then loss_factor_90od else loss_factor_bad; for f in l:n loop der(r_acc[f]) = r[f]; der(rand_loss[f]) = 0; loss[f] = (r acc[f] > rand loss[f]*2*L/loss factor); when r acc[f] > rand loss[f]*2*L/loss factor then rei~it(r_acc[f], 0); end when; when pre(loss[f]) then reinit(rand_loss[f], rand); end when; end for;
II II
Compute packet drops uniformly distributed among flows Drop rate der(z) is send rate above total bandwidth when ~full der(z) = if ~fu11 then s_tot - B_tot e1s8 0.0; rand = randomUniform(time); II If ~full becomes true or z>L the generate drop in a flow and set z=O if (z > L and ~tot > epa) or edge(~full» then i.d[l] = if (O {springDamperl.d == e}l, {s,2,15,2}l; PlotSimulation[slidingMassl.s[t], {t, 0, 4}, SimulationResult -> res, Legend -> False]; 0.07 0.06 0.05 0.04 0.03 0.02 0.01 1
2
3
4
Figure 15-44. Plotsof step responses from seven simulations of the linear actuator withdifferent damping coefficients. Now assume that we would like to choose the damping parameter d so that the resulting linear actuator system behaves as closely as possible to the following"reference" first-order system response, obtained by solving a first-order ODE using the Mathematicadifferential equation solver NDSolve: resReference
= NDSolve[{0.2*y' [t]+y[t] == 0.05,
y[O]
== o}, {y}, {t,O,4];
We make a plot to compare the step response we simulated first for a damping value d=2 and the response from the "reference" first-order system (Figure 15-45). PlotSimulation[{slidingMassl.s[t], y[t] SimulationResult -> resLinActFirst];
I.
reSReference}, {t,C,4},
Chapter t 5 Application Examples 581
slidingMass1.s(t) y(t)
0.06 0.05 0.04 0.03 / I 0.02 I
0.01 time 2
1
3
4
Figure 15-45. Comparison plot between the step response of the linear actuator and the "reference" firstorder system.
Now, let us make things a little more automatic. Simulate and compute the integral of the square deviation from t=O to t=4. This integral is a measure of the deviation from the "reference" response, and is thus suitable as a goal function to be minimized. Simulate [LinearActuator, {t,O,4}, ParameterValues -> {SpringDamperl.d == 3}1; Nlntegrate[First((y[t] I. resReference) - SlidingMassl.s[t]]A 2, .{t, 0, 4}] 0.000162505
We define a Mathematica function, f [a] , doing the same thing as above, but for different values of the spring-damper design parameter d. The function contains two local variables res and t. The expression (y [t] I. resReference) retrieves the interpolating function representing the variable y [t] , i.e., the reference response. f[a_]
:=
Module [{res, t},
Simulate [LinearActuator, {t, 0, 4}, ParameterValues -> {SpringDamperl.d == a}]; Nlntegrate(First[(y[t] I. resReference) - SlidingMassl.s[t]]A 2 , {t,0,4}]]
We tabulate some results for 2 S d S 10 into an array resDeviations: resDeviations
=
Table [{d, f Id} }, {d, 2, 10, O.S}]
{{2,O.000317667}, {2.S,0.000221484},{3.,O.000162S05}, {3.5,0.00012SS13},{4.,0.OOOl02749}, {4.S,O.0000898832},{5.,0.000084067}, {S.S,O.0000836711},{6.,O.0000874S86}, {6.S,0.000094S743}, {7.,0.000104399}, {7.S,0.000116464},{8.,0.000130394}, {8.S,0.000145922},{9.,0.000162819}, {9.S,O.000180894},{10.,O.000200008}}
The tabulated values are interpolated into a Mathematica interpolating function (Figure 15-46). The default interpolation order is 3. f pr e ::: Interpolation [resDeviations] ; Plot [f pre [d), {d, 2, 10 l l ;
582 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
0.00030 0.00025 0.00020 0.00015
4
6
8
10
Figure 15-46. Plot of the deviation function for finding the value of the damping parameterthat gives a minimum deviationfrom the reference response. The minimizing value of d can be computed using FindMinimum: FindMinimum [f p r e [d], {d, 4}] {O.0000832564180689619S,
{s
->
5.2864232458S40S1}}
A simulation with the optimal parameter value: Simulate (LinearActuator, {t, 0, 4}, ParameterValues -> {SpringDamperl.d
==
S.28642}];
A plot comparing the "reference" first-order system and linear actuator system responses together with a plot of the squared deviation amplified by a factor 100 is given in Figure 15-47. PlotSimulation[{SlidingMassl.s[t], y[t] I. resl, 100* (SlidingMass1.s[t] - (y[t] I. resReference»A 2}, {t, 0, 4}, Legend -> False]; /
-----~-----------
~'~
0.05
0.04
/
,/
Reference 1st order system
n
0.03
If\
0.02
j
0.01
Optimized2nd order system
~
\~ Squared difference
\ \
-" 1
2
3
4
Figure 15-47. Comparison plot of the first- and second-order systemstep responses together with the squarederror.
15.8 Fourier Analysis of Simulation Data A simulation of a system may indicate the presence of periodic phenomena such as vibrations. Fourier analysis on the simulation results transforms the data from the time domain into the frequency domain, which makes frequency-dependent characteristics very explicit. For example, the main modes of oscillation become visible as peaks in a plot, e.g. as in Figure 15-49 below.
Chapter 15 Application Examples 583 For example, consider a weak axis (a nonrigid flexible axis containing springs) excited by a torque pulse train. The axis is modeled by three segments joined by two torsion springs, depicted in Figure 15-48.
l'jLJml-·~.. putset
torque 1
..~ . .~) 'tilt' inertia1
spring"
inertia2
spring2
inertia3
Figure 15-48. A WeakAxis model excited by a torque pulse train.
The corresponding Modelica code: model WeakAxis import Modelica.Mechanics.Rotational; import Modelica.Blocks.Sources; Rotational.Torque torquel; Rotational.Inertia inertial; Rotational.Spring springl(c=0.7); Rotational.Inertia inertia2; Rotational.Spring spring2(c=1); Rotational. Inertia inertia3; Sources. Pulse pu!sel(width=1,period=200); equation connect (pulsel.y, torquel.tau); connect (torquel.flange_b, inertial. flange_a) ; connect (inertial. flange_b,springl.flange_a) ; connect (springl.flange_b, inertia2.flange_a); connect(inertia2.flange_b,spring2.flange_a); connect (spring2.flange_b, inertia3.flange_a); end WeakAxis;
We simulate the model during 200 seconds: Simulate [WeakAxis, {t, 0, 200}J;
The plot of the angular velocity of the rightmost axis segment appears as in Figure 15-49, indicating the presence of oscillation frequencies in the result. Note that the greek letter t can be used instead of writing tau, when using the MathModelica Mathematica-style command interface. PlotSimulation[inertia3.w[tl, {t, 0, 200}]; PlotSimulation[torquel.L[t], {t, 0, 200}]; Inertia3.w
Torquel.r
I
1.°L Lsi
1.5 1.0
0.5
0.5
time 100
150
200
1
so
time 100
150
200
Figure 15-49. Plot of the angular velocity of the rightmost axis segment of the WeakAxis model.
Now, let us sample the interpolated function Inertia3 . w using a sample frequency of 4Hz, and put the result into an array using the Mathematica Table array constructor: datal = Table [inertia3.w[t] , {t, 0, 200, 0.25}];
Compute the absolute values of the discrete Fourier transform of datal with the mean removed: fdatal = Abs[Fourier[datal - MeanValue[datal]]];
Plot the first 80 points of the data (Figure 15-50).
584 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica ListPlot[fdatal[[Range[80]]], PlotStyle
->
{Red, pointSize[O.015]}1;
•
10 8 6
•
4
•
2 20
40
80
60
Figure IS-SO. Plot of the data points of the Fourier-transformed angular velocity.
A simple Mathematica function FourierPlot can be written that repeats the above operations. FourierPlot also scales the axes such that amplitude of trigonometric components are plotted against frequency (Hz) (Figure 15-51).
FourierPlot(inertia3.w(t), {t, 0, 200}, 0.5, PlotJoined -> True, PlotStyle -> Red] ;
0.7 0.6
0.5 0.4 0.3 0.2 0.1 0.2
0.4
0.6
0.8
1
Figure IS-51. Plot of the data points of the Fourier-transformed angular velocity.
15.9 Pressure Dynamics in 1D Ducts--Solving Wave Equations by Discretized PDEs Currently Modelica cannot handle partial differential equations (however, language extensions are on the way-see Section 8.5, page 258). directly since there is only the notion of differentiation with respect to time built into the language. However, in many cases derivatives with respect to other variables (such as, for example, spatial dimensions) can be handled by simple discretization schemes represented using the array capabilities in Modelica. Here we will give an example of how the one-dimensional wave equation can be represented in Modelica and how MathModelica can be used for simulation and display of the results, as well as representing the result as a 2D interpolating function. The one-dimensional wave equation is given by a partial differential equation of the following form:
iJ2 p 2 iJ 2p --=c -2 2
iJt
iJx
(15-61)
Chapter 15 Application Examples 585 where p =p(x,t) is a function of both space and time. As a physical example let us consider a duct of length 10 where we let - 5 ~ x ~ 5 describe its spatial dimension. Since Modelica can handletime only as the independent variable, we need to discretize the problem in the spatial dimension and approximate the spatialderivatives using difference approximations using the approximation: 2
aP at 2
P;-I
+ Pi+1 - 2Pi
(15-62)
Ax 2
::::::
wherePi = p(x1 + (i -1)· Lix) on an equidistant grid. Utilizing this approach a Modelica model of a duct whose pressure dynamics is given by the wave equation can be written as follows, where the pressure function p to be computed is represented as a one-dimensional array p of size n, where the array index is the discretized space coordinate along the x-coordinate, and the time dependence is implicitas usual for a continuous-time Modelica variable: model WaveEquationSample import Modelica.Slunits; parameter SIunits.Length L=10 "Length of duct"; parameter Integer n=30 "Number of sections"; parameter SIunits.Length dL::L/n "Section length"; parameter SIunits.Velocity c=l; SIunits.Pressure[n] p(start=initialPressure(n))i Real[n] dp(8tart~fill(O,n»); equation p [1] =exp (- (- L /2 ) 2) ; p[n]=exp(-(L/2)A 2); dp=der (p) ; for i in 2:n-1 loop der(dp[i)) = cA2*(p[i+1)-2*p[i)+p[i-l])/dLA2i end for; end WaveEquationSample; A
Here we are using a Modelica function initialPressure (defined further below) to specify the initial value of the pressurealongthe duct. Assume that we would like an initial pressure profilein the duct of the 2 form e- x ,depicted in Figure 15-52 by the following plot command: 2
Plot Le" x , {x, -5, 5}J;
-4
-2
2
4
Figure 15-52. The initial pressure profile of the duct.
The function ini tialPressure returns the initial pressure profile function in discretized form as an array. function initialPressure input Integer n; output Real p[n] ; protected parameter Modelica.Slunits.Length L=10;
586 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica algorithm for i in l:n loop p [i] : =exp (- (-L/2+ (i-I) / (n-u ) *L) 2 ) ; end for; end initialPressure; A
We simulate the WaveEquationSample model: Simulate [WaveEquationSarnple, It, 0, 10}l;
The simulation result, i.e., the array p, shows how the pressure evolves at equidistant positions in the duct as functions of time. This is represented by the array p of 1D interpolation functions of time, which are packed into a Mathematica 2D interpolation function and plotted using the following two commands (see Figure 15-53): intp
=
Interpolation [Flatten [Table [{-S. + «k - 1)/29)*10, t, p[[k]] [t]), {k, 1, 30}, {t, 0, 10, 0.2}], 1]] i
Plot3D[intp[x,t] ,{x,-5~5},{t,0,10}, PlotPoints->30, PlotRange->{-I,l}, AxesLabel->{"x","t","p(x,t)"}Ji
1 0.5 ptx.t) 0 -0.5 -1 -4
-2 X
o o
Figure 15-53. A 3D plot of the pressure distribution in the duct.
Let us also plot the wave as a function of position x for a fixed point in time (t= 1.2) to observe the pressure distribution in more detail (Figure 15-54): Plot [intp [x, 1.2] I {XI - 5 IS}]
-4
-2
2
i
4
Figure 15-54. The wave as a function of position at time=l .2.
Chapter 15 Application Examples 587
15.10 Mechanical Multibody Systems and the MBS Library A mechanical multibody system can be defined as a system consisting of a number of interacting mechanical bodies or substructures. Previously (Section 14.8, page 502) we gave an introduction to the topic of multibody systems for rigid (nonflexible) bodies, explained the basic concepts, and presented the basic equations including Newton's laws in a form that is used by the Modelica multibody system (MBS) library. The goal of this section is to give a short introduction on how to use the Modelica MBS library to model 3D mechanical applications, as well as presenting a short overview of the library itself. The main goal of the Modelica MBS library is to simplify modeling and dynamic analysis of mechanical systems including mechanical subsystems that are part of larger multidomain systems. Given an idealized model of a mechanical multibody system and external forces influencing this system, a Modelica simulation can compute the position and orientation of each body as a function of time. The most typical use of such a model is to analyze the movements of bodies resulting from the application of certain forces and torques, as well as influences from other changes in the environment. The forces and torques can have different origins: these can be produced by drive trains, electrical motors, controlling devices, etc., or from a combination of such elements. Newton's laws are expressed in the MBS library class MultiBody. Parts. Body, which also is used in other models. Equations of motion and coordinate transformations are formulated in the library, both for free bodies and for connected bodies related by some constraints. Each body has one or more local coordinate systems, also denoted frames of reference, or just frames. Coordinate transformations are used to relate quantities expressed in these frames. The library works with rigid bodies that have some geometric extent, i.e., have not been simplified to point masses. The rotation of bodies relative to the inertial coordinate system is taken into account, being represented by quantities such as angular velocity and angular acceleration vectors. The MBS library described here is the most comprehensive Modelica multibody system library for 3dimensional mechanical rigid bodies. It has a unique technical feature compared to other MBS libraries in its very efficient treatment of joint locking and unlocking. This allows, for example, easy and efficient modeling of friction elements or brakes in joints. Another rather unique feature is to allow connection of all kinds of object in physically meaningful ways, including designs consisting only of force elements such as springs. The major area that the MBS library currently does not handle is multibody systems consisting of general flexible bodies, i.e., bodies that may undergo deformations. However, future extensions in this direction are planned.
15.10.1
New and Old Version of the MBS Library
A new version of the Modelica MBS library (Modelica.Mechanics.Multibody) has recently (September-Nov 2003) been released. This library has a number of advantages compared to the old version of the MBS library (ModelicaAdditions. Multibody), which has been almost unchanged for the past four years. However, the old version of the library is used by many applications and mentioned in many published papers-therefore we will also briefly describe some properties of the old library in this overview, even though we primarily present the new library. A complete document describing the old MBS library is available on the book web page www.DrModelica.org. The new library has the following advantages compared to the old one: •
The new library is much easier to use-all physically meaningful connections between library components are supported, even including direct connections between pure force elements. The old library has several restrictions on how to connect different kinds of objects, which makes it harder to use.
588 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica •
The new library has automatic removal of superfluous equations resulting from so-called kinematic loop connection structures (except for planar kinematic loops, see Section 15.10.7, page 601)-in the old library kinematic loops have to be broken manually by inserting so-called cutjoints, which can be tricky.
•
Built-in animation properties are available for all components, such as joints, forces, bodies, sensors. Animation can easily be turned on or off. The old library has less convenient and less comprehensive support for animation.
•
A number of other improvements are available in the new library such as better documentation, structuring, and understandability including a set of vector and matrix expression functions (in MUltiBody. Frames) that are inlined in equations, definitions of inverse models, initialization via menus, better help messages, automatic selection of states from both joints and bodies, etc.
If not explicitly stated otherwise, the following description applies to new MBS library, even though a number of general properties also hold for the old MBS library.
15.10.2 Main MBS Object Classes The main parts of a multibody system model expressed using the MBS library are primarily constructed from the following three kinds of objects:
•
Frames--frames of reference, i.e., coordinate systems. One or more frames are attached to specific points at each body, depending on its geometry. The inertial system or world object, an instance of the Mul tiBody. World model, is a special global frame of reference which always has to be present in a model. All other frames must be able to relate to this frame through a sequence of coordinate transformations. Frames are described in more detail in Section 14.8.1, page 503, and in Section 15.10.4.1, page 592.
•
Bodies-rigid bodies with mass and inertia. Each body has one or more frames attached at certain points. Joint9--ll1echanical connections between pairs of bodies including constraints for the relative movements of the two bodies connected via a joint.
•
All objects in the new MBS library have geometry and color attributes needed for visualization and animation. Certain types of bodies may have more than one frame attachment point where additional elements can be connected. Such rigid bodies need to be constructed by rigidly connecting a basic body to additional frames via instances of fixed-frame coordinate transformation classes such as FrameTranslation, FrameRotation, etc. The local frames of a body must be related to the world object (inertial coordinate system) through the Modelica implicit force-field inner/outer connection mechanism (in the old library through explicit connections via joints). In this way, coordinate system transformations between the current frame and the inertial system are automatically obtained, and the gravity acceleration defined in the inertial system is automatically propagated to the body. The basic state variables (sometimes called generalized coordinates) are defined in either bodies or joints. Additionally, there are two kinds of objects of somewhat less importance that can be attached to a multibody system model:
• •
Force9-these classes are modeling 3-D vector versions of external force objects such as springs, torsion springs, dampers, etc., that can be connected to bodies and joints. Sensor9-these classes are sometimes useful to compute and observe certain variables that may not be directly available in the model classes.
Chapter 15 Application Examples 589
The different kinds of model classes are packaged into the sublibraries to be presented in the next section. Before going into more detail about the structure of the MBS library it can be instructiveto take a look at a very simple example: the FreeFlyingBody model.
15.10.3 A Simple Free-flying Body Model A free-flying body model is one of the simplest models possible to construct using the MBS library. It is useful to construct this kind of simple model in the MBS library for reasons of comparison with the simple point mass model we described in Section 5.8.3, page 177. Still, this is substantially more complicated than Newton's equations for a point mass in a gravity field, since the rotation of the body need to be taken into account. The connection structure of the model is depicted in Figure 15-55.
rrru world
.. body
Figure 15-55. Connection diagram for the free-flying body model using the new MBS library. The rnodel, expressed using the new MBS library, needs only two objects: the free-flying body itself, and the world object or inertial system that must be present in all models. The Modelica inner/outer implicit connection mechanism for force fields relates the body with its coordinates to the world coordinate system, which also enables the gravity force to act on the body. The gravity force is obtained by multiplying the body mass with the gravity acceleration defined in the world instance.
model FreeFlyingBody import Modelica.Mechanics.MultiBody.Parts; inner Modelica.Mechanics.MultiBody.World world; Parts.Body body(v_O_start={O,S,o}); end FreeFlyingBodYi We also show the same model in the old version of the MBS library for comparison (Figure 15-56).
o--.~
inertialSystem
freeMotion
body
Figure IS-56. Connection diagram for the free-flying body model using the old MBS library. That model needs three objects: the free-flying body itself, the inertial system, and a MultiBody. Joints. FreeMotion "joint" that relates the body coordinates to the inertial system, and enables the gravity force defined in the inertial system instance to act on the body. This joint in the old library is quite strange since it does not impose any movement constraints on the body. However, it is still needed for the above-mentioned reason.
model FreeFlyingBody "Version using the old MBS library" import ModelicaAdditions.MultiBody.Parts.*i import ModelicaAdditions.MultiBody.Joints.*; InertialSystem inertialSystem; FreeMotion freeMotion(v_rela(start={O,S,O}»i Body body(m=l) i equation connect (inertialSystem.frame_b, freeMotion.frame_a)i connect (freeMotion. frame_b, body. frame_a) ; end FreeFlyingBodYi A simulation of the FreeFlyingBody model computes the altitude above ground as a function of time, as shown in Figure 15-57.
590 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica simulate (FreeFlyingBody, stopTime=l)i plot(body.r_O[2]); 1.2 1.0 0.9 0.6 0.4 0.2
Figure IS-57. Altitude above ground for a free-flying body modeled and simulated using the MBS library.
15.10.3.1 Free-flying Body in Point Gravity It is easy to construct a model of one or more non-interacting free-flying bodies in a point gravity field, by setting gravityType=GravityTypes. PointGravity for the world object. The connection structure of such a model with two bodies is depicted in Figure 15-58.
body1
body2
Figure IS-58. Connection diagram for two free-flying bodies in the PointGravi ty model.
The model needs only three objects: the two free-flying bodies and the world object (the global inertial
system): model PointGravity import Modelica.Mechanics.MultiBody.Parts; inner Modelica.Mechanics.MultiBody.World world{gravityType=2,mue=1, gravitySphereDiameter=O.l)i Parts.Body bodyl(m=1,r_O_start={O,0.6,O}, v_O_start={1,O,O},sphereDiameter=O.1,I_l1=O.1,I_22=O.1 , I _ 3 3=O. 1 ) i Parts.Body body2(m=1,r_O_start={0.6,0.6,O}, v_O_start={0.6,0,0},sphereDiameter=0.1,I_ll=0.1,I_22=O.1,1_33=0.1); end PointGravitYi
A simulation of the PointGravi ty model with default animation enabled for the two bodies is shown in Figure 15-59. simulate (PointGravity, stopTime=4)i animate (PointGravity) ;
Figure IS-59. Animation of the pointGravity model with two bodies in a point gravity field using the new MBS library.
Chapter 15 Application Examples 591
15.10.4 Structure. of the MBS Library The classes in the MBS library are grouped into several sublibraries or packages, from which components can be picked when designing an MBS application model, as depicted in Figure 15-60. LJfoWII~
ff)1lhriet
,.mJwGlld.
tLJf~
~~g;::
.
4J.C]IrIIIf.e.. ~CJJ_t
!f t.-P. . . . f i·tlDA4MUt
. ....
•••••
t-+'~tcI'liwMtil;
dnmper
'. '.
r.t~O
\"
!t:::e¥d~~ : :.,
I!r:::. ~~fWtlU.
~""'';d''''
y
!wo I. .
l +,
r f 1·J,...UnM!n~IIhftir:.-aI i i~ lZJAttri6K
! oOtF......' t i.•"~~1JheIU
f,p;::
! 1·_J'-.nI~ il~~········ I.· .
1
...
.
••••••••••••••
.
•
Figure 15-60. Picking objects from the MBS sublibraries for use in an application model.
The MBS library is structured into the following sublibraries: •
• • • • •
• • •
•
MultiBody. World--this is a single class, not a package, defining the global inertial system model. Exactly one instance of World is necessary in each MBS application model to be simulated. MultiBody. Examples-a set of examples on how to use the MBS library. MultiBody. Forces-these are classes modeling 3D force elements such as springs and dampers. MultiBody. Frames--eontains type definitions (e.g. orientation object types) and functions (inlined) to transform rotational frame quantities. MUltiBody.lnterfaces---this subpackage contains classes (Frame, Frame_a, Frame_b) for coordinate systemframes, as well as partial base classes used by the other MBS sublibraries. MultiBody. Joints--elasses describing joints connecting two mechanical parts. Different kinds of joints have different constraints on the relative movements of the two connected parts. Also includes the subpackage MultiBody. Joints .Assemblies, which contains aggregated joint components for analytic solution of kinematic loops, and MultiBody. Joints. Internal, which has components used internally for analytic solution of kinematic loops, and which should not be directly referred to by the user. MultiBody. Parts---this subpackage primarily contains classes for defining rigid bodies which have mass and inertia. The package also contains massless fixed-frame transformation classes. MultiBody. Sensors---this subpackage contains classes for computing relative kinematic quantities between pairs of frames on bodies or joints. MultiBody. Types-definitions of types and constants that are used in the MultiBody library. The types have additional annotation choices definitions that define the menus to be built up in the graphical user interface when the type is used as parameter in a declaration. MultiBody. Visualizers--the classes in this subpackage support animation of shape objects that can be connected to frame connectors.
Moreover, classes from the following Modelica packages are often used together with the MBS library when modeling MBS applications:
592 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica • • •
Modelica.Mechanical.Rotational.lnterfaces. Modelica.Mechanical.Translational.lnterfaces. Modelica.Blocks.Interfaces.
The subsequent sections contain a more detailed overview that covers the most important classes of the MBS library. Most mechanical system models can be constructed from these. Several other classes are variations and optimized combinations of the basic classes. At this stage, the reader who is more interested in application examples may skip to Section 15.10.6, page 598, and if needed go back to this section later.
15.10.4.1 MultiBody.lnterfaces This sublibrary contains connector classes and base classes of the MBS library. Most of the base classes are superclasses of models defined in the other sublibraries, and are therefore not used directly by the modeler. In the old MBS library some of the base classes contain basic formulations of Newton's laws, previously described in Section 14.8.5.4, page 515. In the new MBS library these laws are instead stated in MultiBody. Parts. Body. The most important connector classes in MultiBody. Interfaces are Frame_a and Frame_b, which describe coordinate systems, i.e., frames of reference. •
Frame connector classes: Frame, Frame_a, and Frame_b
Each instance of Frame (or Frame_a or Frame_b, which are identical to Frame) describes a local coordinate system object. Instances of Frame_a are in the following often called frame a, and in Modelica code denoted by frame_a. Instances of Frame_b are denoted frame_b. The cut-force f (connector force applied at the connector) and cut-torque t (connector torque) vectors are resolved relative to the local coordinate system instance, e.g. frame_a, whereas r_O is resolved relative to the global inertial system (the world frame). The Modelica code of the Frame class appears as follows: connector Frame "Frame of a mechanical system" import 81 = Modelica.Slunits;
SI.position
r_O[3] "position vector from world frame to the connector frame origin, resolved in world frame"; "Orientation object to rotate the world frame Frames.Orientation R into the connector frame"; f[3] "Cut-force resolved in connector frame"; flow 5I.Force t[3] "Cut-torque resolved in connector frame"; flow 5I.Torque end Frame;
The cut-force (connector force) and cut-torque (connector torque) are applied at the connector position. As apparent from the above definition, Frame contains the following nonflow (i.e., potential) variables: •
The vector r _0 [3] from the inertial frame to the origin of the local connector frame.
•
The orientation object R (a rotation matrix R [3,3) computed from Euler/Cardan angles, see Section 14.8.4.2, page 507, or from quaternions, see Section 14.8.4.3, page 509) for rotating the inertial frame to the same orientation as the local connector frame. All orientation objects are instances of MUltiBody . Frames .Orientation, see Section 15.10.4.2 below.
The rotation matrix can be used for transformation of vectors between frames: •
To map a vector v expressed in the local connector frame to the global inertial frame, we need to apply the inverse R -I = R T , i.e., R T V expressed in the global inertial frame. This is the same as calling resolvel (R, v), transforming from frame 2 (the local frame) to frame 1 (the global inertial frame). R is often available in the local frame (frame_a. R). See also Section 15.10.4.2.
•
To map a vector x from the inertial frame to the local frame, apply R, i.e. Rx. This is the same as calling reselve2 (R, w), transforming from frame 1 (the global inertial frame) to frame 2 (the local frame). R is often available in the local frame (frame_a. R). See also Section 15.10.4.2.
Chapter 15 Application Examples 593
According to Modelica semantics, if connectors from several objects are connected, the nonflow variables with the same name become constrained to have identical values through equality equations. This corresponds to a common local coordinate system used by all model components connected at the same frame instance. The Frame_ a connector class also contains two flow variables: • •
The resultant force vector f [3] acting at the origin of frame a. The resultant torque vector t [3] acting at the origin of frame a.
According to the Modelica semantics, if 11 connectors from several objects are connected together, the sum of all flow variables is equal to zero, i.e., the sum of the resultant forces connected at a specific point is zero: f 1+f2+ ...+f"=0. For comparison we also show the Frame_a definition from the old MBS library: connector Frame a "Frame a of a mechanical element, from old MBS library" input Slunits.Position rO(3] "Position vector from inertial system to frame origin, resolved in inertial system"; Real S[3,3] nTransformation matrix from frame_a to inertial system"; Slunits.Velocity "Absolute velocity of frame origin, v Ial resolved in frame_a"; w [3] SIunits.AngularVelocity "Absolute angular velocity of frame_a, resolved in frame a"; SIunits.Acceleration a (3] "Absolute acceleration of frame origin, resolved in frame_a"i SIunits.AngularAcceleration z[3] "Absolute angular acceleration of frame_a, resolved in frame_a"; flow SIunits.Force f [3] ; flow SIunits.Torque t [3] ; end Frame_a;
The definition of Frame _a from the old library also contains translational and angular velocities and accelerations, which in the new library are defined in the Body class. The rotation matrix R of the new library is the inverse (i.e., transpose for an orthogonal matrix) of the rotation matrix S from old library, i.e., R =S-1 = ST, (see also Section 14.8.4.1, page 506). Apart from the frame classes just presented, there are also partial superclasses of joints, force elements, sensors, and visualizers. See Section 16.8.5, page 636. To summarize, the following classes are available in the Modelica. Interfaces sublibrary: •
Frame, Frame_a, Frame_b, PartialElementaryJoint, PartialForce, PartialLineForce, PartialAbsoluteSensor, PartialRelativeSensor, PartialVisualizer, PartialTwoFrames.
15.10.4.2 MultiBody.Frames The subpackage MultiBody. Frames contains type definitions and functions to transform rotational frame quantities. The basic idea is to hide the actual definition of an orientation in this package by providing the type Orientation together with functions operating on instances of this type. These functions typically are inlined by most Modelica environments, and therefore give no call overhead. See Section 16.8.9, page 637, for a complete list with examples of all transformation functions.
15.10.4.3 MultiBody.Parts This package mainly contains classes for defining rigid bodies which have mass and inertia. It is often quite convenient to use the BodyBox or BodyCylinder model classes, since their geometries are rather simple and the inertia matrix is automatically computed from the size parameters of the box or cylinder. Additionally, the geometry and color properties of the box or cylinder can be used to automatically obtain 3D graphic animations of simulated multibody systems.
594 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica The package also contains massless frame transformation elements. The following classes are available: •
Body-a rigid body with one frame_a connector, as well as mass, inertia tensor, and relative center-of-mass properties, and default geometry with a cylinder and a sphere at the center of mass, see Figure 15-61 for different shapes. This class is the basic bodyclass, containing Newton's equations of motion expressed in the body local coordinate system, as well as appropriate coordinate transformations. See Section 14.8.5.4, page 515, for a derivation of some of the formulations of Newton's equations used in this class.
•
BodyShape--same as Body, but also containing both frame_a and frame_b connectors, and a fixed distance vector r between those frames. This body can have a more general shape, e.g. user23 defined as a DXF -file or selected from a set of predefined shapes according to the setting of the parameter shapeType: "box", "sphere", "cylinder", "cone", "pipe", "beam", "gearwheel", or "spring", see Figure 15-61.
•
BodyBox-Similar to BodyShape, but has a box-shaped geometry and color properties. The inertia matrix, sometimes called the inertia tensor, is automatically defined from the density and the shape of the box, which also may be hollow-see Figure 15-61.
•
BodyCylinder--similar to BodyBox, but with cylindrical geometry. The cylinder may also have a hole, i.e., a pipe-s-see Figure 15-61 and Figure 15-62.
•
Fixed-frame fixed in the world frame at a given position. Default geometry is a cylinder if shapeType=" cylinder".
•
FixedTranslation--fixed relative translation denoted by the parameter vector r [3] from frame_a to frame_b, resolved in frame_a. An object of this class can be viewed as a massless bar between these two points. Default geometry is a cylinder.
•
FixedRotation--fixed translation and fixed rotation of frame_b with respect to frame_a. Default geometry is shapeType=" cylinder" .
..... , •.• '0.
The default shapes for Body, BodyShape, BodyBox, and BodyCylinder are shown in Figure 15-61 .
Figure 15-61. Default visualization shapes for Body, BodyShape, BodyBox, and BodyCylinder respectively. Different shapes depending on the value of the parameter shapeType are depicted in Figure 15-62. bo~
.phert. e,.lInder
f....
plpt
ham ctar,,'hftl .prtq
Figure 15-62. Visualization body shapes for BodyShape depending on the value of shapeType.
15.10.4.4 MultiBody.Jolnts The Mul tiBody . Joints package contains model classes describing joints connecting two mechanical bodies with various constraints on the relative movements of the connected bodies.
23
AutoCad geometry file format.
Chapter 15 Application Examples 595
Prismatic
ActuatedPrismatic
Planar
Spherical
Revolute
ActuatedRevolute1
Cylindrical
Universal
FreeMotion SphericalSpherical UniversalSpherlcal
Figure 15-63. Schematic pictures of the 11 different kinds of joints available in the MBS library.
The following is a complete list of the joint classes provided by the MultiBody. Joints sublibrary, starting from those with one degree of freedom up to the FreeMotion joint with six degrees of freedom and no motion constraints at all. •
•
•
•
•
• • • • • •
Pr i sma t i c--a joint for sliding translational motion in one direction, giving one translational degree of freedom and two nonflow (i.e., potential) state variables. This class has connectors frame_a and frame_b, as well as a Real parameter vector n [3] (fixed in frame_a) that defines the direction of translation when frame b moves relative to frame a. The variable s contains the relative distance between frame b and frame a. ActuatedPrismatic--a prismatic joint that has two additional l-dimensional mechanical flanges (the flange axi s represents the driving flange and flange bearing represents the bearing) where it can be driven with elements from the Modelica. Mechanics. Translational library. Revolute--a joint that allows rotation relative to one axis (see Figure 14-36, page 518, and Figure 14-30, page 511). The basic state variable is the rotation angle phi, which gives one rotational degree of freedom and two nonfIow states, i.e., potential state variables without the flow prefix. This class has the connectors frame_a and frame_b, as well as a Real parameter vector n [ 3 ) . This unit vector defines the direction of the axis of rotation when frame b rotates around frame a. ActuatedRevolute-a revolute joint that has two additional l-dimensional mechanical flanges (flange axi s represents the driving flange and flange bear ing represents the bearing) where it can be driven with elements of the Modelica. Mechanics. Rotational library. Cylindrical-a joint for independent rotation and sliding motions, with two degrees of freedom and four nontlow states (i.e., potential state variables). The frame_b rotates around and translates along axis n which is fixed in f rame_a. Uni versal--a joint that allows rotation relative to two rotation axes giving two degrees of freedom, and four nontlow states. Planar-a joint for arbitrary translational and rotational motion on a plane, with three degrees of freedom and six nontlow states. Spherical-a joint for arbitrary rotational motion around a fixed point. This joint has three degrees of freedom, three constraints, and no nonflow states. FreeMot ion-a joint that allows relative motion with no constraints, as if there were no joint at all, giving six degrees of freedom and twelve nontlow states from the attached two frames. SphericalSpherical-a spherical aggregated joint consisting of two spherical joints connected by a rod with an optional point mass in the middle. UniversalSpherical-a spherical aggregated joint with a universal joint at frame_a and a spherical joint at frame_ b which are connected together with a rigid rod.
The one-degree-of-freedom JOints, i.e., Revolute, ActuatedRevolute, Prismatic, and ActuatedPrismatic, can be dynamically locked and unlocked during the movement of the bodies in a multibody system. This facility can be used to model brakes, clutches, stops, or sticking friction. Locking
596 Peter Fritzson Principles of Object-OrientedModelingand Simulation with Modelica is modeled using classes such as Clutch or Friction of the Modelica.Mechanics.Rotational library. Instances of these classes can be attached to joints at the axis connector of type Flange_a.
15.10.4.5 MultiBody.Joints.Assemblies This subpackage of MultiBody. Joints contains aggregations of joints for analytic loop handling. These joints are primarily designed to be used in kinematic loop structures. Every component consists of three elementary joints. These joints are combined such that the kinematics of the three joints between frame_a and frame_b are computed from the movements of frame_a and frame_b, i.e., there are no constraints between frame_a and frame_b. This requires solving a non-linear system of equations, which here is performed analytically, i.e., when an analytic solution exists, it is computed efficiently and reliably. The assembly joints in this package are named JointXYZ where XYZ are the first letters of the elementary joints used in the component, in particular: p-prismatic joint, R-revolute joint, s-spherical joint, and u-universal joint. The currently available joints are: JointUPS, JointUSR, JointUSP, JointSSR, JointRRR, and JointRRP. See also Section 16.8.7, page 636.
15.10.4.6 MultiBody.Forces Force elements, such as springs and dampers, can be attached between two frame connectors of arbitrary MBS objects such as bodies, joints, or other elements. The following 3D force elements are available in the Multibody. Forces sublibrary (see also Section 16.8.8, page 637): •
WorldForce, WorldTorque, WorldForceAndTorque, FrameForce, FrameTorque, FrameForceAndTorque,LineForceWithMass,Spring,Damper,SpringDamperParallel, SpringDamperSeries.
Gravitational forces for all bodies are taken into account by having the gravitational acceleration of the world object (the inertial system), i.e., an instance of MultiBody. World, as a nonzero value. The default is the gravitational acceleration at the surface of the earth. The propagation to all objects with mass is via implicit connections via the Modelica inner/outer mechanism (see Section 5.8, page 173). It is easy for a user to introduce new force elements as subclasses, e.g. from the model class MultiBody. Interfaces. PartialLineForce. Moreover, one-dimensional force elements from other (non-MBS) libraries such as the Modelica. Mechanics. Translational can also be used.
15.10.4.7 MultiBody.Sensors This subpackage contains two classes for computing relative quantities between pairs of frames. The following classes are available: •
RelativeSensor,Power
The RelativeSensor class can compute any relative kinematic quantity (position, velocity, acceleration, angular velocity, angular acceleration) between two frames, whereas the Power class measures power flowing from frarne_a to frame_b.
15.10.4.8 MultiBody.Types This subpackage defines types and constants that are used in the MultiBody library. The types have additional annotation choices definitions that define the menus to be built up in the graphical user interface when the type is used as a parameter in a declaration.
15.10.4.9 MultiBody.Visualizers The subpackage Visualizers contains definitions needed for visualizing 3-dimensionaI shapes. These definitions are the basis for the animation features of the MultiBody library, and include the shape types depicted in Figure 15-62.
Chapter 15 Application Examples 597
15.10.5 Using the MBS Library There are several approaches to the construction of an MBS model of a multibody system using a collection of Modelica classes. The following are three common approaches: •
Automatic translation from a CAD model to Modelica code.
•
Traditional manual stepwise refinement, starting from a kinematic outline, and gradually developing a complete MBS model.
•
A physical component top-down design approach starting with the main system structure including bodies and joints picked from the MBS library, and gradually introducing additional details, visualization aspects, and sensor elements.
If a CAD-to-Modelica translator is used (Section 15.11, page 611), there is no need for manual construction of the MBS model. In general, the construction process depends on the context, in particular what type of analysis should be applied to the model, and whether simulation efficiency should be allowed to influence the model structure. Here we advocate the top-down physical component approach, previously described in Section 15.10.5.2, page 597.
15.10.5.1 Kinematic Outline Approach Most traditional textbooks in multibody system design suggest a process of stepwise refinement of an MBS model, first using a so-called kinematic outline (kinematic skeleton), and later introducing details of model dynamics and visualization based on this outline. This approach is also possible using the Modelica MBS library, but is harder to use than the approach described in the next section. The kinematic outline is a graph consisting of nodes, with one or more connectors belonging to each node, and edges drawn between the connectors. The nodes of a kinematic outline of a multibody system consist of the inertial world frame, massless elements (remember that we have not yet added dynamic properties such as mass and inertia), coordinate frame transformations, and joints that define the kinematic features of the system. The edges of the outline are connections between those nodes attached at coordinate frame connectors. Given the angles of rotation for revolute joints and the length of translation for prismatic joints, or a combination of those in other joints, the Modelica MBS library classes can compute the position of any frame connector using the coordinate transformations between adjacent frame connectors.
15.10.5.2 Top-down Physical Component Approach The top-down physical component approach is similar to the kinematic outline approach, with the difference that here we can use real body models with mass and inertia, including dynamic aspects such as forces and their influence. This approach is the most straightforward since there already exist several easyto-use body classes in the Modelica MBS library.
15.10.5.3 Multibody System Graph The multibody system graph is a graph consisting of nodes with connection points (e.g. frame connectors) and edges drawn between the connectors. The nodes of the graph correspond to the global reference frame, the bodies of the system, and the elements defining coordinate frame transformations. The edges of the graph represent interactions between the bodies, in particular joints. In many cases these graphs are acyclic, and represent a tree structure. However, there are models that give rise to graphs with loops, socalled kinematic loops. These are in most cases handled automatically, but sometimes may require special treatment, e.g. see Section 15.10.7, page 601.
598 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica 15.10.5.4 Connection Rules for the Old MaS Library The elements of the old multi body library cannot be connected together in an arbitrary way. The reason is to allow the Modelica translator to generate very efficient simulation code by forming a tree-structured connection graph implying an well-defined efficient computation order for equation solution. This is not needed in new library. The following connection rules apply to the old MBS library, which makes that library much harder to use than the new library where these restrictions have been removed: •
Ordinary joint objects (also called tree joints, not cutjoints), body objects, and the inertial system object have to be connected together so that the frame_a of an object (filled with blue color) is always connected to a frame_ b of another object (unfilled color). The connection structure has to form a tree with the inertial system as root, e.g. as depicted in Figure 15-64.
•
CutJoint (special joints to break kinematic loops when using the old MBS library), force, and sensor objects always have to be connected between two frames of a tree joint, a body, or an inertial system object. For example, in the old MBS library it is not allowed to connect two force objects together.
Figure 15-64. Joints in a tree-shaped connection structure implied by the connection rules of the old MBS library. Fortunately we need' not consider these complicated rules when using the new library. The reason is that the new library uses the new Modelica equation operators for overconstrained connection-based equation systems as described in Section 8.6, page 274.
15.10.6 Developing an Example Model--a 3D Double Pendulum In this section an idealized model of a double pendulum is developed. This pendulum consists of two arms linked by a hinge. The upper box is linked by a hinge to a nonmovable platform, i.e., an inertial system. Both arms can move in the x-y plane. The corresponding kinematic outline consists of two revolute joints, one frame translation and one inertial system, as depicted in Figure 15-65.
revoluteI
body1
Figure 15-65. Mechanical structure of the double pendulum, where body2 is an instance of Body and body! is an instance of a body class with two connectors (BodyShape, BodyBox, or BodyCylinder).
Chapter 15 Application Examples 599 The motion of a dynamic system cannot be defined just by its kinematic outline, since an outline does not contain objects with mass. Fortunately, the body classes in the MBS library have been designed to represent mechanical objects with mass. The Body class (instance body2 in Figure 15-65) has the single connector frame_a, whereas the classes BodyShape, BodyBox, and BodyCylinder have two connectors: frame_a and frame_b, which is apparent for the instance bodyl in Figure 15-65. The following parameters also need to be supplied by the modeler: • • •
•
The mass m of the body. The vector r _ CM [3 J denoting the position of the center of mass with respect to frame_a. Elements 1_11, 1_22, 1_33, 1_21, 1_31, 1_32 of the inertia matrix with respect to the center of mass, with default values 0 if not specified, except for the diagonal elements 1_11, 1_22, 1_33 which have default values 1 . e - 3. The parameter vector r [3] from the origin of frame_a to frame_b with respect to frame_a, for instances of the body classes with two frame connectors.
The inertia matrix I [3 3] is declared as a variable in all body classes, and defined from the above inertia matrix elements through a matrix equation. This 3x3 matrix containing nine elements is defined by the previously mentioned six inertia matrix numbers since it is symmetric: I
In the double pendulum example, two bodies can be added to the kinematic outline. Since the description of class Body contains the distance between its frame_a and its center of mass, such objects can be directly connected to the connector frame_b of revolute joints revolutel and revolute2, as depicted in Figure 15-65. Modelica class instances, such as bodyl, body2, revolute1, etc., have attributes that can be modified. For instance, Body has attributes that define mass, inertia tensor, and the location of its center of mass relative to the local coordinate system. (r_ ca), Instances of Revol ute (revolute joint rotating around an axis) have an attribute n that defines the direction of axis of rotation. Instances of Prismatic (prismatic joint for sliding motion) have an attribute that specifies the direction of the allowed translation. For a FrameTranslation instance, the relative position vector from frame_a to frame_b is specified by the vector r. Several important parameters need to be defined for a double pendulum: Ll and L2 are the lengths of the arms. Their masses are M. The center of mass of the first arm is located at the distance Ll /2 from the first rotation point. The rotation axes of the revolute joints are directed along the z-axis defined by the 1}. direction unit vector {o I
°,
15.10.6.1 Adding Geometrical Shapes: Cylindrical Bodies To produce visualizations including 3-D animations we need geometry and color attributes to the bodies in a multibody system model in addition to those necessary for simulation. The MBS library contains the classes BodyBox, BodyShape, and Bodycy"linder with associated geometry and color information. In the following examples we will use the class BodyCylinder which describes a body with cylindrical shape. It has a connector frame_a which indirectly is attached (via implicit connections, see Section 5.8, page 173) to an instance of World, and a frame_b connector which does not always need to be attached. The class also introduces the following parameters that specify the geometry and color of the cylinder needed for visualization. As usual all position parameters are relative to the local frame_a coordinate system, except r_O which is expressed in the inertial (world) coordinate system. The following is a subset of the available parameters for BodyCylinder:
600 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
•
• • • • •
•
The parameter vector r [3] from the origin of frame_a to frame_b expressed in frame_a. By default the cylinder has two circular surfaces with centers in frame_a and frame_b, placed perpendicular to the line between frame_a and frame_b. The parameter vector r_shape [3] from the origin of frame_a to the origin of the cylinder, i.e, the center of the left circular surface of the cylinder. The parameter diameter specifies the radius of the cylinder (0.1 [m] by default). There is also an innerDiameter parameter(usually 0), for cylinders with holes, i.e., pipes. The parameter density specifies the density of the cylinder (7.7 [g1cm3] by default-a common value for steel). The parameter m specifies the mass of the cylinder, automatically computed from the density and volume given by the length and diameter(s )of the cylinder. The parameter array color [3] (of type MultiBody. Types. Color=Integer [3]) specifies the color the shape, using values for red, green, blue components (RGB). All coefficients are between 0 and 255. Different shapes have different default colors. The parameter length, which is the length of the cylinder, and length_direction ,which is a vector (r - r_shape) in the direction of the cylinder axis. Both of these are defined from the above parameters by equations.
of
15.10.6.2 A Double Pendulum Consisting of Two Cylinders A double pendulum where the two arms have cylindrical shape is depicted in Figure 15-66 below.
Figure 15-66. A 3D visualization from a 3D animation of the double pendulum with cylindrical geometries of the bodies. The inertial system frame (world object) is shown at the top.
The corresponding Modelica model DoublePendulumCylinders for the double pendulum with cylindrical bodies uses an instance of BodyCylinder instead of Body for the second pendulum arm. This is apparent in the connectiondiagram of the model shown in Figure 15-67.
Figure 15-67. The Modelicadiagram for the double pendulum consistingof two cylinders.
The DoublePendulumCylinders class follows below, including the declaration of the pendulum arms as instances of BodyCylinder: model doublePendulumCylinders import Modelica.Mechanics.MultiBody.Partsi import Modelica.Mechanics.MultiBody.Jointsi import Modelica.Mechanics.MultiBody.Types; parameter Real Ll=O.3 "length of 1st arm"; parameter Real L2=O.4 "length of 2nd arm";
Chapter 15 p..pplication Examples 601
parameter Real D=O.l "diameter"; inner Modelica.Mechanics.MultiBody.World world; Joints.Revolute revolutel; Joints.Revolute revolute2; Parts.BodyCylinder bodyl(r={Ll,O,O},diameter=D); Parts.BodyCylinder body2(r={L2,O,O},diameter=D,color={255,255,O}); equation connect (world.frame_b, revo!utel.frame_a); connect{revolutel.frame_b, bodyl.frame_a); connect(revolute2.frame_b, body2.frame_a); connect{bodyl.frame_b, revolute2.frame_a); end doublePendulumCylinders; We simulate and plot the example: simulate (DoublePendulumCylinders, stopTime=l) plot ({body2.body.frame_a.r_O [2] , body2.frameTranslation.frame_b.r_O[2]})
body2.body.frame_a.r_O(2) body2.frameTranslation.frame_b.r_O[2] ~
-0.1
"
0.2
0.4
0/6
1
t
I
~
I
-0.2
I '---
-0.3
-
I
-0.4 -0.5 -0.6 -0.7
Figure 15-68. Vertical positions of two parts of the double pendulum connected by a joint (variable body2. frame_a. r_O [2]) and the tip of the second body (variable body2. frame_b. r_O [2]).
15.10.7 Kinematic Loops A connection chain consisting of joints, bodies, and coordinate transformations may form a circular dependency loop, also called closed kinematic loop. The PendulumLoop2D example in Figure 15-69 below, with connection diagram in Figure 15-71, shows a system with a single closed kinematic loop. The upper rod (a cylinder with small radius) is fixed whereas the three other rods are connected by revolute joints. The whole system behaves like a kind of pendulum. >-.
z
Figure 15-69. 3D visualization and animation of the PendulumLoop2D example.
602 Peter Fritzson Principles of Object-OrientedModeling and Simulation with Modelica The Modelica MBS library uses equation operators for overconstrained connection-based equation systems (see Section 8.6, page 274) to allow Modelica environments to automatically determine where to "break" the kinematic loop, Le., to remove superfluous equations for cases when there otherwise would be more equations than variables. This is illustrated for the four-bar mechanism depicted in Figure 15-70, which is a kinematic loop consisting of 6 revolute joints, 1 prismatic joint, and 4 bars, that is often used as basic construction unit. The example demonstrates that usually no special knowledge of the user is needed to handle kinematic loops. Just connect the joints and bodies together corresponding to the real physical system.
fev
b2
Z...._ ......_ _.......
Figure IS-70. Connection diagramand 3D animation visualization of the four-barkinematicloop example from Mul tiBody. Examples. Loops. Fourbarl. However, at the current state-of-the-art this analysis cannot be made automatically for two-dimensional (planar) kinematic loops (such as the PendulumLoop2D example). Planar loops have the difficulty that by infinitesimal changes of parameters such as the axis of rotation of a revolute joint in the loop, the loop has fewer degrees of freedom and is usually locked. The symbolic algorithms currently used to transform the equations are based on structural information and do usually not utilize numerical values. Therefore, these algorithms cannot distinguish the "planar" loop case from the "3-dimensionallocked" loop case. In order to model such loops correctly, the user needs to supply a hint by setting the attribute planarCutJoint to true through a modification for one revolute joint that is used to break the circular dependency (also available in the Advanced menu of the revolute joint). The revolute4 instance is an example of such a joint, visible in the connection diagram of PendulumLoop2D depicted in Figure 15-71 below. This option sets the connector-force in the direction of the axis of rotation, as well as setting the connector-torques perpendicular to the axis of rotation at this joint to zero and thereby makes the problem mathematically well-formed.
Figure 15-71. Connectiondiagram for the PendulumLoop2D model.
Chapter 15 Application Examples 603
Specifying the initial state can also be tricky for a mechanical system with circular dependencies. In order to specify a valid initial state for a mechanical system that is a planar kinematic loop, a hint needs to be given to the Modelica simulator by selecting a joint with a state variable that has an independent start value. The parameter startValueFixed is set to true to mark this joint (revolutel), for which an appropriate start value also should be supplied. The Modelica code of the PendulumLoop2D model with these attributes specified follows below. model Pendu!umLoop2D import Modelica.Mechanics.MultiBody.Partsi import Modelica.Mechanics.MultiBody.Jointsi import Modelica.Mechanics.MultiBody.Types; inner Modelica.Mechanics.MultiBody.World world; Parts.BodyCylinder bodyl(r={1,O,O},diameter=O.1,color={125,125,12S}); Parts.BodyCylinder body2(r={O.S,O,O},diameter=O.1); Parts.BodyCylinder body3(r={-O.9,O,O},diameter=O.1,color={O,25S,O}); Parts.BodyCylinder body4(r={O.5,O,O},diameter=O.1); Joints.Revolute revolutel(startValuesPixed=true,phi_start=-60); Joints.Revolute revolute2; Joints.Revolute revolute3; Joints.Revolute revolute4(planarCutJoint=true); equation connect (world. frame_b, bodyl.frame_a); connect (bodyl.frame_b, revolutel.frame_a)i connect (revo!utel.frame_b, body2.frame_a)i connect (world.frame_b, revolute3.frame_a)i conn~ct(revolute3.frame_b, body4.frame_a); connect (body2. frame_b, revo!ute2.frame_a); connect (body3.frame_a, revolute2.frame_b); connect(revo!ute4.frame_b, body3.frame_b); connect(body4.frame_b, revolute4.frame_a); end PendulumLoop2D;
We simulate and plot the example: simulate (PendulumLoop2D, stopTime=l) plot (revolutel.angle) -1. 0
-1.5 -2.0 -2.5
0.2
0.4
0.6
0.8
Figure 15-72. The relative angle (in radians) of the joint revolutel stored in variable revolutel. q.
15.10.8 Interfacing to Non-MBS Models and External Force Elements When constructing a model of a multidomain system that includes a mechanical multibody subsystem as well as parts from other application domains, all these parts need to be connected through appropriate interfaces. The MBS library provides three main kinds of connector classes: •
Connector classes Multibody. Interfaces. Frame_a and Frame_b, for connecting external forces described by 3D force elements from Multibody . Forces.
•
Connector classes Rotational. Interfaces. Flange_a and Flange_b, for connecting ID rotational elements from the Modelica. Rotational library.
604 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica •
Connector classes Translational. Interfaces. Flange_a and Flange_b, for connecting ID translational elements from the Modelica. Translational library.
In the following sections we give examples of interfacing a multibody model to external force elements and model elements using these three kinds of connectorclasses. 15.10.8.1 Pendulum with Applied External Forces
Any MBS object with coordinate system connectors of types Multibody. Interfaces. Frame_a or Frame_b, can be connected to an instance of an external force or torque element from the set of model classes in Multibody. Forces. Such an external force or torque element is applied to a corresponding point on the relevant body. The ExtForcePendulum example model depicted in Figure 15-73 below includes a force acting at the end of the pendulum in the direction of the local y-axis, i.e., perpendicularto the pendulumrod. When a force is appliedto the pendulumit does not oscillate; it rotates instead.
constant1
worldForce1
Figure 15-73. Connection diagram for the ExtForcePendulum example model of an external force acting on a pendulum. The Modelica class ExtForcePendulum includes an external force element instance worldForcel acting on the pendulum. The size and direction of the external force is determined by the constant vector constantl here given in the body local coordinate system of the frame_b connector. This constant vector must be transformed into the inertial world coordinate system before setting equal to worldForcel. inPort and thus determining the external force vector. This is done by applying the inverse R- 1 of the rotational transformation matrix worldForcel. frame_b. R to the vector constantl . y via the call to the function Frames. resolvel. model Ext Force Pendulum import Modelica.Mechanics.MultiBody.Partsi import Modelica.Mechanics.MultiBody.Jointsi import Modelica.Mechanics.MultiBody.Forcesi import Modelica.Mechanics.MultiBody.Frames; import Modelica.Blocks.Sourcesi
inner MultiBody.World world; Joints.Revolute revolutel; Parts.BodyCylinder bodyl(r={1,O,O},diameter=O.2)i Forces.WorldForce worldForcel; Sources.Constant constantl(k={O,1190,O})i equation connect (world.frame_b, revolutel.frame_a)i connect (revolutel.frame_b, bodyl.frame_a) i connect (bodyl.frame_b, worldForcel.frame b)i
worldForcel.force = Frames.resolvel(worldForcel.frame_b.R,constantl.y)i end ExtForcePendulumi
We simulate and plot the example: simulate (ExtForcePendulum, stopTime=7) plot (revolutel.w) i
i
Chapter 15 Application Examples 605
/
50
40 30 20
10 _ _ _ _ L-~~-L~--.=_c_____....J_~~'____L_~ _ _~.L_.._~
1
2
4
5
6
t
7
Figure 15-74. The angular velocity of the pendulumcaused by the sudden applicationof a constant force. The force vector is attached to the pendulum tip.
15.10.8.2 Pendulum with Damped Torsion Spring Connected via 10 Rotational Flanges The Modelica. Rotational library describes a number of modeling elements for one-dimensional rotational motion. These elements can be attached to the Revolute joint from the MultiBody library. A torque, a torsion spring, a torsion damper, or any other rotational component can be attached to one of the connectors of type Rotational. Flange_a or Flange_b of the revolute joint. The example in Figure 15-75 illustrates a one-dimensional damped torsion spring (springDamperl) from the Rotational library attached to the revolute joint (revolutel) of a simple pendulum.
world
Figure 15-75. Connection Diagram for a pendulum with a non-MBS external force element springDamperl.
The flange_ b connector of the springDamperl damped torsion spring is attached to the axi s connector of the revolutel joint of the PendulumWithDampedSpring model. The parameter springDamperl.phi_relO describes the unstretched spring angle. In this model the pendulum performs oscillations with gradually decreasing amplitude and converges to the position corresponding to the angle 1 [Rad], which is the default value of phi_reIO. model PendulumWithDampedSpring import Modelica.Mechanics.MultiBody.Parts; import Modelica.Mechanics.MultiBody.Joints; import Modelica.Mechanics.MultiBody.Forces; import Modelica.Blocks.Sources; import Modelica.Mechanics.Rotational; inner Modelica.Mechanics.MultiBody.World world; Parts.BodyCylinder bodyl(r={l,O,O},diameter=O.2); Joints.ActuatedRevolute revolutel; Rotational.SpringDamper springDamperl(c=500,phi_reIO=l,d=170); equation connect (world.frame_b, revo!utel.frame_a); connect(springDamperl.flange_a, revolutel.bearing); connect(springDamperl.flange_b, revolutel.axis); connect(revolutel.frame_b, bodyl.frame_a)i end PendulumWithDampedSpring;
We simulate and plot the example: simulate (PendulumWithDampedSpring, stopTime=3)i
606 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
4.---......--..------..----~-t
0.5
1
1.5
2
2.5
3
-0.2 -0.4 -0.6
-O.B
Figure 15-76. The oscillation of the vertical position (bodyl. frame_b. r_ 0 [2]) of the pendulum tip is gradually reduced due to the effect of the springdamper.
.
15.10.8.3 Pendulum with Rotation Angle Steering Sometimes there is a need to rotate the body connected to the joint to a certain desired angular position. This can be done by the use of an instance of the class Rotational. Posi tiona In the example pendulum with rotation angle steering depicted in Figure 15-77, the specified value of the angle is given by the stepl instance of the Step signal source from the Modelica. Block. Sources sublibrary. This value is converted to an angular position by the positionl component. ..
.~
I~~ step1
phi'
position 1
Figure 15-77. Connection Diagram for the PendulumRotationalSteering example.
The Position class from the Modelica. Rotational library filters the input reference angle signal to become smooth. This is needed since the second derivative of the filtered curve is used to compute the reference acceleration of the flange. The angular position of the joint is (partly) computed from this acceleration. For filtering, the Posi tion class uses a second order Bessel filter. The critical frequency (also called cut-off frequency, in [Hz]) of the filter is defined via the parameter f_crit. This value should be selected to be higher than the essential low frequencies of the signal to preserve its main characteristics while eliminating irrelevant higher frequency noise. model PendulumRotationalSteering import Modelica.Mechanics.MultiBody.Parts; import Modelica.Mechanics.MultiBody.Jointsi import Modelica.Modelica.Blocks.Sources; import Modelica.Mechanics.Rotational; inner Modelica.Mechanics.MultiBody.World world; Parts.BodyCylinder bodyl(r={l,O,O})i Joints.ActuatedRevolute revolutel; Sources.Step stepl(startTime={O.5}); Rotational.Position positionl(f_crit=5); II Filter cut-off f_crit equation connect (revolutel.frame_b, bodyl.frame_a); connect (world.frame_b, revolutel.frame_a); connect (stepl.y, positionl.u); connect(positionl.flange_b, revolutel.axis); II Connect positionl to axis end PendulumRotationalSteering;
Chapter 15 Application Examples 607 We simulate and plot the example: simulate (PendulumRotationalSteering, stopTime=l}; plot(bodyl.frame_b.r_O[2]) ; 0.8 0.6 0.4 0.2 __ O. B
-+-_~~~~-L-~_~
0.2
0.4
0.6
~~
t
1
Figure 15-78 The vertical position (body t . frame_b. r_O [2]) of the pendulum tip. At time=O. 5 the desired angular position of the revolute joint becomes t.O radian.
15.10.8.4 Computational Steering of a Pendulum through a PO controller Another way to steer the rotational behavior of a joint is to set up a Proportional Derivative (PD) controller. Instead of computing a specified angular position as in the pendulum rotational steering class of the previous section, the rotational PD controller creates a torque, which acts on the joint. It actually behaves like a motor-driven actuator. The parameters k and d of the PD controller can be tuned in order to adjust the reaction speed and power.
~
bIj-O . step1
etrl
Figure 15-79. The PendulumWithPDController connection diagram, including a proportional derivative (PD) controller denoted ctrl. The PendulumWithPDController class together with the RotationalPDController class used for controlling rotational movement: model PendulumWithPDController import Modelica.Mechanics.MultiBody.Parts; import Modelica.Mechanics.MultiBody.Joints; import Modelica.Blocks.Sources; inner Modelica.Mechanics.MultiBody.World world; Parts.BodyCylinder bodyl(r={1,O,O},diameter=O.2); Joints.ActuatedRevolute revolutel; Sources.Step stepl(startTime={O.5}); RotationalPDController ctrl(k=5000,d=500); equation connect(revolutel.frame_b, bodyl.frame_a); connect (stepl.y, ctrl.u); connect (ctrl.flange_b, revolutel.axis); connect(world.frame b, revolutel.frame a); end PendulumWithPDCont;oller model RotationalPDController "Input signal acting as reference value for angle, gives external torque on a flange" import Modelica.Blocks; import Modelica.Mechanics.Rotational;
608 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
parameter Real k=li parameter Real d=li Blocks.1nterfaces.Real1nput Ui Rotational.lnterfaces.Flange_b flange_bi equation flange_b.tau = k*(flange_b.phi-u)+d*der(flange_b.phi) end RotationalPDControlleri
i
0.8 0.6
0.4 0.2 0.2
0.4
.6
0.8
-0.2
Figure IS-80. The vertical position (body1. frame_b. r_O [2) of the pendulum tip of the controlled pendulum. At time=O. 5 the desired angular position of the revolute joint becomes 1.0 radian and the pendulum smoothly rotates to this position.
15.10.9 Connecting Force Elements-a Triple Springs Model This example demonstrates that 3-dimensional line force elements (e.g. MultiBody. Forces. Spring instances) can be connected together in series and in parallel without having a body with mass at the connection point, which would be required by the old MBS library and by most multi-body simulation programs. Besides the modeling inconvenience, a small mass between the springs would have the disadvantage of causing the resulting equation system to become stiff (see Section 18.2.1.5, page 671). The connection structure and 3D view of the model are shown in Figure 15-81.
bar2
spring3 spring2
world bar1
body1
spring1
Figure IS-81. Connection diagram (left) and 3D animation view (right) of the TripleSprings model with three springs directly connected in series and in parallel. The TripleSprings model, (essentially MultiBody. Examples. Elementary. ThreeSprings) appears below with an animation parameter. If the animation attributes are not specified, bodies and bars are animated by default, but not springs. If animation=false for the model, there will be no animation at all.
encapsulated model TripleSprings "3-dim. springs in series and parallel" import Modelica.Mechanics.MultiBody.Partsi import Modelica.Mechanics.MultiBody.Forces; parameter Boolean animation=true n= true, if animation shall be enabled"; inner Modelica.Mechanics.MultiBody.World world(animateWorld=animation); Parts.Body body1 (animation=animation, r_CM={O,-O.2,O}, r_O_start={O.5,-0.3,0}, m=0.8, 1_11=0.1, 1_22=0.1, 1_33=0.1, startValuesFixed=true, useQuaternions=false, sphereDiameter=O.2)i
Chapter 15 Application Examples 609 Parts. FixedTranslation Parts. FixedTranslation Forces.Spring Forces.Spring Forces.Spring equation connect (world. frame_b, connect(world.frame_b, connect{barl.frame_b, connect(bar2.frame_b, connect(spring2.frame_b, connect(spring3.frame_b, connect(spring2.frame_a, end TripleSprings;
15.10.10
barl(animation=animation, r={O.3,O,O}); bar2(animation=animation, r={O,O,O.3}}; springl(s unstretched=O.l, width=O.l, - coilWidth=O.OOS, numberOfWindings=5, c=20, animation=animation); spring2(s unstretched=O.l, width=O.l, - coilWidth=O.OOS, numberOfWindings=5, c=40, animation=animation}; spring3(s unstretched=O.l, width=O.l, - coilWidth=O.OOS, numberOfWindings=S, c=20, animation=animation); barl . frame_a) ; bar2. frame_a) ; springl.frame_a)i spring3.frame_a) ; bodyl. frame_a) ; springl.frame_b) ; springl.frame_b) i
ve Engine
We show a simple model of a V6 engine with 6 cylinders, MultiBody. Examples. Loops. EngineV6, to give an example of a slightly more complex application model using the MBS library than the previous examples. A simple model of the combustion process is used, given by an empirical formula. The model, MultiBody.Examples.Loops.EngineV6, is from the MultiBody.Examples sublibrary, and uses the Cylinder model (not shown here) from the Modelica. Mechanics. MultiBody. Examples. Loops. Utilities sublibrary. Each cylinder in the engine is modeled solely by revolute and prismatic joints, forming a planar kinematic loop. As was described in Section 15.10.7, page 601, we have to break a planar loop by setting the attribute planarCutJoint to true for one of the revolute joints in the loop. This is done in the Cylinder model, not in the EngineV6 model. The connection structure and 3D view of the model are shown in Figure 15-82.
Figure 15-82. Connectiondiagram (left) and 3D animation view (tight) of the V6 engine model, from MultiBody.Examples.Loops.EngineV6.
The Modelica code of the EngineV6 model with 1 degree-of-freedom and 6 cylinders, each containing a planar loop, and animation turned on: model EngineV6 "V6 engine with 6 cylinders, 6 planar loops and 1 degree-of-freedom" import Cv = Modelica.Slunits.Conversions; import Modelica.Mechanics.MultiBody.Examples.Loops.Utilities; import Modelica.Mechanics.MultiBody.Joints; extends Modelica.lcons.Example; parameter Boolean animation=true "= true, if animation shall be enabled"; inner Mcdelica.Mechanics.MultiBody.World world (animateNorld=false,
610 Peter Fritzson Principlesof Object-OrientedModeling and Simulation with Modelica animateGravity=false); bearing(n={l,O,O}, cylinderLength=O.02, cylinderDiameter=O.06, animation=animation); Modelica.Mechanics.Rotational.lnertia inertia ( phi (stateSelect=StateSelect.always, fixed=true, start=O), w(stateSelect=StateSelect.always, fixed=true, start=lO»; Utilities.Cylinder cylinderl(crankAngleOffset=Cv.from deg(-30), cylinderlnclination=Cv.from_deg(-30), anlmation=animation); Utilities.Cylinder cylinder2(crankAngleOffset=Cv.from deg(90), cylinderlnclination=Cv.from_deg(30), animation=animation); Utilities.Cylinder cylinder3(crankAngleOffset=Cv.from deg(-lS0), cylinderlnclination=Cv.from_deg(-30), a~imation=animation); Utilities.Cylinder cylinder4(crankAngleOffset=Cv.from deg(-90), cylinderlnclination=Cv.from_deg(30), a~imation=animation); Utilities.Cylinder cylinderS (crankAngleOffset=Cv.from deg(300), cylinderlnclination=Cv. from_deg (-30) , ;nimation=animation); Utilities.Cylinder cylinder6{crankAngleOffset=Cv.from deg(lS0), cylinderlnclination=Cv. from_deg (30) , a~imation=animation); equation connect (bearing.frame_b, cylinderl. crank_a) ; connect (cylinderl.crank_b, cylinder2.crank_a)j connect (cylinder2.crank_b, cylinder3.crank_a); connect(cylinder3.crank_b, cylinder4.crank_a); cylinderS.crank_a)j connect(cylinder4.crank_b, connect (cylinderS.crank_b, cylinder6.crank_a); connect (cylinder5.cylinder_b, cylinder6.cylinder_a); connect {cylinder4.cylinder_b, cylinderS.cylinder_a); connect(cylinder4.cylinder_a, cylinder3.cylinder_b) ; connect(cylinder3.cylinder_a, cylinder2.cylinder b); connect(cylinder2.cylinder_a, cylinderl.cylinder=b); connect {inertia.flange_b, bearing.axis); connect (world.frame_b, cylinderl.cylinder_a) ; connect (world.frame_b, bearing.frame_a); end EngineV6; Joints.ActuatedRevolute
15.10.11 Cardan/Euler Angles or Quaternions/Euler Parameters This rather advanced topic concerns two alternatives for construction of the rotation matrix R. The first approach is to use three independent variables-including the Euler and Cardan angle approaches, whereas the second is based on four variables dependent on each other-the QuatemionlEuler parameter approach. This is discussed in more detail in Sections 14.8.4.2, page 507 and 14.8.4~3, page 509. Since the rotation matrix represents three degrees of freedom, in principle three independent variables (i.e., states) would suffice. However, if these variables are chosen to be successive rotations around body local coordinate axes-the Euler and Cardan angle approaches- a division by zero may occur in one of the differential equations if the second angle f{J2 becomes ±nl2 , since there is a division by cos(lfJ2) in the right hand side of that equation. In the MBS library this is prevented by instead transforming relative to an intermediate frame T_ fix, which is a coordinate system available in each body (class MultiBody. Parts. Body), and is fixed relatively to the world frame. Whenever the Cardan angles (the phi vector) come close to their singular configuration (a condition when phi [2] passes the value phi2_critical, generating a state event), the frame T_fix is changed such that the new Cardan angles are far away from their singularity, i.e., a singular configuration will never occur. The initial values of the Cardan angle states are automatically computed from the initial values given via the sequence_start and angles_start values. Since the Cardan angles are defined relative to a frame T_ fix that is changing during simulation, these variables are not very descriptive. It is better to use the rotation matrix frame_a. R to get information about the body orientation.
Chapter 15 Application Examples 611 The rotation matrix for transforming a vector from the inertial frame to the local frame_a (i.e, R) is constructed from the 3 Cardan angles in three steps: first rotate around the x axis of frame T_ fix with an angle phi [1] , then around the y axis with an angle phi [2] , and finally around the z axis with an angle phi [3] , arriving at frame_a. The Euler angle approach applies these rotations in a different order. See Section 14.8.4.2, page 507. As an alternative, 4 dependent variables can be used as rotational body states. These are called quaternions or Euler parameters (see Section 14.8.4.3, page 509). They can be used instead of the 3 Cardan/Euler angles, by setting the parameter useQuaternions (also available in the Advanced menu of the MBS library) to true. Quaternions do not have a singular configuration and therefore no state events will occur during simulation, which it is necessary when the Cardan angles need to change their base frame T fix. The disadvantage of quatemions is that there is a non-linear constraint equation between the 4 quatemions. Therefore, at least one non-linear equation has to be solved per body during simulation. In most cases, the Cardan angle choice will be more efficient than the quatemion choice, but there may be cases where quatemions are better suited, e.g. when generation of state-events should be avoided to get continuous derivatives.
15.11
Mechanical CAD Model Simulation and Visualization
The two-dimensional graphic modeling paradigm provided by the connection editors available in most Modelica environments, e.g. see Chapter 5, page 145 and Chapter 19 page 699, provides graphic user interfaces for combining reusable model components. However, for certain applications such as the design of 3D mechanical parts and assemblies of such parts, the two-dimensional connection graph is not very intuitive and sometimes is hard to understand. It would be more natural to use a 3D graphic representation for the design of mechanical application systems consisting of three-dimensional mechanical components. Fortunately, such 3D graphic representations and geometry modeling tools already exist. These are available in CAD systems for design of mechanical applications. Therefore, it is natural to employ a mechanical CAD system as the interactive user interface to design the geometry, constraints, and connection structure of a mechanical application (Figure 15-83). However, consider the case that we want to simulate the dynamics of a mechanical application, and to do this using Modelica since we are interested in multidomain simulation with the possibility of simulating systems containing both mechanical and nonmechanicaI parts, e.g. attaching control, electric, or hydraulic components. CAD
Modelica Simulation Environment
Environment
r-------------Standard
Standard
Component
Component
Library
Library
,
---.....,...---' ,, I
r----II
:
:
------~--~---------
Vjsuali~ation , I : : r-O-yn-a-nn...:o·c--M-o-de-I-
i :
: I
,_!. -.__-
:: - -_-_-
I
I
Visualization (Animation)
: I
~ - t_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_·_-_-_-_-_-_-~_
Figure 15-83. Functional structure of the information flow between the Modelica simulation environment, the 3D visualizer, and the CAD environment.
612 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica To perform such a simulation we need a Modelica model that defines the dynamics of the mechanical application designed in the CAD systems. Component classes from the Modelica mechanical multibody system (MBS) library can be used to model the dynamics of a mechanical system consisting of interconnected mechanical parts, provided that the interacting parts are rigid (nonflexible) bodies. Fortunately, the information needed for simulating a multibody system of interacting mechanical bodies is already available in the CAD design. This includes the geometry, mass, inertia matrix, interconnections, movement constraints, etc., of the bodies. We just need to translate this information into a Modelica model consisting of appropriately selected instances of certain MBS library classes, connected according the constraints and geometry of the CAD design and design rules of the MBS library. The translation from CAD design information to a Modelica model for dynamic system simulation can be automated, provided that the CAD design is complete enough. To date, at least two automatic translators exist; for the SolidWorks and the AutoDesk Mechanical Desktop CAD systems, but more will probably follow. Both translators have been designed as CAD system plug-ins that extract geometry, mass, inertia, and constraint information using the CAD system programmable API, and translate this information into Modelica model code. This code can be subsequently combined with other models, e.g. control system models, and simulated. One advantage of the CAD-based model design approach, apart from its ease of use, is that information needed for 3D visualization and animation of the simulated multibody system can be obtained from the same CAD design. The geometry is already available in the 3D design, and if appropriate surface colors and patterns are specified, 3D visualizations of the bodies can be created automatically. Combined with a simulation of the model that computes the coordinates of all the moving bodies as functions of time, 3D animations can be produced automatically based on the CAD model. Figure 15-84 shows the process of designing a mechanical model using a CAD tool, serving as the starting point for the specification of a virtual prototype with dynamic properties. In the AutoCAD Mechanical Desktop-based translator, the model is first represented in the DWG format, which contains all the information, including connections and mates constraints, related to the geometrical properties of the parts and the whole mechanical assembly.
I CAD Syste;- - - - - - I 3D CAD mechanicalmodel D1GL I I I I I
L
-
-
-
-
-
-
-
-
-I I Translator II to Modelica II II II II -_-~J
CAD Sy;(;m- - -!ith attached t!!!,slato~
Mates related information
Figure 15-84. The process from a static CAD model to a dynamic system simulation and visualization. The geometry of each part is exported in an appropriate geometry format. At the same time, the mass and inertia of the parts are extracted together with mates information from the mechanical assembly. The
Chapter 15 Application Examples 613 translator uses this information to generate a corresponding set of Modelica class instances coupled by connections, which contain a set of dynamic equations of motion. This automatically generated Modelica code is processed by the Modelica simulation environment. The simulation code can be enhanced by adding components from other Modelica libraries or by adding externally defined program code, e.g. in the C programming language. In this phase, electrical, control, or hydraulics components can be added to the generated mechanical model, thus providing multidomain simulation. The solution of the model equations during simulation computes the dynamic response to a given set of initial conditions including force and/or torque loads, which might even be functions of time.
15.12
Summary
Aiming to show different modeling styles and know-how for various domains, we presented application examples from the following areas: mechatronic systems, thermodynamic systems, chemical reactions, biological and ecological systems, economic systems, internet communication, design optimization, Fourier analysis, pressure dynamics with discretized PDEs, mechanical multibody systems, and mechanical CAD systems. However, important additional goals of this chapter were to illustrate multi-domain modeling as in the DC-motor example, bottom-up design of a library as in the. thermodynamic example, and to give an introduction to using the Modelica multi-body library for 3D mechanical rigid bodies.
15.13
Literature
The literature references for this chapter are grouped according topic, as follows: •
•
•
•
• •
•
•
The simple multi-domain DC-motor model is discussed in detail in (Andersson 1994). Advanced multidomain systems are discussed in (Clauss and Beater 2002). Hybrid electric vehicles is another example of multi-domain system, described in (Hellgren 2002). Electrical brushless motors is yet another example, presented in (Ferretti, Magnani, Rocco, Bonometti, and Maraglino 2002). Thermodynamic theory and systems for engineering applications is presented in (Potter and Somerton 1993). Further reading on changing flow directions in thermodynamic flow systems: (Elmqvist, Otter, Mattsson, and Olsson 2(02). Advanced thermodynamics, thermo-hydraulics and chemical reaction modeling is discussed in (Tummescheit 2002; Tummescheit, Eborn 2002). Thermodynamics with models of moving boundaries for dynamic simulation of two-phase flows is described in (Jensen and Tummescheit 2002). Chemical processes with the simple hydrogen-iodine reaction can be found in most chemistry textbooks, but also in (Cellier 1991). Further reading on object oriented modeling of chemical processes can be found in (Nilsson 1993). Biological and ecological systems-population dynamics and energy forest models. Willow growth: (Larsdotter-Nilsson and Fritzson 2003; Sannervik, Eckersten, Verwijst, and Nordh 2002), (Lotka 1956; Volterra 1928). Basic relations in biochemistry are described in (Voit 2000). Biological pathways in biochemistry are discussed in (Michael 1999; SBML 2003). Economic systems--Keynesian national economy is presented in detail by (Lipsey 1997). Internet communication-TCP packet communication protocols (Farnqvist, Strandemar, Johansson, Hespanha 2002; Mascolo, Casetti, Gerla, Lee, and Sanadidi 2001; Jacobsson and Braden 1988). Design optimization-improving the response of a linear actuator. Further reading on design optimization using Modelica can be found in (Franke 2002; Elmqvist, Otter, Mattsson, and Olsson 2002). Fourier analysis of simulation data--vibrations in a rotating weak axis. No reference.
614 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica • •
•
Solving wave equations by discretized PDEs-pressure dynamics in ID ducts. No reference. Mechanical multi-body systems in general are described in (Shabana, 1998), whereas (Otter 1995; Otter, Elmqvist, and Cellier 1996) describes the theory behind the first version of the Modelica multi body library. . Employing CAD systems for designing mechanical Modelica models as well as generating visualizations based on OpenGL is described in (Engelson 2000), CAD Mechanical translation, Visualization: (Bunus, Engelson, and Fritzson 2000; Engelson, Larsson, and Fritzson 1999; Engelson 2000).
There are many more application areas in which Modelica is being employed. The following are references to some additional applications: •
• • •
Car applications, e.g. automatic gear boxes: (Otter, Schlegel, and Elmqvist 1997; Pelchen, Schweiger, and Otter 2002). Driveline vibrations in cars is presented in (Tiller, Tobler, and Kuang 2002). Tyre modeling for cars is described in (Andreasson and Jarlmark 2002). Spark-ignited . combustion engine simulation is presented in (Newman, Batteh, and Tiller 2002). Further reading on parameter estimation/identification using Modelica can be found in (Sjoberg, Fyhr, and Gronstedt 2(02). Thermal building behavior modeling and simulation is presented in (Sahlin 1996; Felgner, Agustina, Cladera Bohigas, Merz, and Litz 2002). An example of the integration of genetic algorithms using a Simulink interface to Modelica is given in (Hongesombut, Mitani, and Tsuji 2002).
615
Chapter 16 Modelica Library Overview
As we have emphasized earlier in this book, much of the power of modeling with Modelica comes from the ease of reusing model classes. Related classes in particular areas are grouped into packages which make them easier to find. This chapter gives a quick overview of some common Modelica packages. Definitions of a selection of these packages, including source code, are available in the appendices of this book. Explanations on how to use classes from certain commonly used packages are given in Chapter 15, page 523, whereas Chapter 5, page 145, covers the issues of connecting instances of models from different application areas. A special package, called Mode1 i ca, is a standardized predefined package that together with the Modelica Language is developed and maintained by the Modelica Association. This package is also known as the Modelica Standard Library. It provides constants, types, connector classes, partial models, and model classes of components from various application areas, which are grouped into subpackages of the Modelica package. A subpackage named Interfaces occurs as part of several packages. It contains interface definitions in terms of connector classes for the application area covered by the package in question, as well as commonly used partial classes to be reused by the other subpackages within that package. The subpackage Examples contains example models on how to use the classes of the package in question.
Modelica Blocks Interfaces Continuous Nonlinear Math Sources Constants Electrical Analog Interfaces, Basic, Ideal, Sensors,Sources,Examples, Lines,Semiconductors Digital Icons Math Mechanics Rotational
Standard library from the Modelica Association including the following sublibraries: Input/output blocks for use in block diagrams. Block sublibraries. Continuous control blocks with internal states (PI, ...). Discontinuous or non-differentiable control blocks Mathematical functions as input/output blocks (sin, ...). Source blocks generating Real and Boolean signals. Com.mon constants from mathematics, physics, etc. Common electrical component models Analog electrical component models, with sublibraries. Analog electrical sublibraries. Analog electrical sublibraries. Analog electrical sublibraries. Digital electrical components. Graphical icon definitions used in several packages. Definitions of common mathematical functions. 10 mechanical components. 10 rotational mechanical component models.
616 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica Interfaces,Sensors, Examples Translational Interfaces,Sensors,Examples MultiBody World,Interfaces,Parts, Joints,Forces,Sensors, Frames ,Types, Visualizers SIUnits Thermal Fluid Media
Rotationalsublibraries. ID translational mechanical component models. Translational sublibraries. 3D mechanical systems- new MultiBody library. MultiBody sublibraries. MultiBody sublibraries. MultiBodysublibraries. Type definitions with SI standard names and units. Thermal components with ID heat transfer. Thermodynamic fluid and gas models. Media models.
The Modelica Standard Library can be used freely for both noncommercial and commercial purposes under the conditions of The Modelica License as stated in the front pages of this book. The full documentation as well as the source code of these libraries appear at the Modelica web site: http://www.modelica.org/library/library.html.
There are also a number of free Modelica libraries that are not yet part of the Modelica standard library, and have not yet been "certified" by the Modelica Association. The quality of these libraries is varying. Some, like HyLibLight, PneuLibLight, most parts of ModelicaAdditions, etc., are well documented and tested, whereas this is not the case for certain other libraries. The number libraries available at the Modelica Association web site is growing rapidly. This table is a snapshot of the status in September 2003. Collectionof additionalModelica libraries of DLR:
ModelicaAdditions:
Blocks, PetriNets,Tables, HeatFlowlD, MultiBody. Blocks Discrete Logical Multiplexer PetriNets Tables HeatFlowlD MultiBody
Interfaces, Joints, CutJoints Forces,Parts,Sensors, Examples HyLibLight PneuLibLight ObjectStab ExtendedPetriNets ThermoFluid SystemDynamics QSSFluidFlow ATPlus Fuzzy Control VehicleDynamics
Additionalinput/outputblocks. Discrete input/outputblocks with fixed sample period. Boolean input/outputblocks. Combine and split signal connectors of type Real. Petri nets and state transitiondiagrams. Table look-up in I and 2 dimensions. l-dimensional heat flow. 3D mechanical systems - old MBS library with some connection restrictions and manual handling of kinematic loops. MBS sublibraries MBS sublibraries MBS sublibrary Hydrauliccomponent models, free subset of HyLib. Pneumaticcomponent models, free subset of PneuLib. Power Systems Voltage and Transient Simulation. Extended Petri net library. Advanced library on thermodynamics and thermohydraulics,steam power plants, and process systems. System dynamics formalismaccording to Forrester. Quasi steady-statefluid flows. Building simulation and building control. Fuzzy control library. Library of vehicle dynamics and chassis models.
Some comrnerciallibraries (usually not free of charge) are available, includingthe following: Library of hydrauliccomponent models.
Chapter 16 Modelica Library Overview 617 Library of pneumaticcomponentmodels. Library of powertraincomponentmodels. When developing an application or a library in some application area it is wise to use the standardized quantity types available in Modelica. SIuni ts and the standard connectors available in the corresponding Interf aces subpackage e.g. Model ica. Blocks. Interfaces of the Modelica Standard Library, in order that components based on the same physical abstraction have compatible interfaces and can be connected together.
16.1 Modelica.Constants The Modelica. Constants package provides often needed constants from mathematics, machine dependentconstants, and constants from nature. constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant constant
Real Real Real Real Real Real
e=Modelica.Math.exp(l.O) i pi=2*Modelica.Math.asin(1.O); D2R=pi/180 "Degree to Radian"; R2D=180/pi "Radian to Degree"; eps=1.e-15 "Biggest number such that 1.0 + EPS = 1.0"; small=1.e-60 "Smallest number such that small and -small are representable on the machine"; Real inf=1.e+60 "Largest Real number such that inf and -inf are representable on the machine"; Integer Integer_inf=2147483647 "Biggest Integer number such that Integer_inf and -Integer_inf are representable on the machine"; Modelica.SIunits.Velocity c=299792458 "Speed of light in vacuum"; Modelica.SIunits.Acceleration g n=9.80665 "Standard acceleration of gravity on earth"; Real G(final unit="m3/(kg.s2)") = 6.673e-11 "Newtonian constant of gravitation"; Real h(final unit="J.s") = 6.62606876e-34 "Planck constant"; Real k(final unit="J/KtI) = 1.3806503e-23 "Boltzmann constant"; Real R{final unit="J/(mol.K)") = 8.314472 "Molar gas constant"; Real sigma(final unit="W/(m2.K4)tI) = 5.670400e-8 "Stefan-Boltzmann constant"; Real N_A(final unit="l/mol") = 6.0221419ge23 "Avogadro constant"; Real roue OCfinal unit="N/A2") = 4*pi*1.e-7 "Magnetic constant"; Real epsflon_O(final unit="F/m") = l/(mue_O*c*c) "Electric constant"; Modelica.SIunits.CelsiusTemperature T_zero=-273.15 "Absolute zero temperature"; Real E=e; Real PI=pi; Real EPS=eps; Real SMALL=small; Real INF=inf; Real INTEGER_INF=Integer_inf; Real C=c; Real H=h; Real K=ki Real RO=R; Real SIGMA=sigma; Real G_EARTH=g_n; Real T_ZERO=T_zero;
618 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
16.2 Modelica.lcons This package contains definitions for the graphical layout of component icons which can be reused in more than one library. The icons can be used by inheriting them into the desired class. The following icons are currently available:
I' I [Ll~~+~ (;~3~,~ nfo
Info
Ubrary1
Ubrary2
r~m~e~
Example
TranslationalSensor
RotationalSensor
... ..
Gearlcon
Motortcon
Figure 16-1. Modelicalibraryicons to be reused in severallibraries.
Source code for these classes is available in Appendix D.
16.3 Modelica.Math This package contains the following basic mathematical functions: sin(u)
sine cosine tangent (u shall not be: ..., -1l12, 1l/2, 31/,/2, ... ) inverse sine (-1 SuS 1)
cos(u)
tan(u) asin(u) acos(u) atan(u)
inverse cosine (-1 ~ u S 1) inverse tangent four quadrant inverse tangent hyperbolic sine hyperbolic cosine hyperbolic tangent exponential, base e natural (base e) logarithm (u > 0) base 10 logarithm (u > 0)
atan2(ul,u2)
sinh(u) cosh(u)
tanh(u) exp (u) log(u) loglO(u)
u w~ l3ZJ [1j l5j ~ 123
Additionally, a subpackage Random containing certain random distribution functions is available. The above functions have the following graphical icon attributes:
baselcon1
I~I ~ atan2
baselcon2
sin
cos
tan
asin
acos
I"'"iLl 1\ :"'/1 1"'' '1:1 I~,,; /1 I~L:I ILl lCIJ ~ l£J ~ lLiiJ ~ sinh cosh tanh exp log log10
D
atan
templnterpol1
Figure 16-2. Icons for common mathematical functions.
Source code for these classes is available in Appendix D.
16.4 Modelica.SIUnits This package provides predefined types, such as Mass, Length, Time, based on the international standard on units:
Chapter 16 Modelica LibraryOverview 619
• •
ISO 31-1992 "General principles concerning quantities, units and symbols" ISO 1000-1992 "SI units and recommendations for the use of their multiples and of certain other units". The following conventions are used in this package: •
• • • • • •
Modelica quantity names are defined according to the recommendations of ISO 31. Some of these names are rather long, such as ThermodynamicTemperature. Shorter alias names are defined, e.g. type Temp_K = ThermodynamicTen~perature. Modelica units are defined according to the SI base units without multiples (only exception "kg"). For some quantities, more convenient units for an engineer are defined as displayUni t, i.e, the default unit for display purposes (e.g., displayUnit="deg" for quantity= "Angle II). The type name is identical to the quantity name, following the convention of type names. All quantity and unit attributes are defined as final in order that they cannot be redefined to another value. Synonyms for identical quantities, e.g. Length, Breadth, Height, Thickness, Radius are defined as the same quantity (here: Length). The ordering of the type declarations in this package follows ISO 31, i.e. 1) Space and Time, 2) Periodic and Related Phenomena, 3) Mechanics, 4) Heat, 5) Electricity and Magnetism, 6) Light and Related Electro-Magnetic Radiations, 7) Acoustics, 8) Physical Chemistry, 9) Atomic and Nuclear Physics, 10) Nuclear Reactions and Ionizing Radiations, 11) (not defined in ISO 31-1992), 12) Characteristic Numbers, 13) Solid State Physics.
Type definitions in the package Modelica. SIUni ts have the following appearance: type Angle = Real (final quantity="Angle", final unit="rad", displayUnit="deg") ; type SolidAngle := Real(final quantity="SolidAngle", final unit= "sr n ) ; type Length = Real (final quantity="Length", final unit="m" ); type PathLength = Length; etc ...
The full set of type definitions of Modelica. SIUnits can be found in Appendix D.
16.5 Modelica.Electrical This library contains electrical components to build up analog and digital circuits. The library is currently structured in the following sublibraries: • •
Analog Digital
[~~~ Analog
Figure 16-3. Icons for electrical sublibraries.
Explanations on how to use several basic electrical components such as resistors, capacitors, etc., and how to combine them with mechanical components, can be found in Chapter 2, page 19, Chapter 5, page 145, and Chapter 15, page 523. Source code for many classes in the Modelica. Electrical library is available in Appendix D.
620 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
16.5.1 Modelica.Electrical.Analog This is a libraryof analog electrical models, containing subpackages for differentkinds of analog electrical components: Basic: basic components, e.g. resistor, capacitor, conductor, inductor, transformer, gyrator. Semiconductors: semiconductor devices,e.g. diode, bipolar and MOS transistors.
• • • • • •
Line~:
transmission lines,both lossy and lossless.
Ideal: ideal elements, including switches, diode,transformer, idle, short, etc. Sources: time-dependent and controlled voltage and currentsources. Sensors: sensors to measure potential, voltage, and current.
The graphicalicons for the sublibraries appear as follows:
[~~~;~
Interfaces
(~~!~~ Basic
r\~~~ Ideal
f~fi~
[~~~~~
Sensors
Sources
(;H~tJI Examples
[~~~~ Lines
[~!~~
Semiconductors
Figure 16-4. Icons for electrical analog sublibraries.
16.5.1.1 Modelica.Electrical.Analog.lnterfaces
• -cr•
This subpackage contains the interface definitions in terms of connectorclasses, as well as partial models for analog electricalcomponents. The namesand iconsof the classesappearbelow:
PositivePin
Pin
0
TwoPort
AbsoluteSensor
D
NegativePin
~
RelativeSensor
0
TwoPin
--& VoltageSource
0
OnePort
--err
CurrentSource
Figure 16-5. Connector and partial model icons in the electrical analog interfaces sublibrary.
Detailed explanations of classes such as Pin, PositivePin, etc. is presented in Chapter 5, page 146. Sourcecode for these classesis available in Appendix D. 16.5.1.2 Modelica.ElectricaI.Analog.Basic
This packagecontainsbasic analogelectrical components: • •
Ground Resister
• • • •
Conductor Capacitor Inductor Transformer
•
Gyrator
•
Linear controlled sourcessuch as EMF, VCV, vee, eev, and eec.
The basic natural laws used in these models are brieflydescribed in Section 14.2,page 478. An application example in terms of a DeMetor model using many of these components, including an EMF (Electro Motoric Force) converter, is presented in Section 15.1,page 524.
Chapter 16 ModelicaLibrary Overview 621
-.L
-c=JD
--r=Jn
-----! J--o
Resistor
Conductor
Capacitor
Ground
Inductor
Transfonner
rIJ]]
rtJ]t
ccv
ece
EMF
Gyrator
3C: M
!E ~ IJJ1 vec vev
ill
.fVVV"\....Q
Figure 16-6. Icons for basic electrical analog components. Source code for these classes is available in Appendix D.
16.5.1.3 Modelica.Electrical.Analog.ldeal This package contains ideal components:
• •
• • •
• • • • •
thyristor GTO thyristor
switches diode transformer gyrator operational amplifier operational amplifier (3 Pins) idle branch short cut
* *JC
The ideal diode model mentioned in the list is discussed in Section 2.15, page 50.
IdealThyristor
~--
.J=:
IdealGTOThyristor
IdealSwitch
Controlledldea ISwitch
ControlledIdeal CommutingSwitch
IdealTransformer
IdealGyrator
---&+--n
Ideal Diode
,
J~
I
Dca
--Do Idle
~ '+
I~~I
pAmp
H
Short
Figure 16-7. Icons for ideal electrical analog components.
Source code for these classes is available in Appendix D.
16.5.1.4 Modelica.Electrical.Anelog.Sensors This package contains potential, voltage, and current sensors.
PotentialSensor
-qr
VoltageSensor
~
CurrentSensor
Figure 16-8. Icons for electricalanalog sensors,for sensing voltages and currents. Source code for these classes is available in Appendix D.
16.5.1.5
Modellca.EJectrical.Analog.Sour~es
This package contains time-dependent and controlled voltage and current sources, as depicted in Figure 16-9. Step signals are used in a Dumber of models, e.g. the DCMotor model described in Section 15.1, page 524.
622 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
.~ ./
SignalVoltage
ConstantVoltage
StepVoltage
RampVoltage
SineVoltage
ExpSineVoltage
TableVoltage
SignalCurrent
..... ~ : J~
'.
ExponentialsVoltage
PulseVoltage
,:
SawToothVoltage TrapezoidVoltage
.~.' ~ StepCurrent
ConstantCurrent
RampCurrent
SineCurrent
ExpSineCurrent ExponentialsCurrent
.-{I)-o PulseCurrent
SawToothCurrent TrapezoidCurrent
TableCurrent
Figure 16-9. Icons for electrical analogvoltageand current sources, with generated signals of various forms. Source code for these classes is available in Appendix D.
16.5.1.6 Modelica.Electrlcal.Analog.Examples This package contains examples for the analog electrical packages. • • •
Chuas circuit Cauer filter NAND gate
CauerFilter
ChuaCircuit
is
DifferenceAmplifier
NandGate
Figure 16·10. Icons for a few electrical analog example models. Source code for these classes is available in Appendix D.
16.5.1.7 Modelica.Electrlcal.Analog.Lines
·v
This package contains models for lossy and lossless analog transmission lines.
V
OLine
III
ULine
Figure 16-11. Icons for lossy and losslesselectricalanalog transmission lines. Source code for these classes is available in Appendix D.
16.5.1.8 Modelica.Electrical.Analog.Semlconductors This package contains a few common analog semiconductor devices: • • •
diode MOS transistors bipolar transistors
Chapter 16 Modelica Library Overview 623
Diode
.JS
.J8 PMOS
NMOS
--c -r: PNP
NPN
Figure 16-12. Icons for common electrical analog semiconductors such as diodes and transistors. The diode model is explained in Section 2.15, page 50. Source code for these classes is available in Appendix D.
16.6 Modelica.Blocks This library contains input/output blocks to build up block diagrams. See Section 12.5, page 396, for description of the notion of block diagrams. The library is structured into the following sublibraries:
• • • • •
• •
Interfaces: connectors and partial models for block diagram components. Continuous: basic continuous input/output blocks. Discrete: discrete control blocks (not yet available). Logical; logical and relational operations on Boolean signals (not yet available). Nonl inear: discontinuous or non-differentiable algebraic control blocks. Ma t h: mathematical functions as input/output blocks. Sources: signal sources such as signal generators.
~*~~
Continuous
r~~~
ru¥~~
Interfaces
Nonlinear
rTh~~~ Math
r~+~
Sources
Figure 16-13. Icons for sublibraries of the Modelica blocks library for input/output blocks.
Source code for the Modelica.Blocks library is available in Appendix D.
16.6.1 Vectorized vs. Nonvectorized Blocks Library This book describes the new vectorized version of the Modelica.Blocks library planned to be released in November 2003. All examples in this book are adapted to the new library. The difference is in simpler connector classes, when enable automatic vectorization, i.e. even though a scalar connector is specified, it is automatically converted to a vector when connected to a vector connector. This property make many block classes shorter and easier to understand. The old, nonvectorized versions use an explicit signal vector, which is more cumbersome to refer to. The old connector class for Real signals appear below: connector InPort parameter n=l; input Real signal[nl; end InPort; II From Modelica.Blocks.lnterfaces The corresponding definition Real Input in the new vectorized Blocks library is as follows: connector Reallnput
=
input RealSignali II RealSignal is subtype of Real
16.6.2 Modelica.Blocks.lnterfaces This package contains interface definitions for continuous input/output blocks. In particular it contains the following connector classes:
624 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica • • • • • •
Connector with input signals of type Real. Connector with output signals of type Real. Connector with input signals of type Boolean. Connector with output signals of type Boolean. Connector with input signals of type Integer. Connector with output signals of type Integer.
RealInput RealOutput Booleanlnput BooleanOutput IntegerInput IntegerOutput
Of the above, the use of Reallnput and RealOutput is explained in some detail in Section 5.2, page 146 The following partial block classes are provided to model continuous control blocks: •
Blocklcon
•
so
• •
MO S ISO S 12 SO MISO MIMO MIMOs
•
• • •
• • • • •
Basic graphical layout of continuous block. Single Output continuous control block. Multiple Output continuous control block. Single Input Single Output continuous control block. 2 Single Input I 1 Single Output continuous control block. Multiple Input Single Output continuous control block. Multiple Input Multiple Output continuous control block. Multiple Input Multiple Output continuous control block with the same number of inputs and outputs. 2 Multiple Input I Multiple Output continuous control block. Base class for continuous signal sources . Base class for periodic continuous signal sources. Single-Variable continuous controller. Multi-Variable continuous controller.
MI2MO .SignalSource Periodic SVcontrol MVcontrol
The following partial block classes are provided to model Boolean control blocks: • • • •
BooleanBlocklcon BooleanSISO BooleanSignalSource MI2BooleanMOs
Basic graphical layout of Boolean block Single Input Single Output control block with signals of type Boolean Base class for Boolean signal sources 2 Multiple Input I Boolean Multiple Output block with same signal lengths
The icons corresponding to all these classes are depicted in Figure 16-14.
~
Reallnput
[>
RealOutput
~
Booleanlnput
0
0
0
0
0
0
so
MIMO
QI
SISO
MO
MIMOs
r----·-----: i !
I
L.______
I
J
BooleanBlocklcon
MI2MO
r·-········-·····;
~l._________ .!~
BooieanSISO
r'··, ...I'~ .".,.,.-.".-."
BooleanOutPut
0 0
SI2S0
SlgnalSource
Ir-------·l t_:_·:_·_·_·:_·_·~:j
BooleanSlgnal Source
D 0
Blocklcon
MISO
~sv&nL .r-----------l I ~, ~
__________J
MI2Booiean MOs
Figure 16-14. Icons for connector classes and partial classes used by the Modelica Blocks library. Source code for these classes is available in Appendix D.
Chapter 16 Modelica Library Overview 625
16.6.3 Modelica.Blocks.Continuous This package contains basic continuous input/output blocks.
{ZJ
Integrator
£@ ...........
PI
,~t
{J
£}
i:J
Limlntegrator
........
PIO
Derivative
I;,
. ..
U
~
10
{C~t ,f\fJ ....
FlrstOrder
,~~t
TransferFunction
-----"
SecondOrder
+~~
StateSpace
Figure 16-15. Icons for basic continuous input/outputblocks.
Source code for these classes is availablein Appendix D.
16.6.4 Modelica.Blocks.Nonlinear This package contains discontinuous and nan-differentiable, algebraic input/output blocks. In particular the following blocks are provided:
• •
Limit the range of a signal. Provide a region of zero output.
Limiter DeadZone
Limiter
id
DeadZone
Figure 16-16. Icons for discontinuous and nondifferentiable the input/outputblocks such as limiters and the zones.
Source code for these classes is availablein AppendixD.
16.6.5 Modelica.Blocks.Math This package contains basic mathematical operations, such as summation and multiplication, and basic mathematical functions, such as sqrt and sin, as input/output blocks. All blocks of this library can be either connected with continuous blocks or with sampled-data blocks. In particular the following operations and functions are provided:
• • • • • •
• • • •
Twolnputs TwoOutputs Gain MatrixGain Sum Feedback Add Add3 Product Division
•
Abs
• •
Sign Sqrt Sin
•
Change causalityof input signals. Change causalityof output signals. Output the input multiplied by a scalar gain Output the productof a gain matrix with the input Output the sum of the elementsof the input vector Output differencebetweencommanded and feedback input Output the sum of the two inputs Output the sum of the three inputs Output productof the two inputs Output first input divided by second input Output the absolute value of the input Output the sign of the input Output the square root of the input Output the sine of the input
626 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
•
• • • • • • •
• • •
•
Outputthe cosineof the input Outputthe tangentof the input Outputthe arc sine of the input Outputthe arc cosineof the input Outputthe arc tangentof the input Output atan(utlu2) of the inputs Ul and U2 Outputthe hyperbolic sine of the input Outputthe hyperbolic cosine of the input Outputthe hyperbolic tangentof the input Outputthe exponential (basee) of the input Outputthe natural (base e) logarithm of the input Outputthe base 10 logarithm of the input
Cos Tan Asin Acos Atan Atan2 Sinh Cosh Tanh Exp Log LoglO
The icons for these input/output blocksfor basic mathematical functions are depicted in Figure 16-17.
{>
B
ill
~
~
~
~
rd g' W
Gain
Product
Cos
.. ; {d
"~l
Sinh
MatrixGain
Division
~ ...'.":
..
~
~----
Tan
Sum
Abs
... i'" {2} ~~::-.::
~.
Asin
...
............
Cosh
',
":"..~-
Tanh
~~
!-
Feedback
E:J I
... ..~.
.~:;.:!'
~ ...
'
-
1--
Sign
~
0 £It
[]J
~
[6J
~
~ Add
~:.n< I· ..
.~
Sqrt
m
...I.. ."; .,~,
t2}
~r:
.~~~~~
Acos
..I '~XL::
I :....
0;.
Exp
Atan
I'
I:.'; .,.;-
Log
Add3
. ......
Sin
":"".:"--
Atan2
..
~ ~~~~.:
Log10
Figure 16-17. Icons for blocks corresponding to basic mathematical operations and functions.
Sourcecode for these classesis available in Appendix D.
16.6.6 Modelica.Blocks.Sources This packagecontains signal source components, i.e, blocks which only have output signals.These blocks are used as signal generators. For example, a Step signal generator is used in the examples in Section Chapter 5, page 145and Section 15.1,page 524. The following sourcesare provided to generate Real signals:
• • • • • •
• • • • •
Clock Constant Step Ramp Sine ExpSine Exponentials Pulse SawTooth Trapezoid KinematicPTP
Generate actual time. Generate constantsignals. Generate step signals. Generate ramp signals. Generate sine signals. Generate exponentially dampedsine signals. Generate a rising and fallingexponential signal. Generate pulse signals. Generate sawtooth signals. Generate trapezoidal signals. Generate an acceleration signal to move as fast as possible along a
Chapter 16 Modelica Library Overview 627
distance within given kinematic constraints. •
Generate a (possibly discontinuous) signal by linear interpolation in a table.
TimeTable
The following sources are provided to generate Boolean signals: • • • •
Generateconstant signals. Generate step signals. Generate pulse signals. Generate sample triggers.
BooleanConstant BooleanStep BooleanPulse SampleTrigger
All sources are automatically vectorized when needed, and works either for connecting scalars or vectors of signals. All Real source signals (with the exception of the Constant source) have at least the following two parameters: • •
offset startTime
Value which is added to all signal values. Start time of signal. For time < startTime, the output is set to offset.
The offset parameter is especially useful in order to shift the corresponding source such that at initial time the system is stationary. To determine the corresponding value of offset usually requires a trimming calculation. Il-:·'- . . . '
Il·"-~i
I\...:...l..~/ Clock
ru
Exponentials
[:--:J BooieanConstant
B
Constant
OJ
[23
[]ill
[M}
lIY}
Step
Pulse
SawTooth
:;---'~:-:-._.:
rM~
lSi, i·,,·;
;
Booie'anStep
. .,1
" ... __. ___ .J
BooleanPulse
Ramp
Trapezoid
reg
~
ffiirt
~
Sine
I"
rL____
KlnematlcPTP
: .. "'r ExpSlne
TimeTable
III II IJ
Samplefrigger
Figure 16-18. Icons for signal sources of various forms. Source code for these classes is availablein AppendixD.
16.7 Modelica.Mechanics This package contains components to model mechanical systems. Currently the following subpackages are available: • •
Rotat ional Translational
•
~
Rotational
l-dirnensionalrotational mechanical components. l-dimensional translationalmechanical components.
f.~
Transiational
Figure 16-19. Icons for the rotational and translational mechanical sublibraries. Source code for these sublibrariesis availablein AppendixD.
628 Peter Fritzson Principlesof Object-OrientedModeling and Simulation with Modelica
16.7.1 Modelica.Mechanics.Rotational This package contains components to model l-dimensional rotational mechanical systems, including different types of gearboxes, shafts with inertia, external torques, spring/damper elements, frictional elements, backlash, elements to measure angle, angular velocity, angular acceleration and the torque transmitted at a flange. A simple examples with explanation of using a few rotational elements from this library are presented in Section 15.1, page 524. A discussion of the hybrid mode switching ElastoBacklash model is given in Section 13.4.2, page 464. A selection of the basic equations used in this library are described in Section 14.4, page 483. In the Examples sublibrary several examples are present to demonstrate the usage of the elements. Just open the corresponding example model and simulate the model according to the provided description. A unique feature of this library is the component-oriented modeling of Coulomb friction elements, such as friction in bearings, clutches, brakes, and gear efficiency. Even (dynamically) coupled friction elements, e.g. as in automatic gearboxes, can be handled without introducing stiffness, leading to fast simulations. The underlying theory is rather new and is based on the solution of mixed continuous/discrete systems of equations, i.e. equations where the unknowns are of type Real, Integer, or Boolean. Provided appropriate numeric algorithms for the solution of such types of systems are available in the simulation tool, the simulation ef (dynamically) coupled friction elements of this library is efficient and reliable. 16.7.1.1 Components of the library This package contains the following model components: • • • • • • • • • • • • • • • • • • • • •
Sublibrary containing example models. Sublibrary containing interface definitions. Rotational component with inertia. Ideal gear transforming rotational in rotational motion. Ideal standard planetary gear. Ideal gear transforming rotational in translational motion. Linear spring. Linear damper. Linear spring and linear damper in parallel connection. Linear spring, linear damper and backlash in series connection (backlash is modeled with elasticity) See also Section 13.4.2, page 464. BearingFriction Coulomb friction in the bearings. Clutch Frictional clutch where the clutch pressure force is an input signal (= Coulomb friction between two flanges). OneWayClutch Parallel connection of free wheel and clutch Brake Frictional brake where the brake pressure force is an input signal (= Coulomb friction between flange and housing). GearEfficiency Efficiency ofa gearbox. Gear Realistic model of a gearbox (taking into account efficiency, bearing friction, elasticity, damping, backlash) position Forced movement of a flange with a reference angle given as input signal (positive angle for positive input signal). Accelerate Forced movement of a flange with an angular acceleration given as input signal (positive acceleration for positive input signal). Move Forced movement of a flange according to an angle, speed and angular acceleration given as input signals. Fixed Fixing flange in housing at a predefined angle. Torque External torque defined as input signal which accelerates the connected flange for positive input signal. Examples Interfaces Inertia IdealGear IdealPlanetary IdealGearR2T Spring Damper Spr ingDamper ElastoBacklash
Chapter 16 Modelica Library Overview 629 • •
.,
Relati veStates Sensors
Definition of relative state variables Sublibrary containing idealsensors to measure flange variables.
The icons correspondingto the rotational modelcomponents are depicted inFigure 16..20 below.
Inertia
--IIf-a Damper
*
OneWayClutch
4
T
:a
IdealGear
-0
IdealPlanetary
SpringDamper
T~
Brake
~
ElastoBacklash
-L
T
GearEfficiency
~
--N'-fJ
a
$
IdealGearR2T
...,
Spring
Clutch
BearingFriction
Gear
..
-L . I
T
Position
~~o
Hi
tau
Accelerate
r~a~~
Examples
Torque
Fixed
[~;~~,~
Interfaces
RelativeStates
[u~a~~
Sensors
Figure 16·20. Icons and sublibraries for the mechanical rotational sublibrary. Source code for these classes is availablein Appendix D. 16.7.1.2 Modelica.Mechanics.Rotatlonal.lnterfaces
This Rotational. Interfaces package contains connector classes and partial models (i.e. base. classes) for ID rotational mechanical components. The use of the connector classes Flange_a and Flange_b for rotational connections and the base classes Rigid is mentioned in Section 15.1, page 524,. The icons correspondingto these models are depictedin Figure 16-21.
•o
Flange_8
TwoFlanges
D
FrictionBase
o o Rigid
Compliant
AbsoluteSensor
RelativeSensor
~
Figure 16-21. Icons for connector classes and partial classes in the mechanical rotational sublibrary. Source code for these classes is availablein AppendixD. 16.7.1.3 Modelica.Mechanics.Rotatlonal.Sensors
The Sensors sublibrary for sensors of rotational quantities such as angle, angular speed, angular acceleration, torque, etc., can be used to measure certain variables in ID rotational mechanical components.
630 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Tor~m ~,
ReIAng Sensor
~
AngleSensa
{!);
{!);
Speedsensor
Acesensor
Re~~sor ~ RelAee
nsor
Figure 16-22. Icons for sensor components in the mechanical rotational sensor sublibrary. Source code for these classes is available in Appendix D.
16.7.1.4 Modelica.Mechanics.Rotatlonal.Examples This package contains example models to demonstrate the usage of the ID mechanical rotational library. The following example models are present: • • •
First example using simple basic elements. First Example to demonstrate usage of a clutch and a brake. Friction CoupledClutches Example to demonstrate usage of three dynamically coupled clutches.
E3 First
(;:;~ Friction
[~~~
CoupiedClutches
Figure 16-23. Icons for mechanical rotational example models. Source code for these classes is available in Appendix D.
16.7.2 Modelica.Mechanics.Translational This package contains components to model l-dimensional translational mechanical systems. In Section 14.3, page 481, we describe the basic equations governing such translational motion. A more detailed presentation concerning many issues of one-dimensional translational mechanical models was earlier given in Sections 5.3 and 5.4 , pages 148 and 151. The filled and non-filled green squares at the left and right side of a component represent translational mechanical flanges. Drawing a line between such squares means that the corresponding flanges are rigidly attached to each other. The components of this library can usually be connected together in an arbitrary way. For example, it is possible to directly connect two springs or two sliding- masses with inertia. The only connection restriction is that the Coulomb friction elements (such as Stop) should only be connected together provided a compliant element, such as a spring, is placed in between. The reason is that otherwise the frictional force is not uniquely defined if the elements are stuck at the same time instant (i.e, there does not exist a unique solution) and some simulation systems may not be able to handle this situation, since this leads to a singularity during simulation. It can only be resolved in a "clean way" by combining the two connected friction elements into one component and resolving the ambiguity of the frictional force in the stuck mode. Another restriction arises if the hard stops in model s top are used, L e. the movement of the mass is limited by a stop at smax or smin. This requires the states Stop. s and Stop. v. If these states are eliminated during the index reduction stage (see Section 18.2.4, page 679) of the total equation system solution process the model will not work. To avoidthis any inertias should be connected via springs to the Stop element----other sliding masses, dampers or hydraulic chambers must be avoided. In the icon of every component an arrow is displayed in grey color. This arrow characterizes the coordinate system in which the vectors of the component are resolved. It is directed into the positive translational direction (in the mathematical sense). In the flanges of a component, a coordinate system is rigidly attached to the flange. It is called flange frame and is directed in parallel to the component
Chapter 16 Modelica Library Overview 631 coordinate system. As a result, e.g., the positive flange-force of a "left" flange (f lange_a) is directed into the flange, whereas the positive flange-force of a "right" flange (flange_b) is directed out of the flange. See Section 5.4, page 151, for further discussion of coordinate systems and flanges of ID translational model components. As already stated in Section 5.2, page 146, aID mechanical translational flange is described by a Modelica connector containing the following variables: SIunits.Position s flow Force f
"absolute position of flange"; "flange-force at the flange";
This package contains the following mode! components:
•
Sublibrary containing interface definitions. Sublibrary containing examples of library usage. Translational component with inertia. Sliding mass with Coulomb friction and hard stops. Massless rod. Linear spring. Linear damper. Linear spring and linear damper connected in parallel. Linear spring and linear damper that can lift off. Drive a flange with a reference position given as input signal. Drive a flange with an acceleration given as input signal. Drive a flange with a reference position, velocity and acceleration given as input signal. Fixed Fixed flange at a predefined position. Force External force defined as input signal. ForceSensor Ideal sensor to measure the force in a flange. PositionSensor Ideal sensor to measure absolute position of a flange. SpeedSensor Ideal sensor to measure absolute velocity of a flange. AccSensor Ideal sensor to measure absolute acceleration of a flange.
Interfaces Examples SlidingMass Stop Rod Spring Damper SpringDamper ElastoGap Position Accelerate Move
• • •
• • •
• • • • •
• • • •
• •
This library is designed in a general way in order that components can be connected together in every meaningful combination, e.g. including direct connections of two springs or two shafts with inertia. As a consequence, most models lead to a system of differential-algebraic equations (DAEs) of index 3 (i.e. constraint equations have to be differentiated twice in order to arrive at a state space representation, see also Section 18.2.3, page 675) and the Modelica translator or the simulator has to cope with this system representation. According to our present knowledge, this requires that the Modelica translator is able to symbolically differentiate equations - otherwise it is e.g. not possible to provide consistent initial conditions. However, even if consistent initial conditions are present most numerical DAE integrators can handle at most index 2
DARs.
•.
a-~':J
--.
--...
SlIdfngMass
--f l!r: --.
ElastoGap
~
Examples
Stop
-
Rod
.,---.----.-(J
Position
Accelerate
--...to-r:.
-----sprtng
7b
Fixed
~.:
--.
Damper
~.,
f
Force
~
SpringDamper
~ RelaliveStates
(3
Interfaces
Figure 16-24. Icons for components and sublibraries in the mechanical translational sublibrary.
632 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Source code for all Mechanics. Translational classes is available in Appendix D. 16.7.2.1 Modelica.MechanicslITranslational.lnterfaces
Interfaces for ID translational mechanical components, i.e. the connector classes Flange_a and Flange_b, as well as base classes such as Rigid and Compliant belong to this library. The icons are depicted in Figure 16.. 25 below. The class Compliant is presented in some detail in Section 5.4.2, page 153, whereas Rigid is used in the hanging mass oscillator model in Section 5.4.4, page 156.
r o
Flange_b
0
--w~
~~,
- -
. _
. _
- -
-'
I
I I
I
1.......__ ..._ ._ ......1
o
TwoFlanges
--.
AbsoluteSensor
Rigid
RelatiteSensor
0 0
Compliant
FrictionBase
Figure 16-25. Icons for connector classesof partialclasses for the mechanical translational sublibrary. 16.7.2.2 Modelica.Mechanics.Translational.Sensors
Sensors for ID translational mechanical quantities such as force, position, speed, and acceleration belong to this sublibrary, for which the icons are depicted in Figure 16-26 below.
~l
Force~e~sor
SpeedSensor
PositionSensor
AccSensor
Figure 16-26. Iconsfor force, position, speed, and acceleration sensorcomponents in the mechanical translational sensorsublibrary. 16.7.2.3 Modelica.Mechanics.Translational.Examples
This package contains example models to demonstrate the usage of the Mechanics. Translational package, including instructions on how to simulate them. A variant of the oscillator example is explained in detail in Section 5.4.4, page 156. The following example models are present in this sublibrary:
•
• • • • • • •
SignConvention InitialConditions Accelerate Damper Oscillator Sensors Friction PreLoad
Examples for the used sign conventions using simple, basic elements Setting of initial conditions Use of model accelerate Use of damper elements Oscillator demonstrates the use of initial conditions Sensors for translational systems Stribeck friction characteristics Positioning of a spool using ElastoGap models
The icons of the example models are schematically depicted in Figure 16-27 below.
rExamp,~ SignConventlon
F::pl
Oscillator
~~~]
~;~~
Accelerate
E~~~]
rExamp,~
[Fmp~~
rExamp~
InltialCondltlons
Sensors
Friction
Damper
Preload
Figure 16-27. Iconsfor example models usingthe mechanical translational sublibrary.
Chapter 16 Modelica Library Overview 633
16.8 Modelica.Mechanics.MultiBody The Modelica. Mechanics . r~ul tiBody library is used to model 3-dimensional mechanical systems, such as robots, satellites or vehicles, consisting of rigid bodies. Models of flexible bodies are currently not supported. The library has been designed to give very efficient simulation of multibody systems consisting of rigid mechanical bodies, especially those coupled by joints. A basic feature is that all components have animation information with appropriate default sizes and colors. Note that all components-the coordinate system of the world frame, the gravity acceleration vector, the revolute joints and the bodies-ean be visualized in the animation. This library replaces the old MBS library called ModelicaAdditions . MultiBody library, since the new library is much easier to use and more powerful. Note that the components of the MultiBody library can be combined with components from the libraries Madelica. Mechanics. Rotational and Madelica. Mechanics. Translational, which are both l-dimensional mechanical libraries. A unique feature of the Mul t iBody library is the efficient treatment of joint locking and unlocking. This allows e.g. easy modeling of friction or brakes in the joints. A general introduction to the topic of multibody systems of rigid bodies together with the theory and derivation of the basic Newton equations relating bodies and coordinate systems in the form they appear in this library, is briefly given in Section 14.8, page 502. A comprehensive introduction to the structure and usage of the Mul t iBody library, including examples, is given in Section 15.10, starting on page 587, which we recommend to read before using this library. Below we just present a short summary of the library. This description applies to the beta version of the library available in the middle of September 2003. Updated versions can be accessed at www.Modelica.org or at the book web page.
16.8.1 Overview The main features of the new Modelica. Mechanics. MultiBody library are: •
•
•
•
About 40 main components, i.e., joint, force, part, body, sensor and visualizer components that are ready to use and have useful default animation properties. One-dimensional force laws can be defined with components of the Modelica . Mechanics. Rotational and of the Modelica. Mechanics. Translational library and can be connected via available flange connectors to MultiBody components. A War Id model has to be present in every model on top level. Here the gravity field is defined (currently: no gravity, uniform gravity, point gravity), the visualization of the world coordinate system and default settings for animation. If a world model is not present, it is automatically provided together with a warning message. Built-in animation properties of all components, such as joints, forces, bodies, sensors. This allows an easy visual check of the constructed model. Animation of every component can be switched off via a parameter. The animation of a complete system can be switched off via one parameter in the world model. If animation is switched off, all equations related to animation are removed from the generated code. This is especially important for real-time simulation. Automatic handling of kinematic loops. Components can be connected together in a nearly arbitrary fashion. It does not matter whether components are flipped. This does not influence the efficiency. If kinematic loop structures occur, this is automatically handeled in an efficient way by a new technique to transform a certain class of overdetermined sets of differential algebraic equations symbolically to a system where the number of equations and unknowns are the same (the user need not cut loops with special cut-joints to construct a tree-structure).
634 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica •
Automatic state selection from joints and bodies. Most joints and all bodies have potential states. A ModeJica translator, such as Dymola, .will use the generalized coordinates of joints as states if possible. If this is not possible, states are selected from body coordinates. As a consequence, strange joints with 6 degrees of freedom are not necessary to define a body moving freely in space. An advanced user may select states manually from the Advanced menu of the corresponding components or use a Modelica parameter modification to set the stateSelect attribute directly.
•
Analytic solution of kinematic loops. The non-linear equations occuring in kinematic loops are solved analytically for a large class of mechanisms, such as a 4 bar mechanism, a slider-crank mechanism or a MacPherson suspension. This is performed by constructing such loops with assembly joints JointXXX, available in the MultiBody. Joints package. Assembly joints consist of 3 joints that have together 6 degrees of freedom, i.e., no constraints. They do not have potential states. When the motion of the two frame connectors are provided, a non-linear system of equation is solved analytically to compute the motion of the 3 joints. Analytic loop handling is especially important for real-time simulation.
•
Line force components may have mass. Masses of line force components are located on the line on which the force is acting. They approximate the mass properties of a real physical device by one or two point masses. For example, a spring has often significant mass that has to be taken into account. If masses are set to zero, the additional code to handle these point masses is removed. If the masses are taken into account, the calculation overhead is small (the reason is that the occuring kinematic loops are analytically solved). Note that in this Beta-release, not all provided line force components have already an optional mass. This will be fixed in the next release.
•
Force components may be connected directly together, e.g., 3-dimensional springs in series connection. Usually, multi-body programs have the restriction that force components can only be connected between two bodies. Such restrictions are not present in the Modelica multi-body library, since it is a fully object-oriented, equation based library. Usually, if force components are connected directly together, non-linear systems of equations occur. The advantage is often, that this may avoid stiff systems that would occur if a small mass has to be put in between the two force elements. Initialization definition is available via menus. Initialization of states in joints and bodies can be performed in the parameter menu, without typing Modelica statements. For non-standard initialization, the usual Modelica commands can be used. Multi-body specific error messages. Annotations and assert statements have been introduced that provide in many cases warning or error messages that are related to the library components (and not to specific equations as it is usual in Modelica libraries). This requires appropriate support from the Modelica environment. Inverse models of mechanical systems can be easily defined by using motion generators, e.g., Modelica. Mechanics. Rotational. Posi tion. Also, non-standard inverse models can be generated, e.g., when elasticity is present it might be necessary to differentiate equations several times. About 45 functions to operate in a convenient way on orientation objects, e.g., to transform vector quantities between frames, or compute the orientation object of a planar rotation. The basic idea is to hide the actual definition of an orientation by providing essentially an Orientation type together with functions operating on instances of this type. Orientation objects based on a 3x3 transformation matrix and on quaternions are provided. As a side effect, the equations in all other components are simpler and easier to understand.
•
•
•
•
16.8.2 Structuring of the MultiBody Library The classes in the Mul t iBody library are grouped into several sublibraries or packages:
Chapter 16 Modelica Library Overview 635
•
World
Class representing a global inertial coordinate system fixed in ground.
•
Interfaces
•
Parts
• • •
Joints Forces Sensors
• •
Frames Types
•
Visualizers
Coordinate system frame classes and base classes used by the MultiBody sublibraries, Classes for defining rigid bodies which have mass and inertia, massless fixed frame transformationclasses. Classes describingjoints connecting two mechanical parts. Classes modeling 3-D force elements such as springs and dampers. Classes for computing relative kinematic quantities between pairs of frames on bodies or joints. Classes containing functions to transform rotational frame quantities. Classes containing constants and types with choices, especially used to build menus. Classes for supporting animation of vector quantities at connectors.
16.8.3 MultiBody Object Connection Rules As mentioned previously the elements of the Mult iBody library can be connected essentially arbitrarily together when this is physically meaningful.
16.8.4 Modelica.Mechanics.MultiBody.World The model World represents a global inertial coordinate system, which for most models (but not objects moving in space) can be regarded as fixed in the ground. This model servers several purposes: • • •
•
•
It is used as inertial system in which the equations of all elements of the Mul t i Body library are defined. It is the world frame of an animation window in which all elements of the Mult iBody library are visualized. It is used to define the gravityfield in which a multi-body model is present. Default is a uniform gravity field where the gravity acceleration vector g is the same at every position. Additionally, a point gravity field can be selected. It is used to define default settings of animation properties (e.g. the diameter of a sphere representing by default the center of mass of a body, or the diameters of the cylinders representing a revolute joint). It is used to define a visual representation of the world model (= 3 coordinate axes with labels) and of the defined gravity field.
Since the gravity field function is required from all bodies with mass and the global and default settings of animation properties are required from nearly every component, exactly one instance of model World needs to be present in every model on the top level. The basic declaration needs to be: inner Modelica.Mechanics.MultiBody.World world
Note that there must be an inner declaration with the instance name world in order that this world object can be accessed from all objects in the model. When dragging the World model class from the package browser into the diagram layer using the graphic connection editor, this declaration is automatically generated (this is defined via annotations in model World). All vectors and tensors of a mechanical system are resolved in a frame that is local to the corresponding component. Usually, if all relative joint coordinates vanish, the local frames of all components are parallel to each other, as well as to the world frame (this holds as long as a Parts. FixedRotation component is
636 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica not used). In this reference configuration it is therefore as an alternative possible to resolve all vectors in the world frame, since all frames are parallel to each other. This is often very useful. In order to give some visual support in such a situation, in the icon of a World instance two axes of the world frame are shown and the labels of these axes can be set via parameters.
16.8.5 Modelica.Mechanics.MultiBody.lnterfaces This subpackage contains connector and partial models for 3D mechanical components. The connector classes Frame_a and Frame_b are describedin Section 15.10.4.1, page 592.
D ,
r
PartlaLineForce
D Frame_b
Frame_a
Frame
PartialAbsoIuteS9nsor
,
~
PartialEle mentary Joint
~
~
B
PartialRelatlveSensor
~
PartialForce
0
I
~
PartJallW oFrames
PartialVisuallzer
Figure 16-28. Icons for connectorclasses and base classes used by the multibody library.
16.8.6 Modelica.Mechanics.MultiBody.Parts Package Parts contains rigid componerit s of a multi-body system.These components may be used to build up more complicated structures. For example, a part may be built up of a Body and of several FixedTranslation components
~ FIXed
..,
AJ
Ii
FlXedTranslation
.. • -
1;
FlXedFbtation
Body
BodyShape
BodyBox
Body(,V Bnder
Figure 16-29. Icons for basic mechanical parts used to constructmultibody system models.
16.8.7 Modelica.Mechanics.MultiBody.Joints This package contains joint components, that is, idealized, massless elements that constrain the motion between frames. In subpackage Assemblies aggregation joint components are provided to handle kinematic loops analytically (this means that non-linear systems of equations occurring in these joint aggregations are analytically solved, i.e., robustlyand efficiently).
A'isrmt Ie ActuatedA'lsrmtic
Aanar
Sphe~al
H
Awolute
ActuatedRevolute
FreeMltion
SphericalSpherical
~lindrlcal
ltllversalSphertcal
Figure 16-30. Icons for joints in the multibody joints sublibrary.
Ultversal
Chapter 16 Modelica LibraryOverview 637 Source code for these classes is available in Appendix D.
16.8.8 Modelica.Mechanics.MultiBody.Forces This package contains components that exert forces and torques between two frame connectors, e.g., between two parts. ~
t(:~ ~·::;.,;l \/(j
World Foree
lIneForeeWithMass
WorldTorque
WorldForeeAndTorque
~ Danper
Spring
FrameForee
~
SprlngDaril>er Parallel
FrameTorque
FrarreForeeAndTorque
~.
SpringDarrperSerles
Figure
16-31. Icons for force elementsin the multibody forces sublibrary.
16.8.9 Modelica.Mechanics.MultiBody.Frames The subpackage Mul tiBody . Frames contains type definitions and functions to transform rotational frame quantities. The basic idea is to hide the actual definition of an orientation in this package by providing essentially the type Orientation together with functions operating on instances of this type. These functions typically are inlined by most Modelica environments, and therefore give no call overhead. An example is given for every function in Table 6-1. The used variables are declared below: Orientation Real[3,3] Real[3] Real[6] Real
R, RI, R2, R_rel, R_inv; T, T_inv; vI, v2, wI, w2, n_x, n_y, n_z, e, e_x, res_ori, phi; res_equal; L, angle;
Table 16-1.Functions for coordinate transformations and related tasks. Function/type Orientation Rj der_R; res ori = orientationConstraint(R) ; der~Orientation
w2 = angularVelocity2(R,der_R) ; vl v2
resolvel(R,v2)i
=
resolve2(R,vl)
i
[vl,wIJ = multipleResolvel(R, [v2,w2]) ; [v2,w2] = multipleResolve2(R, [vI, wI] ) ; D1 = resolveDyadel(R,D2) ; 02 = resolveDyade2(R,Ol); I R = nullRotation ()
Description An orientation object that describes the rotation of frame 1
(e.g. the global inertial frame) into frame 2 (e.g. the body local frame), often available as frame_a. R. The first time derivative of Frames. Orientation. Return the constraints between the variables of an orientation object (shall be zero). Return angular velocity resolved in frame 2 from orientation object R and its derivative der_ R. Transform vector v2 from frame 2 to frame 1, e.g. from the local to the global inertial frame with frame_a. R as argument. Transform vector vI from frame 1 to frame 2, e.g. from the global frame to the local frame with frame_a. R as argument. Transform several vectors from frame 2 to frame 1. Transform several vectors from frame 1 to frame 2. Transform second order tensor D2 from frame 2 to frame 1. Transform second order tensor 01 from frame 1 to frame 2. Return orientation object R that does not rotate a frame.
638 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica R_inv = inverseRotation(R); R_rel = relativeRotation(Rl,R2); R2
=
absoluteRotation(Rl,R_rel) ; R = planarRotation(e, angle); angle=planarRotationAngle(e, vI, v2); R
axisRotation(i, angle);
R
axesRotations(sequence, angles) ;
angles=axesRotationsAngles(R, sequence) ; phi = smallRotation(R); R from_nxy(n_x, n_y); R from_nxz (n_x, n_z); R from_T (T) ;
Return inverseorientation object. Return relativeorientation object from two absoluteorientation objects. Returnabsolute orientation objectfrom another absolute and a relativeorientation object. Return orientation object of a planarrotation. Return angle of a planarrotation, given the rotationaxis and the representations of a vectorin frame 1 and frame 2. Return orientation object R for rotation around axis i of frame 1. Return rotation object to rotate in sequence around 3 axes. Example: R = axesRotations ({ 1,2,3}, {90, 45, - 90}) ; Return the 3 angles to rotate in sequence around 3 axes to constructthe given orientation object. Returnrotationangles phi validfor a small rotation. Returnorientation objectfrom n_x and n_y vectors. Returnorientation object from n_x and n_z vectors. Return orientation object R from transformation matrix T. Return orientation object R from inverse transformation matrix
R
from T inv (T_inv) ;
R
from_Q (0)
T
to_T(R);
Return transformation matrix T from orientation object R. Return inverse transformation matrix T_ inv from orientation object R. Return quaternion orientation object Q from orientation object
exy = to_exy (R) ;
Return fe_x, e_y] matrix of an orientation object R, with e _x and e _y vectors of frame 2, resolvedin frame 1. Return length L of a vector n_ x. Return normalized vector e_x of n_x such that length of e_x is one.
T_inv.
Return orientation object R from quaternion orientation object
;
Q.
R.
L = length (n_x) ; e x =
no~alize(n_x);
The icons corresponding to these functions are simpleellipticalshapes, as depicted in Figure 16-32. @n
f~n
orientationConstrailt angular elcx:1y2
f@n
reso"eOyade1
f~n
reso e1
@n f@n
reso"eOyade2
nulFbtatlon
f~n
r"o e2
f@9n
@n
rrultipleResolve1
f@n
InverseFbtatlon relatlveRotatbn
f@n
fen
fen fen fen
fen
f@n ''''RLnxz
ft@n f~11 front.T '10"'- _Inv
planarFbtation planarFbtationAngle axisRotation
'",,,,-nxy
fen fen Io_T_ilv
to_Q
f@9 11 to_vector
axesAotatlons axesRotationsAngles
t@n 'IOfl'LQ
re fen n
to_·XV
length
f~
rruftPe solve2
f@n
absokJteAotatlon
f@n
srTBIFbtation
f,pn to_
f@n nornelze
Figure 16-32. Icons for frame transformation functions in the Multibody. Frames sublibrary.
Chapter 16 Modelica Library Overview 639
16.8.10 Modelica.Mechanics.MultiBody.Types In this package types and constants are defined that are used in the Mul t iBody library. The types have additional annotation choices definitions that define the menus to be built up in the graphical user interface when the type is used as parameter in a declaration.
16.8.11
Modelica.Mechanics.MultiBody.Visualizers
Package Vi~ualizers contains components to visualize 3-dimensional shapes. These components are the basis for the animation features of the Mul t iBody library .
•,
~
RxedShape
FlXedFrarre
... -t FlXedArrON
SignalArrON
Figure 16-33. Icons for visualizer elements in the multibody visualizers sublibrary.
16.8.11.1 Modelica.Mechanics.MultiBody.Vlsualizers.Advanced Package Visualizers. Advanced contains components to visualize 3-dimensional shapes with dynamical sizes. Basic knowledge of Modelica is needed in order to utilize the components of this package. These components have also to be used for models, where the forces and torques in the frame connector are set via equations (in this case, the models of the Visualizers package cannot be used, since they all have frame connectors).
ArrON
DoubleArrON
Figure 16-34. Icons for advanced visualizer elements in the multibody visualizers sublibrary.
16.8.11.2 Modelica.Mechanics.MultiBody.Visualizers.lnternal This package contains two subpackages, Lines and FixedLines. Both can be used to define sets of Jines that are located relatively to frame_a. Every line is represented by a cylinder. This allows definition of simple shaped 3-dimensional characters. If the lines are fixed relatively to frame_a, it is more convenient to use model FixedLines.
Figure 16-35. Icons for internal visualizer elements in the Multibody. Visualizers sublibrary.
16.8.12 Modelica.Mechanics.MultiBody.Sensors This subpackage contains sensor elements that can be attached between two distinct points of bodies and joints of the multibody system library.
640 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica A sensor is used to calculate relative kinematic quantities between the two points. In this sublibrary a general 3D sensor element that calculates all relative quantities as well as a line-sensor element are present. Sensor icons are depicted in Figure 16-36below.
RelativeSensor
Fbw 9"
Figure 16-36. Icons for sensor elements in the multibody sensors sublibrary.
16.8.13
Modelica.Mechanics.MultiBody.Examples
The MultiBody. Examples subpackage contains example models to demonstrate the usage of the MultiBody library. We recommend you to open the models and simulate them according to the provided descriptions in the models. A series of pendulumexamples are presented and simulated in Section 15.10.5, page 597.
B
Loops
B
8ementary
Figure 16-37. Icons for examples an examplesublibraries using the multibody systemlibrary.
16.8.13.1 Modelica.Mechanlcs.MultiBody.Examples.Loops
This package contains multibody model examples with kinematic loops. An example of breaking a kinematic loop is also given in Section 15.10.7, page 601.
E~ ~
Eem Engine
E~e E~e E~e
B191n~lyliC Fo~ Fo~
E~e
AanarLoops_analytic
Figure 16-38. Icons for example models with kinematic loops.
16.8.13.2 Modelica.Mechanics.MultiBody.Examples.Elementary
This packagecontains elementary examplesto demonstrate variousfeatures of the MultiBody library.
E~
E~
Dou~~m Force~:es
E~ F~
E~e
E~
~ PendulU~Darrper
E~
1h~; Figure 16-39. Icons for elementary example models.
Chapter 16 Modelica Library Overview 641
16.9 Modelica.Thermal This package contains components to model l-dimensional heat transfer with lumped elements. This allows especially to model heat transfer in machines provided the parameters of the lumped elements, such as the heat capacity of a part, can be determined by measurements (due to the complex geometries and many materials used in machines, calculating the lumped element parameters from some basic analytic formulas is usually not possible). The Modelica.Thermal package contains the following model components and sublibaries:
!;~:r~ &~~~ Heateepee.. Th:~n... Prescribed...
1K R=Efr" ~
Te~rat...
Heatflow...
tJi tl F ' it FM:i CellkJs
~ :
~ ,::
..•..•..............•...... ...•........
: .
...•........•.........
Figure 16-40. Icons for components and sublibraries in Modelica . Thermal. The library is structured into the following sublibraries and components: • Examples: (subpackage) Examples of library usage. Interfaces: (subpackage) Interface definitions. • HeatCapacitor: Lumped thermal element storing heat. • • ThermalConductor: Lumped thermal element transporting heat without storing it. Convection: Lumped thermal element for heat convection. • • BodyRadiation: Lumped thermal element for radiation heat transfer between two bodies FixedTemperature: Fixed temperature boundary condition. • PrescribedTemperature: Variable temperature boundary condition • FixedHeatFlow: Fixed heat flow boundary condition. • PrescribedHeatFlow: Variable heat flow boundary condition. • TemperatureSensor: Absolute temperature sensor. • ReITemperatureSensor: Relative temperature sensor. • • HeatFlowSensor: Sensor to determine the heat flow rate between two ports. Celsius: (subpackage) Elements with Celsius interface. • Fahrenheit: (subpackage) Elements with Fahrenheit interface. • Rankine: (subpackage) Elements with Rankine interface. •
16.10
Hydraulics Library-HyLib and HyLibLight
HyLibLight is a subset of HyLib-a commercial Modelica Library of Hydraulic Components. The library HyLib contains the most important components for modeling hydraulic circuits. Coupling elements exist to connect hydraulic components with blocks of the blocks library and elements of the Mode 1 i ca . Me chani CB library. Full documentation of HyLib is available at www.Modelica.org. Here we just briefly present the component models in HyLibLight. This library supports the following types of models: • • •
Modeling of I-dimensional rotational and translation hydraulic systems. As a state variable the pressure in a lumped volume is used. The inductance of a moving oil column can be added with the model Inductance. Each component of the main library has a lumped volume connected at each port. The components can therefore be connected in any sequence.
642 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
16.10.1
HyLibLight.lnterfaces
II
PorCA
D
PorLB
0
TwoPortComp
-0
0
TwoPortSys
•
0
Aotdmp
0
TwoPortSys
0
0
OnePortComplnput OnePortComplll>ut90 OnePortCompOutput
H)4..ibProperties
D
FlutdProp
Figure 16-41. Iconsfor interface elements in the HyLibLight sublibrary.
16.10.2
HyLibLight.Pumps
These classes model positive displacement pumps and motors. The shafts of the pumps and motors can be connected directly to the rotational library. The control inputs of the variable displacement units can be connected directly to outputs of the control blocks of the blocks library. All components have lumped volumes at the inlet and outlet ports. They also include the inertia of the rotating parts.
clJ Tank
~
-r.
Con ot'
~J
FlowSource
~t
i
~, FlowSourceExtCommand
g
§-D--r
Diesel
Rotor
if g
Asynchron
Figure 16-42. Icons for pump elements in the HyLibLight sublibrary.
16.10.3
HyLibLight.Pumps.Basic
This sublibrary describes ideal or basic components.
r-1-1
TankNoRes
~
IdFtowSource
~,
IdAowSourceExlCommand
~
IdV~P
~,
IdCo~P DiesefNoStates
AsynchronNoStates
Figure 16-43. Iconsfor basicpumpelements in the HyLibLight sublibrary.
16.10.4
HyLibLight.Cylinders
These classes model hydraulic cylinders. All cylinders have lumped volumes at the inlet and outlet ports and a lumped mass for the piston. The models ChamberA and ChamberB model the pressure build up as a function of flow rate and stroke.
Chapter 16 Modelica Library Overview 643
til ,j} @} iiJ
Cylinder1
ChamberA
Cylinder2
ChamberS
Figure 16-44. Icons for cylinder elements in the HyLibLight sublibrary.
HyLibLight.Cylinders.Basic
16.10.5
o
This sublibrary describes ideal or basic components.
Olantier Partial
Figure 16-45. Icon for basic cylinderelement in the HyLibLight sublibrary.
HyLibLight.Valves
16.10.6
This sublibrary describes valves.
8
CheckValve
CheckValveTwo
ThreeWayFC
TwoWayValve
~J SerFlowCont
_._~J
RelieNaive
t!]
{~}
ffi}
,-'
©J
{~,
j---'
t~t
ReduclngVaive
il
ThreePortValve
ShuttleVaive
D lRJ:p
Ii
I
+"P ServoValve
-
PropValve
Figure 16-46. Icons for valve elementsin the HyLibLight sublibrary.
16.10.7
HyLibLight.Valves. Basic
This sublibrary describes ideal or basic components.
8
CheckValveNoStates
t!J
8
CheckValveTwoNoStates
m
~]
RellefValveNoStates
r=-l
tilt
~
SerFlowContNoStates
it
ReduclngValveNoStates
ShuttleValveNoStates
TwoWayValveNoStates
II
PropValveNoStates
It
SolenoidL
SolenoldR
FlowArsa
CheckValvePartla1
ServoValveNoStates
!l. ~
SfcExtCom
~}
MeteringOriTwo
1[l-- ,
ReliefValveExtComNoStates
G' g
ThreePortVetveNoStat.
Ft __I
{~ L.-I
D
SolenoidPartial
Figure 16-47. Icons for basic valve elements in the HyLibLight sublibrary.
644 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
16.10.8
HyLibLight.Restrictions
These classes .mo,del restrictions. All components have lumped volumes at the inlet and outlet ports.
E}
LamRes
fB
'---}
r-~l
t~~-J SimOri
Orifice
Hi' OriPoly
t~' OriCav
Figure 16-48. Icons for restriction elements in the HyLibLight sublibrary.
16.10.9
HyLibLight.Restrictions.Basic
This sublibrary describes ideal or basic components.
t::j
ttJ'
t-~~J
LamResNoStates VarlamResNoStates OrificeNoStates
~ ~._~., ..t-l
C-J
SimOriNoStates r---,j~
+-X,-r L_J
TwoOrifices
-:
OriCavNoStates
OrificeN
OriPolyNoStates
MeteringOriNoStatel
[-x·-l~ l-_.-J OrificePartial
Figure 16-49. Icons for basic restriction elements in the HyLibLight sublibrary.
16.10.10 HyLibLight.Sensors These classes model measurement devices. They are used for control loops that can be modeled with the blocks library.
aMeas
@
PMeas
Figure 16-50. Icons for sensor elements in the HyLibLight sublibrary.
16.10.11 HyLibLight.Sensors.Basic
f@J
Controller
Figure 16-51. Icons for basic sensor elements in the HyLibLight sublibrary.
Chapter 16 Modelica Library Overview 645
16.10.12 HyLibLight.Lines These classes model long lines and the inertia of a moving oil column.
l;';J ~) LongUne
,----1 .-.··b I
{-l
I
L-.-J RigidLine
IndHole
Inductance
Figure 16-52. Icons for line elements in the HyLibLight sublibrary.
16.10.13 HyLibLight.Lines.Basic
,---.D
These classes model long lines and the inertia of a moving oil column.
D
UneBase
I-=,-t
l~r
RlgldLineNoStates
D
UneEntrance
~}
tnductanceNoVolumos
.
I
I
LineMlddte
Ii +
~
L-J
UneExlt
f~}
tndHoJeNoVolumes
Figure 16-S3. Icons for basic line elements in the HyLibLight sublibrary.
16.10.14 HyLibLight.Volumes These classes model the stiffnessof hydraulic volumes and accumulators.
•{IJ
--tIJ
OilVolume
VolumeConst
VolumeTemp
--[IJ
@
~([J
·iIJ
OilVolume2
Accu1
r-l
I I L_.-.I
Accu2
Figure 16-54. Icons for volume elements in the HyLibLight sublibrary.
16.10.15 HyLibLight.Volumes.Basic These basic modelsgive the responseof gas volumes.
.-~ VolumePartiat
~
AccumulatorPartial
1-1
GasVolumaPartia
i~
{!l GasVoIume
r-
GasVolumeBB
i~~lf1
ValveLogic
Figure 16-S5. Icons for volume elements in the HyLibLight sublibrary.
Q46 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica
16.10.16 HyLibLight.Examples d)._._~
~
.- ...-. -'
C'osedCircuit
Cylinder
OpenCircuit
~~.~~ UTM
SecControl
L~-Cont~o , ,
LSControl
Figure 16-56. Icons for example elements in the HyLibLight sublibrary.
16.11
ThermoFluid
The ThermoFluid library provides a framework for the modeling of one-dimensional compressible flow including heat transfer and chemical reactions. It contains physical properties for a large number of ideal gases and some high accuracy equation of state models for technically important fluids: water, carbon dioxide and the refrigerant R134a. The focus of the library are numerically robust and efficient base classes implementing a flexible class structure, the mass- energy and momentum balances and physical properties. ThermoFluid itself does not provide many high-level models except as usage examples, but it has been used successfully in a broad range of industrial and academic applications: modeling of the steam distribution network in a paper plant, micro turbine modeling, modeling of fuel cells including the hydrogen reforming, modeling of advanced refrigeration systems using the natural refrigerant C02 and modeling of a steam power plant for non-linear model predictive control. The ThermoFluid library can be freely downloaded from the ThermoFluid web page and is actively maintained by its authors. It is an advanced and powerfullibrary not recommended for beginners.
16.12
Pneumatics Library-PneuLib and PneuLibLight
The PneuLib library contains the most important pneumatic components needed in order to model pneumatic circuits. Coupling elements exist to connect pneumatic components with blocks of the Modelica. Blocks library and elements of the Modelica. Mechanics library. This library supports the models according to the following principles: • • • • •
Modeling of l-dirnensional rotational and translation pneumatic systems. The behavior of air is modeled as an ideal gas The gas mass and the temperature in a lumped volume are used as state variables. Temperature changes during compression and expansion can be taken into account or neglected. Each component of the main library has a lumped volume connected at each port. These components can therefore be connected in any sequence.
16.12.1
PneuLibLight.lnterfaces
This package contains definitions for the graphical layout of component icons which can be reused in more
•D •.. ,
Chapter 16 Modelica Library Overview 647
DOD
TwoPortComp
PorC1
PneuUbUghtPropemes
muAtr
nuAlr
0
TwoPortSys OnePortComplnput OnePortCompOutput
rhoAir
LongLineConPos
LongUneConNeg
Figure 16-57. Icons for bases classes and connector classes.
PneuLibLight.Supply
16.12.2
This sublibrary describes components used to originate and end an airflow. All of these components have lumped volumes at the nodes and can be connected in an arbitrary way.
Reservoir Reservoir Silencer Line RigidLine LongLine Booster Basic
Huge reservoir with constant pressure and resistance of tank pipe Huge reservoir with externally commanded pressure and resistance of tank pipe Silencer with internal resistance Line with resistance, empirical model Line with resistance, fluid mechanics model Long line with dynamics and resistance Pressure booster More models without lumped volumes at the ports
§
@J Reservoir
ReservoirExtCom
Line
Silencer
B
Capillary
Figure 16-58. Icons for reservoirs and tubes.
16.12.3
PneuLibLight.Supply.Basic
This sublibrary describes ideal or basic components, e.g. without lumped volumes at the ports. Name IdealReservoir IdealReservoirExtCom SurroundingsNoRes LineNoStates RigidLineNoStates CapillaryNoStates LineEntrance LineMiddle LineExit
@J IdealReservoir
Description Huge reservoir with constant pressure Huge reservoir with externally commanded pressure Outlet to the atmosphere, no resistance Line resistance, empirical model Line resistance, fluid mechanics model Long thin line with laminar flow Entrance element of long line model Middle element of long line model Exit element of long line model
EJ
IdealReservoirExtCom SurroundingsNoRes
§
L1neNoStates
Figure 16-59. Icons for ideal models of reservoirs, line tubes, etc.
a
CapillaryNoStates
648 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica
16.12.4
PneuLibLight.Components
@
{Wj
VaneMolor
ThrottleNonRelum
~
RapldExhauslValve
___J ~
RelieNalve
Shuttle'Valve
PressureRegulalorNoRelief
~
NonRetumValve
~
NonRelumOvenideValve
@]
@J
~
PressureRegulalor PressureRegulalorExiCommand
&J
00
8
SoftSlartValve
NOlzle
Figure 16·60. Icons for pneumatic valves and motors.
16.12.5
PneuLibLight.Components.Basic
@§
E]
fril
PressureRegulatorNoStates1
PressureRegulatorExtCommandNoStates
Rtl
RellefValY,NoStates
PressureRegulatorExtReferenceNoStates
~
I I VarNo;ieNOStates
SoftStartNoStates
RapidExhaustNoStates
r=l
L....+L-i
NonReturnOverrldeNoStates
~ - -.!d
~ r=ff
ShuttleValveNoStates
rO'·]
~
NonRetumNoStates
NozzteNOStates
LtJ
~
PressureRegulatorNoRellefNoStates
[2]
g
AowArea
l:J
llnearReslstanceNoStates
@1
IdealMotor3Ports
Figure 16-61. Icons for basic ideal components such as valves, regulators, line resistances, etc.
16.12.6
PneuLibLight.More
This sublibrary models additional components or partsthereof. Name
Description
airVolume with HeatTransfer airVolumeIsotherm m dot Meas pMeas DeltaPMeas ProximitySensor Basic
Lumped volume, heat exchange with surroundings Lumped volume, isotherm => constant temperature Mass flowrate sensor Pressure sensor Differential pressure sensor Proximity sensorfor PLC More models
Chapter 16 ModelicaLibrary Overview 649
[!J
icut-j
I
I I
I
L---t,~
pMeas
airVolumelsotherm
~
I
I: 1+:
; :.
DeltaPMeas
ProximitySensor
Figure 16-62. Icons for lumped volume, flow rate and pressuresensors.
16.12.7
PneuLibLight.More.Basic
This sublibrary models additional components or parts thereof. Name RS bistable airVolumeIsotherm
RS_bistable
Description ~nl
Bistable latch, reset signal dominates Lumped volume with external initialization value, isotherm => constant temperature
[!j
alrVolumelsotherm_ini
Figure 16-63. Icons for bistable latch and volume with externalinitialization.
16.12.8
EJ
First_example
PneuLibLight.Examples
Motor_control
Controller
Figure 16-64. Icons for three model examples: first, motorcontrol, and controller.
16.13
Summary
This chapter has described the Modelica library structure, version 2.1, as presented at the Modelica Association web page at the time of this writing, including the Modelica standard library. The set of available libraries is growing quickly, however, the existing Modelica standard subIibraries are rather welltested and have so far mostly gone through small evolutionary enhancements (with the exception of the Blocks library where a new vectorized version was recently released-the new version is described in this book). For this reason the presentation of the now existing Modelica standard libraries will valid to a large extent, even some time into the future.
16.14
Literature
All the free Modelica libraries described here, including both documentation and source code, can be found on the Modelica web site, www. modelica. org. Documentation for several commercial libraries is also available on the Modelica web site. The respective authors of these libraries, including some documentation text reproduced in this chapter, are listed in the front pages of this book.
650 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica The constant definitions, with name, value, and description, in the Modelica. Constants package are from the following source: (Mohr and Taylor 2000). For more information on units and unit conversion, see (Cardarelli 1997). Basic equations and methods behind the multibody library can be found in (Otter 1995; Otter, Elmqvist, and Cellier 1996), and multi-body systems theory in general in (Shabana, 1998). The new Modelica.Mechanics.MultiBody library is also described in (Otter, Elmqvist, and Mattsson 2003). Use of the HyLib hydraulic library is presented in (Beater, 2000). An early version of the PowerTrain library and some usage examples are described in (Otter, Dempsey, and Schlegel 2000). There is not as yet a general Modelica library available for electric power systems. The ObjectStab library (Larsson 2000) covers some cases. The SPOT library (Wiesmann 2003) is more general, but a complete version is not available at the time of this writing. Modeling of electromagnetic transients in power systems is described in (Bachmann and Wiesmann 2000). The Modelica electrical analog library and its usage is described in (Clauss, Schneider, Leitner, and Schwarz 2000). An electrical digital library is just being released at the time of this writing. ThermoFluid is an advanced thermo-hydraulic library, also including certain chemical reaction phenomena. The library is briefly described in (Tummescheit, Eborn, and Wagner 2000; Tummescheit 2002; Tummescheit, and Ebom 2002), and can be downloaded from the ThermoFluid web page (Tummescheit and Ebort 2003). A Modelica flight dynamics library is presented in (Moormann and Looye 2002), whereas a new gas turbine library is mentioned in (Idebrant 2003).
651
Part IV
Technology and Tools
653
Chapter 17
A Mathematical Representation for Modelica Models
At the beginning of this book, in Section 2.20 on page 57, we briefly explained how a Modelica model is translated to a basic mathematical representation in terms of a flat system of differential and algebraic equations (DAEs) before being able to simulate the model. This translation process elaborates on the internal model representation by performing analysis and type checking, inheritance and expansion of base classes, modifications and redeclarations, conversion of connect equations to basic equations, etc. The result of this analysis and translation process is a flat set of equations, including conditional equations, as well as constants, variables" and function definitions. By the term flat is meant that the object-oriented structure has been broken down to a flat representation where no trace of the object hierarchy remains apart from dot notation within names. However, since discrete and hybrid modeling constructs are an important part of Modelica, a continuous DAB representation is not enough, since discrete variables and discrete state transitions now belong to the basic mathematical state space model for Modelica. This model formalism is called hybrid DAEs, i.e., hybrid differential and algebraic equations. This is analogous to similar definitions for other modeling formalisms, e.g. the finite state automata and DEVS formalisms described in Sections 13.3.5 and 444 respectively, of Chapter 13.
17.1 Defining Hybrid DAEs-a Hybrid Mathematical Representation To make the hybrid DAE representation easier to understand, first recall the basic ODE state space explicit form of the equations for continuous systems, previously presented in Section 2.20.1 on page 58 in Chapter 2, and in Section 12.8.1 on page 402 in Chapter 12. In the special case of an equation system on explicit state space form a DAE system reduces to an ODE system. Here x(t) is the set of state variables, i.e., for an ODE the variables for which time derivatives occur in the model, u(t) represents the input variables, and y(t) represents the output variables and/or algebraic variables. The time dependency of these variables is made explicit by showing these variables as functions of time. The ODE explicit state space form is as follows: x(t) = ](x(t),u(t»
(17-1)
y(t) = g(x(t),u(t» Here
j (t)
and g(t) are vector-valued functions, and x(t), y(t), u(t) are vectors, i.e.:
Yl(t ) ]
y(t)
= : , (
Yr(t)
Ut (t)
u(t) =
:
(
um(t)
]
(17··2)
654 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica By rearranging the terms we obtain the more general DAE implicitform where f(t) == ](x(t),u(t» - x(t) , and g(t) == g(x(t), u(t» - y(t). Also, for a DAB, y(t) also includes algebraic variables as well as output variables, which means that we need to add a possible dependency on y(t) in f(t).
f(x(t), x(t),u(t), yet»~ =0
(17-3)
g(x(t),u(t), y(t» = 0 There is also a rather common semi-explicit form of DAE:
x(t) == f(x(t), y(t), u(t»
(17-4)
y(t) == g(x(t), u(t» Note that for a DAE it is usually not true that the state variables are those for which time derivatives occur. since the DAE contains algebraic constraints which reduce the degrees of freedom of the model, the number of state variables is often fewer than the number of variables that appear differentiated. Moreover, some state variables may be purely algebraic variables, possibly including discrete-time variables.
17.1.1 Continuous-Time Behavior Now we want to formulate the continuous part of the hybrid DAE system of equations including discrete variables. This is done by adding a vector q(te) of discrete-time variables and the corresponding predecessor variable vector qpre(te) denoted by pre (q) in MOOeHca. For discrete variables we use t, instead of t to indicate that such variables may only change value at event time points denoted t.. i.e., the variables q(te) and qpre(te) behave as constants between events. We also make the constant vector p of parametersand constants explicit in the equations, and make the time t explicit. The vector c(te) of condition expressions, e.g. from the conditions of if constructs and when constructs, evaluated at the most recent event at time t, is also included since such conditions are referenced in conditional equations. We obtain the following continuous DAE system of equations that describe the system behavior between events:
f(x(t), x(t),u(t), y(t),t,q(te ),qpre (t e), p,c(te» == 0
(a)
g(x(t),u(t), y(t),t,q(te ),qpre(te ) , p,c(te» = 0
(b)
(17-5)
17.1.2 Discrete-Time Behavior Discrete time behavior is closely related to the notion of an event. Events can occur asynchronously, and affect the system one at time, causing a sequence of state transitions. An event occurs when any of conditions c(te) (defined below) of conditional equations changes value from false to true. We say that an event becomes enabled at the time t-. if and only if, for any sufficiently small value of e, c(te-e) is false and c(te+e) is true. An enabled event is fired, i.e., some behavior associated with the event is executed, often causing a discontinuous state transition. Firing of an event may cause other conditions to switch from false to true. In fact, events are fired until a stable situation is reached when all the condition expressions are false. Discontinuous changes of continuous dynamic variables x(t) can be caused by so-called reini t equations in Modelica, which for the sake of simplicity are excluded from the equation representations discussed in this chapter. However, there are also state changes caused by equations defining the values of the discrete variables q(te) , which may change value only at events, with event times denoted teo Such discrete variables obtain their value at events, e.g. by solving equations in when-equations or evaluating assignments in whenstatements. The instantaneous equations defining discrete variables in when-equations are restricted to
Chapter 17 A Mathematical Representation for Modelica Models 655 particularly simple syntactic forms (Section 8.3.5, page 246), e.g. var = expri . These restrictions are imposed by the Modelica language in order to easily determine which discrete variables are defined by solving the equations in a when-equation. Such equations can be directly converted to equations in assignment form, i.e., assignment statements, with fixed causality from the right-hand side to the left-hand side. Regarding algorithmic when-statements, e.g. Section 9.2.9, page 293, that define discrete variables, such definitions are always done through assignments. Therefore we can in both cases express the equations defining discrete variables as assignments in the vector equation (17-5a), where the vector-valued function fq specifies the right-hand side expressions of those assignmentsto discrete variables. q(te ) := f q (x(t e ), x(te), u(t e), y(te), te, q pre (r,'), p, c(te »
(17-6)
The last argument c(te) is made explicit for convenience. It is strictly speaking not necessary since the expressions in c(te) could have been incorporated directly into fq. The vector c(te) contains all Boolean condition expressions evaluated at the most recent event at time teo It is defined by the following vector assignment equation with the right-hand side given by the vector-valued functionft. This function has as arguments the subset of the discrete variables having Boolean type, i.e., qB (t e ) and q;"e (tt)' the subset of Boolean parameters or constants, p B , and a vector rel(v(t» evaluated at time te , containing the elementary relational expressions from the model. The vector of condition expressions c(te) is defined by the followingequation in assignmentform: c(te ) := !e(qB(te),q:re(te),pB ,rel(v(te »)
(17-7)
Here rel(v(t» = rel(cat(l,x(t),x(t),u(t), y(t),t,q(te),qpre(te),p» , a Boolean-typed vector-valued function containing the relevant elementary relational expressions from the model, excluding relations enclosed by noEvent(). The argument v(t) = {V.,V2, ...} is a vector containing all scalar elements of the argument vectors. This can be expressed using the Modelica concatenation function cat applied to the vectors, e.g. v(t)=cat(l,x,x,u,y,{t},q(te),qpre(te),p). For example, if rel(v(t» = (v) > V2, V3 >= 0, v4= 0, VIO, not Vll, v4
(18-7)
h
Performing a similar substitution as for (18-5) gives the implicit Euler ODE solution method: x(tn+i ) = x(tn ) + h· rv;«. x n+1 )
(18-8)
In this case a small equation system has to be solved at each step.
18.2.1.2 Multistep Methods The Euler method given in (18-5) and (18-6) is an example of a one-step method, since the next value depends on one previous value. In general, a numerical method for solving differential equations can be denoted a k-step method if it depends on k (previous) values: (18-9) The method is called explicit if the next value x n+1 only depends on previous values. It is an implicit method if the function H on the right-hand side also includes x n+1 ' In that case a small equation system has to be solved at each step. Euler's method is an explicit one-step method.
670 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica 18.2.1.3 Local Error The global error is the deviation x(t n ) - x n between the exact and approximate value for x(t). This absolute difference is hard to compute; therefore the one-step or local error en is often used instead: (18-10) This is the error from one step, assuming that all information from previous steps is exact.
18.2.1.4 Stability Keeping the error within bounds is not the only criterion for a numerical method. Each numerical method for solving differential equations has a region of stability. If the step size h is small enough to be within the region of stability, the method is stable; otherwise the computation becomes unstable and strange oscillations appear. Explicit methods have smaller regions of stability than implicit methods. It is instructive to take a look at the solution of a small test problem: model ErrStab
Real z(start=l)i equation
der(z) = -S*(time+l)*zA(2)+S/(time+l)-1/(time+l)A(2)i end ErrStab; We simulate the problem twice, using Euler's method with two different step sizes, h=0.21 and h=0.19, respectively, employing the Mathematica command interface to MathModelica:
simEulerl= Simulate [ErrStab, {t,O,24},Method->Euler, IntervalLength->0.21]; simEuler2= Simulate [ErrStab, {t,0,24},Method->Euler, IntervalLength->0.19]; We compare the results in a plot depicted in Figure 18-1.
PlotSimulation[z[t] ,{t,O,24}, SimulationResult->{simEulerl,simEuler2}J; 1.0 0.8 0.6
0.4 0.2 5
10
15
20
Figure 18-1. Solving the same problem using the Euler method with different step sizes h=O.l9 (stable), and h=O.20 (oscillations). The result is rather dramatic. Even though the difference in step size is quite small the behavior differs substantially. The reason is that the step size is outside the region of absolute stability for the solver. It is important to understand that the absolute stability restriction is indeed a stability, not an accuracy, requirement. For the smaller step size, h=0.19, the solution is stable, but the question is how accurate it is. Therefore, let us compare the solution for this simulation with the exact answer. The equation (18-11) is identical to the differential equation in the ErrS tab model apart from a time offset of 1:
· 5tz2 +---, 5 1 z=2 t
t
z(l) = 1
(18-11)
Chapter 18 Techniques and Research 671 This is one of the rare cases for which an exact analytical solution is available:
1 z(t) =t
(18-12)
Before comparing the results in a plot, we perform a simulation with a much smaller step size and hopefully a smaller error:
simEuler3
=
Simulate [ErrStab, {t,O,24},Method->Euler,IntervalLength->10 A - 4 ] ;
We compare both solutions, simEuler2 with h=O.19 and simEuler3 with h=10-4 ,to the exact solution (see Figure18-2):
PlotSimulation[l/t - z[t-l], {t, 1, 2S}, SimulationResult->{simEuler2}l; PlotSimulation[l/t - z[t-I], {t, 1, 2S}, SimulationResult->{simEuler3}l i
0.015 0.010
10
15
20
25
10
(a) Step size h=O.19
15
20
2S
(b) Step size h=O.OOOI
Figure 18-2. Comparing the exact solution to numerical solutions with step sizes (a) h=O.19 and (b) h=O.OOOl. As expected, decreasing the step size to h= 10-4 gives a much smaller error on the order of 10~ , whereas the previous step length h=0.19 gives an error on the order of 0.01. However, decreasing the step size increases the computational work. Also, decreasing the step size too much is not always feasible when using DAB solvers, as we shall see further on. 18.2.1.5 Stiff Differential Equations
Stiff differential equations have solutions with greatly varying time scales. For example, if we model the bouncing ball problem previously presented in Section 2.15, page 50, as a pure continuous-time problem instead of a hybrid continuous-discrete problem, we may have something close to a stiff model. The reason is the following: while the ball is moving in space it is described by a rather slowly varying function. However, when it touches the ground it bounces and changes speed and direction very suddenly. Large forces cause high accelerations and sudden changes. This effect is described by quickly varying functions for the position, speed, and acceleration of the ball. The solver must take very small steps to accurately compute this part of the behavior. On the other hand, rather long steps were satisfactory while the ball was moving freely in space. Thus, solvers for stiff problems are often adaptive, that is. the step size can be varied during solution. However, there is one more requirement for a stiff model: a slowly varying dynamic component in the solution should be present at the same time as the quickly varying component, e.g. for the ball when it bounces. One example is a bearing ball, which rotates (relatively slowly) around the bearing axis along with the bearing, and at the same time bounces against the cage walls of the bearing.
672 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
18.2.1.6 The Runge-Kutta Methods The simplest Runge-Kutta ODE integration method can be derived by combining numerical integration with the Euler approximation. If we integrate equation (18-2) over the interval (t n ,tn+1 ) we obtain:
,H,
x(tn+1 ) = x(tn)+lt f(t,x(t»dt
(18-13)
t"
Approximating the integral by the value of f at the midpoint of the integration interval, multiplied by the length h of the interval gives: X n+1 =
x n +h· f(t n +t,x(tn +t»
The value x(t n
x(t n
f
(t = tn
+ t) ,
(18-14)
+t) is unknown, but can be computed using the Euler approximation:
+t) ~ t, +t· f(t n ,xn )
(18-15)
We substitute (18-15) into (18-14):
= x n + h .k2 k l = f(t n ,xn )
X n+1
(18-16)
k 2 = f(t n +t,xn +t·kl)
If we make a series expansion we can show that the local error x(t n+l ) - x n+l is O(h 3 ) , i.e., a factor of h smaller than the error using Euler's method. In, general, a Runge- Kutta method is described by the following equations: x n+1 =xn +h·(blk t + ...+bsk s)
r«;
k1 = ,xn ) k 2 =f(tn +c 2 -h.x; +h·a 2t ·k 1 ) k3
= f(t n +c3 -h.x; +h·(a 3 1 -k, +a 32 ·k 2 »
(18-17)
The number s and the different coefficients are chosen depending on the desired order of accuracy p and/or computational efficiency. A common choice of coefficients is the following: the number of coefficients s=4, the order p=4, and all coefficients except the following equal to zero: c 2 = 1/2, c 3 = 1/2, c 4 = 1, a 21 = 1/2, a 32 =1/2, a 43 =1, bl =1/6, b2 =2/6, b3 = 2/6, b4 =1/6. The coefficients are chosen to give the method the desired accuracy level, i.e.: (18-18)
18.2.1.7 The Adams Methods The Adams methods are multistep methods--compute the next step based on a number of previous steps. The coefficients b, are chosen to give the maximum accuracy for the given number of terms. The explicit variant of the method, often called Adams-Bashforth, is specified by (18-19): k
x n = x n-1 + Lb;fn-;
(18-19)
;=1
The explicit methods combine the values explicit cases follow below:
In
from the preceding k steps. The formulas for the simplest
Chapter 18 Techniques and Research 673
k :.: 1: x" =X,,_I + 1"-1 h k =2:
Xn
k = 3:
Xn
k = 4:
= X,,_l + (31'1-1 - 1'1-2)1-
=X n- 1 + (23/'1_1 -16/'1-2 + 5/'1-3)-1'2 Xn = Xn- 1 + (55 In-I - 591n- 2 + 37 In-3 - 9In-4) fr
(18-20)
The implicit variant, called Adams-Moulton, is specified as follows: k-I
(18-21)
x" =X"_I + Lb;I,,-i ;=0
The implicit method uses values x n and I" from the k most recent steps, including the current step since In = f(t n.x,). The simplest implicit formulas are given below:
k = 1: x" = x n-1 + In h
k = 2: x" = X n- l + (I" + I,,-I)t
k =3: x"
k =4:
=X,,-l
+(5/" +8/n- l -
X n =X n - 1+(9/"
(18-22)
f n-2) fr
+19/,,_1- 5/ n_2 + 1,,-3)f4
18.2.1.8 LSODE1, LSODE2, and LSODAR ODE Solvers
LSODEI is a multistep method that uses Adams-Bashforth-Moulton (ABM) formulas. The method varies the step size and the order of the methods to efficiently meet the error tolerance. The method is similar to DEABM (see below) but generally uses a lower order and smaller step size to integrate the system. DEABM is often more efficient if high accuracy is needed. This method is suitable for non-stiff problems. A related method called LSODE2 should be used instead if the problem is stiff. LSODE2 is a multistep BOF method (Backward Difference Formulas). The BDF methods have wide stability regions and are therefore good choices for stiff problems. LSODE2 also uses a Nordseick representation of the fixed step size BDF formula. LSODAR is a combination of LSODEI and 2 together with a root solver to handle discrete events. The method starts with LSODEI and then switches to the stiff solver if any stiffness is detected. For non-stiff problems the solution is very similar to using LSODE 1. 18.2.1.9 DEABM ODE Solver DEABM is another multistep method that uses Adams-Bashforth-Moulton (ABM) formulas. The method varies the step size and the order of the methods to efficiently meet the error tolerance. It uses divided differences to represent the ABM formulas and is considered more stable than the LSODE implementation of ABM formulas. This is a good choice when high accuracy is needed. The method uses higher orders of the ABM formulas and longer step sizes than LSODEI.
18.2.2 Solution of Differential Algebraic Equations (DAEs) As we have seen in the previous sections, when solving an ordinary differential equation (ODE) the problem is to compute, i.e., to integrate, the continuous-time state variables from their derivatives. In the case of ODEs on explicit state space form such as equations (18-1) and (18-2) this is fairly straightforward since the expressions for the derivatives to be integrated are defined by the ODE right-hand side expressions.
674 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica However, as we have stated previously, a general DAE system on implicit form such as (18-23) below typically also includes algebraic equations (18-23b) that express algebraic constraints between nondifferentiated variables:
=0
(a)
h(x(t), u(t), y(t» = 0
(b)
g(x(t), x(t), y(t), u(t»
(18-23)
Here x(t) is the set of unknown differentiated state variables, u(t) are the inputs, and y(t) the algebraic variables that do not appear differentiated. Both parts of (18-23) can be combined into a more compact DAE form with a single vector-valued function F: F(x(t), x(t), y(t), u(t»
=0
(18-24)
The main difference compared to solving an ODE is that solving a DAE may also include differentiation, i.e., calculating the derivatives of certain variables. The reason differentiation may be necessary is that the algebraic equations in many cases express constraints between certain state variables in the vector x(t), but not necessarily directly between their derivatives. However, even though the derivatives are not present in the algebraic constraints, they might be implicitly constrained. For example, Xl = x 2 implies Xl = 2 • Therefore certain constraint equations have to be differentiated to make the constraints explicit in order to directly influence the numerical solver. The differential index of a general DAE system is the minimum number of times that certain equations in the system need to be differentiated to reduce the system to a set of ODEs, which can then be solved by the usual ODE solvers. Even if the system has a higher index it can sometimes be solved directly by numerical methods. We will discuss this topic in more detail in Section 18.2.3.
x
18.2.2.1 Numerical DAE Solvers May Fail For DAE systems with index greater than 1, numerical methods may converge poorly, may converge to the wrong solutions, or may not converge at all. As we have seen, higher index DAE systems may have hidden algebraic constraints between the dependent variables and/or derivatives. Hidden algebraic constraints complicate the problem of providing proper initial conditions for the system and also present difficulties for numerical integration methods. The main cause of these problems is that the differentiation needed by DAE solvers is a numerically sensitive operation in contrast to integration, which is usually stable. Numerical instabilities and loss of precision can easily occur. It does not help to increase precision by decreasing step sizes as we do for ODEs. The reason is that the error in differentiation will increase with decreasing step sizes due to roundoff errors and inaccurate solutions of algebraic equations in previous steps. Such problems might introduce large artificial variations in the solution, e.g. if some part of the system model caused a drastic reduction in step size. For these 'reasons there exists no general-purpose numerical DAE solver for DAEs with index higher than 1, even though there are certain numerical DAE solvers for index 2 DAEs with special structure. This might be a serious situation since many natural models result in DABs of index 2 or index 3. Fortunately, mixed symbolic-numerical techniques can help, as will be described further on. The DAE system can be symbolically transformed into an equivalent low index DAB through so-called index reduction before the numerical solution process is started.
18.2.2.2 The DASSL DAE Solver When the simulation problem is a DAE the method of choice is DASSL (Differential Algebraic System Solver) by Petzold 1982, and continuously improved. This is the default solver used by several Modelica environments. It uses a BDF (Backward Difference Formulas) scheme to solve the DAE, and has been proved very stable and 'reliable for most DAE problems. A special version of DASSL, DASSLRT with a root solver, can be called when events occur in the simulated model; see also Section 18.2.5.5 on crossing
Chapter18 Techniques and Research 675 functions. Newer versions of DASSLRT exist, e.g. the root-finding DAE solver called DASKR included in the latest version of DASPK3.0. Since DASSL uses a BDF formula it can also be used for certain stiff (see Section 18.2.1.5) ODE problems. However, the error formulas in the method are adapted for DAE problems. Therefore it might be better, for example, to use a solver such as LSODE2 for stiff ODE problems if problems arise when using DASSL. 18.2.2.3 Mixed Symbolic and Numerical Solution of DAEs A mixed symbolic and numerical approach to solution of DAEs avoids the problems of numerical differentiation. The DAE is transformed to a lower index problem by using index reduction. The standard mixed symbolic and numerical approach contains the ~ollowing steps:
1. Use Pantelides algorithm (see Section 18.2.4.3) to determine how many times each equation has to be differentiated to reduce the index to one or zero. 2. Perform index reduction of the DAE by analytical symbolic differentiation of certain equations and by applying the method of dummy derivatives (see Section 18.2.4.1). 3. Select the state variables to be used for solving the reduced problem. These can be either selected statically during compilation, or in some cases selected dynamically during simulation. 4. Use a numerical ODE or DAE solver to solve the reduced problem.
In the following we will discuss the notions of index and index reduction in some more detail.
18.2.3 The Notion of DAE Index From the preceding discussion we can draw the conclusion that index is an important property of DAE systems. Consider once more a DAE system on the general form: F(x(t), x(t), y(t), u(t»
=0
(18-25)
We assume that this system is solvable with a continuous solution, given an appropriate initial solution. There are several definitions of DAE index in the literature, of which the following, also called differential index, is informally defined as follows:
•
The index of a DAE system (18-25) is the minimum number of times certain equations in the DAB must be differentiated in order to solve x(t) as a function of x(t), y(t), and u(t), i.e., to transform the problem into ODE explicit state space form.
The index gives a classification of DAEs with respect to their numerical properties and can be seen as a measure of the distance between the DAB and the corresponding ODE. An ODE system on explicit state space form is of index 0 since it is already in the desired form: x(t) = f(t, x(t»
(18-26)
The following semiexplicit form of DAE system is of index 1 under certain conditions:
= f(t, x(t), y(t)
(a)
0= g(t, x(t), y(t»)
(b)
x(t)
(18-27)
The condition is that the Jacobian of g with respect to y, (dg loy)-usually a matrix-e-see (18-29), is nonsingular and therefore has a well-defined inverse. This means that in principle y(t) can be solved as a function of x(t) and substituted into (18-27a) to get state-space form. The solution procedure involves differentiating (I8-27b) to get (18-28a), solving for y, (I8-28b), and finally integrating y to obtain the y to be substituted.
676 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
g g}+ O=(ddy }+(dax dgat g g y =_(d r(d lx-(dg dg ay ax ay at
r
(a) (18-28) (b)
The Jacobian of g with respect to y is defined as follows:
(~~ )=
dg. dy. dg 2 (JYt
dg. aY2 dg 2 aY2
(Jg. (Jy, dg 2 dY,
dg s dYt
dg s dY2
dg s ay,
Y. Y2 where y= y,
g=
g. g2
(18-29)
gs
A DAE system in the general form (18-25) may have higher index than 1. Mechanical models often lead to index 3 DAE systems as exemplified in Section 18.2.3.3. We conclude: •
There is no need for symbolic differentiation of equations in a DAE system if it is possible to determine the highest-order derivatives as continuous functions of time and lower derivatives using stable numerical methods. In this case the index is at most 1. The index is zero for such a DAE system if there are no algebraic variables.
•
A perhaps even simpler way of stating the high index property of a DAE system, allowing for the case when certain variables have a derivative of order higher than 1: •
A DAE system has high index if it is necessary to differentiate certain equations when solving for the highest-order derivatives of the variables.
18.2.3.1 Higher Index Problems Are Natural in Component-Based Models The index of a DAE system is not a property of the modeled system but the property of a particular model representation, and therefore a function of the modeling methodology. A natural object-oriented component-based methodology with reuse and connections between physical objects leads to high index in the general case 24• The reason is the constraint equations resulting from setting variables equal across connections between separate objects. Since the index is not a property of the modeled system it is possible to reduce the index by symbolic manipulations. High index indicates that the model has algebraic relations between differentiated state variables implied by algebraic relations between those state variables. By using knowledge about the particular modeling domain it is often possible to manually eliminate a number of differentiated variables, and thus reduce the index. However, this violates the object-oriented component-based modeling methodology for physical modeling that we want to support. We conclude that high index models are natural, and that automatic index reduction is necessary to support a general object-oriented component-based modeling methodology with a high degree of reuse.
However, it is possible to avoid high index in certain application domains by careful manual control of model formulation and by avoiding certain connections. However, this limits reuse of component models.
24
Chapter 18 Techniques and Research 677
18.2.3.2 Example of High Index Electrical Model As an example of high index that is caused by connection of model components, consider the electrical circuit in Figure 2-21 a, which consists of two connected identical subcircuits each containing one resistor and one capacitor. We will show that this system leads to a DAB with index 2. Interestingly enough, Figure 2-21b shows an equivalent transformed circuit with an index 1 DAE where we have used the usual rules for connecting resistors and capacitors in parallel, illustrating the fact that a problem can be transformed from index 2 to index 1.
R=O.5
R=1
(a) Circuit model with an index 2 DAE system
(b) Equivalentcircuit model with an index 1 DAB system
Figure 18-3. A circuit model (a) resulting in an index 2 DAE, vs. an equivalent circuit (b) giving rise to an index 1 DAE. Both circuits are driven by a current i, which is a known function
or time.
To begin the analysis of the circuit depicted in Figure 18-3a, we first recall the constitutive equations relating voltage and current for resistors and capacitors: v = Rri
(18-30)
v=C·i By using these equations to compute the currents through the resistor and the capacitor in the left part of the circuit, we obtain the following equation since the sum of the two currents is equal to i l :
(18··31) Analogously, the circuit in the right part of Figure 18-3a is described by essentially the same equation: (18-32)
The connections between the left and right parts of the circuit are reflected in the following constraint equations: VI
-v 2 =0
t, + i2
=i
(a)
(18-33)
(b)
The complete DAB system then becomes:
VI +v. -i. =0 V2 + v 2 - i 2=0 VI
(18-34)
-v 2 =0
i. + i 2 = i
=
We differentiate the constraint equation (18-33a) between the state variables, VI - v2 0, to make this constraint explicit also for the differentiated state variables, and replace the original constraint by the differentiated one. The resulting DAE system (18-35) is of index 1 since it has the form (18-27) and is theoretically possible to solve for VI and V2. Thus the original system (18-34) is of index 2.
678 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
VI +vl -il =0 V2 +v2 - i 2=O VI-V2=O i.
(18-35)
+i2 = i
This model results in the following sets of variables, including two state variables: x(t) =
{VJ,V2},
y(t)
= {iJ,i 2 } , u(t)={i}
The new index 1 DAE system (18-35), with consistent the initial values, is mathematically equivalent to the original problem (18-34). Unfortunately, due to numerical imprecision in the solver there is no guar~ntee that a numerical solution to (18-35) will fulfill the original constraint VI - V2 =0 in (18-34). Thus we need improved methods for reducing the index of a DAB system, to which we will return in Section 18.2.4. For comparison, we also derive the equations for the RC circuit in Figure 18-3b, using the usual rules for connecting resistors and capacitors in parallel: II 1 = araue
Rp
R1 • R2
R+R 1
0.5
(18-36)
2
C parallel =C1 + C2 = 2 Here only one state variable is needed. The system is of index 1 since it has the form (18-27):
2v +0.5v-i = 0 i l +i 2 -i = 0
(18-37)
v = 0.5il
This model results in the following sets of variables, including one state variable: x(t) = {VI}, y(t) = {iJ,i 2 } ,
u(t)={i}
18.2.3.3 Examples of High Index Mechanical Models As an example from the mechanical application domain, consider a classical planar pendulum depicted and described in Section 12.7.3-12.7.4, page 400. Using Newton's second law to describe the dynamics of the pendulum results in a nonlinear secondorder differential equation system:
..
x
..
Y
mx = - L F ; my = - L F - mg
(18-38)
where F is the force in the rod, g is the gravitational acceleration, and x,y are the coordinates of the mass m. In order to fully specify the physical system the following geometrical constraint needs to be added:
(18-39) Combining the differential equations from (18-38) and (18-39) we obtain the DAE system of (18-40) below. The geometric constraint does not contain the higher-order derivatives X, y and F. The length constraint equation needs to be differentiated, which yields the system of equations presented in (18-41). The equation system obtained still does not contain the highest derivates and therefore needs to be differentiated once more, resulting in (18-42). In conclusion, the equation system (18-40) has been differentiated twice in order to get the DAB system down to index 1. Therefore the differential index of the system is equal to 3.
Chapter 18 Techniques and Research 679 ••
Y
.0
X
2
+ y2
= L2
(18-40)
..
yp
my=-- -mg L 2xi+2yy =0
x
mx=-- F L
L
L
my=-- F -mg L
..
.. xF mx=--
X
mx=-- p
(18-41 )
(18-42) YF -mg my=-L 2xx+2yy +2xi+2yy = 0 '0
As mentioned regarding the electrical example in the previous section, a transformed index 1 DAE system such as (18-42) is not quite suitable for numerical solvers since the solution tends to drift away from the original constraint (18-39). Fortunatelythe methodof dummy derivativesdescribed in the next section can help. In general, mechanical models often lead to index 3 problems when some kind constraint is involved. Consider a mass, m, at a position x, subject to a force F. Its motionis described by Newton's second law: m.x=F
(18-43)
In robotics and many other mechanical problems the position is constrained to be on a certain trajectory
x R (t) : (18-44) To calculate the force F, the equation x problem.
=x R (t) needs to
be differentiated twice, i.e., a high-index
18.2.4 Index Reduction We have informally shown some examples of reducing the index of a DAE system. However, we need general algorithms to be able to handle DABs resulting from object-oriented models in general. The following two algorithms in combination compute the index and transform DAE systems tolow index system by index reduction. •
•
Pantelides algorithmcan be used to compute the index and to determine which constraintequations should be differentiated, and how many times each equation has to be differentiated in order to reduce the index to one or zero. The method of dummy derivatives for index reduction augments the DAE system with differentiated versions of equations, and replaces some of the differentiated variables with new algebraic variables called dummy derivatives.
Before going into detail about Pantelides algorithm, which is based on graph-theoretical methods, we briefly present an example of using the methodof dummy derivatives for index reduction. 18.2.4.1 The Method of Dummy Derivatives for Index Reduction
In two of the previous examples of DAB systems, Sections 18.2.3.2 and 18.2.3.3, we reduce the DAE index by replacingcertain constraint equations by their differentiated counterparts. Such transformedDAE systems are mathematically equivalent to the original versions but have numerical difficulties since the numerical solution tends to drift and thereby not fulfill the original constraintequations. Such problems are largely avoided by the method of dummy derivatives mentioned above, which augments the DAE system with differentiated versions of constraint equations, i.e., keeps the original constraint equations, and also replaces some differentiated variables with new algebraic variables. In the example DAE system (18-34) we first augment the system with a differentiated version of the third equation instead of replacing it, producingthe following overdetermined system:
680 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
VI +v t -it =0 v2 + v2 - i2 = 0 VI -V 2 = 0
(18-45)
Vz =0 it + i 2 =i
Vt
-
The system is overdetermined since we have 5 equations and 4 variables. To add one additional variable we select one of the derivatives of the differentiated constraint equation to be replaced in all equations by a new variable called vd2' known as a dummy derivative-bence the name of the method.
vt +v t -it =0 vd 2 + v 2 - i 2 = 0 (18-46)
vI-VZ=O
VI
-Vd 2
=0
it + iz = i This new equation system is well determined with 5 equations and 5 variables, and has index 1. 18.2.4.2 Bipartite Graphs Pantelides algorithm and the dummy derivatives index reduction method use a so-called bipartite graph representation of equation systems. A bipartite graph representation has the following characteristics: • • •
A set of nodes representing equations. A set of nodes representing variables. A set of edges between equation nodes and variable nodes, where there is an edge between an equation node and a variable node if the variable or its derivative is present in the equation.
The bipartite graph representation of the pendulum example is depicted in Figure 18-4. Since Modelica only supports syntax for the first-order derivatives we have rewritten equations (18-40) by introducing vx and V y for the velocity components. x eql mv =-!..F x
L
eq2
y
Y F -mg mv· =-Y
L
eq3
F
x + y2
=I3
eq4
Vx
eq5
vy
2
x=v x
y=v y
Figure 18-4. Pendulum modelequations and the corresponding bipartitegraph.
Now we will use this bipartite graph representation when computing the DAE index. 18.2.4.3 Structural DAE Index and Pantelides Algorithm The structural index is a computationally efficient alternative to the previously presented differential index definition of DAE index. Computing the structural index is reduced to the problem of finding maximum weighted matchings of different cardinalities in the bipartite graphs that represent the DAE systems. This method is used by Pantelides algorithm. The following definition of the structural index is closely related to Pantelides algorithm:
Chapter 18 Techniques and Research
681
The structural index istr of a DAE is the minimum number of times that any subset of equations in the DAE is differentiated using Pantelides algorithm.
•
Now, a method that computes or approximates the index based only on structural information needs to be provided. The algorithm for computing the structural index starts by constructing the bipartite graph representation of the DAE system. When considering the bipartite graph representation of the DAE system the numerical values of the coefficients are ignored (e.g. in an expression k*vx, the coefficient k is ignored when constructing the graph). We have the following definitions: A matching M ~ of size n associated to the bipartite graph G is a set of n edges in the graph G where no two edges have a common end node. A perfect matching M ~ covers all nodes in G, i.e., all nodes are connected by exactly one edge. A weight W;j is assigned to each edge (v;, U j ) in the graph G, where the weight is the order of the highest derivative of the variable U j present in the equation Vi. The weight w(M) of a bipartite matching M is defined as the sum of the weights W;j of all edges included in the matching.
•
• • •
An algorithm for computing the structural index and performing index reduction is presented below. Algorithm 18-1: Computing the Structural Index of a DAE and performing index reduction. Input Data: DAE system of differential algebraic equations Result: The numerical value of the structural index istr (G) begin: -Create a bipartite graph representationG of the DAB system. - Assign a weight to each edge (v s u t ) in the graph 0, where the weight is the order of the highest derivative of the variable u t present in the equation v s . - Find all perfect matchings M k of size n in the bipartite graph G.
maxM~
-
= max(w(M k )
,
LWij for all edges
where w(M k)=
(ij) in
Mk
(;'j)eMJ:
- Find all matchings M k of size n-l in the bipartite graph G.
- maxM ~-1 = max(w(M k»' where w(M k) =
L
W;j
for all edges (iJ) in M k
(i,j)eM i
- Compute the structural index as isir (G) = maxM ~-l - maxM ~ + 1 - while( isl r (G) > I ) do - Differentiate the equation corresponding to the equation node that is not covered by the maximum weighted matching M k of size n- t . - Increase the weights of all adjacent edges of the differentiatedequation node with 1. - Recompute the maximum weighted matching M k of size n-l. - Decrement the structural index iSIT (G) =iSIT (G)-1 end while end.
Let us now consider the bipartite graph shown in Figure 18-5a associated to the DAE from (18-40) and below: ..
x L .. Y my=-- F -mg L
mx=-- F
x +y 2
2
=L2
(eql) (eq2)
(eq3)
(18-47)
682 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
x,
Since the highest derivatives y, of second order, are present in the first and the second equation we assign a weight of 2 to the edges (eql, x) and (eq2, y). One perfect matching containing the edges is depicted with thick lines in Figure 18-5b, the other in Figure I8-5c. Edges with weights of 2 because of x, y have weight labels; all other weights are zero. Both perfect matchings have the same total weight 0+2+0 =2, i.e., the maximum total weight maxM~ = 2.
=
x
eql-----< x
2 eql-et----
....--e y
eq2-=--""",*---::i y
eq2.e~-_2.....o y
eql
x
eql
eq2---~--i
y
eq2~-
eq3
F
eq3
F
eq3
F
-o x
(d)
Figure 18-5. (a) Bipartite graph for the DAE system (18-40). (b) Perfect matching of size 3 of the bipartite graph. (c) The other perfect matching of size 3 of the bipartite graph. (d) Matching of size 2 where equation eq3 and variable F have been eliminated from the bipartite graph. The maximum weighted matching of cardinality equal to 2 is shown in Figure 18-5c and has a total weight equal to 4. The structural index is computed as part of the results from Algorithm 18-1:
istr(G) = max(w(M ~-I»
- max(w(M ~» + 1 = 4 - 2 + 1 = 3
The value corresponds to the previous value for the differential index. If we differentiate equation (eq3) in (18-47), create a bipartite graph, and recompute the structural index we obtain the value 2 as it should be since the index has been reduced by one.
18.2.5 Simulation of Hybrid Models Based on Solving Hybrid DAEs A Modelica simulation problem in the general case is a Modelica model that can be reduced to a hybrid DAE as described in 17.1, page 653, in the form of equations (17..5), (17-6), and (17-7), together with additional constraints on variables and their derivatives called initial conditions. This is a generalization compared to a simple simulation problem such as the simple circuit problem shown in Section 2.20.1, page 58, that can be expressed as ODEs. If Modelica in the future is extended with partial differential equations (PDEs), the set of additional constraints will also include boundary conditions. The initial conditions prescribe initial start values of variables and/or their derivatives at simulation time=O (e.g. expressed by the Modelica s tart attribute value of variables, with the attribute fixed true), or default estimates of start values (the start attribute value with fixed = false). The simulation problem is well defined provided that the following conditions hold:
=
• • •
The The The end
total model system of equations is consistent and neither underdetermined nor overdetermined. initial conditions are consistent and determine initial values for all variables. model is specific enough to define a unique solution from the start simulation time to to some simulation time tl'
The initial conditions of the simulation problem are often specified interactively by the user in the simulation tool, e.g. through menus and forms, or alternatively as default start attribute values in the simulation code. More complex initial conditions can be specified through initial equation sections in Modelica.
Chapter 18 Techniques and Research 683
18.2.5.1 Hybrid DAE Solution Algorithm The general structure of the hybrid DAE solution algorithm is presented in Figure 18-6, emphasizing the main structure rather than details. First, a consistent set of initial values needs to be found based on the given constraints, which often requires the solution of an equation system consisting of the initial constraints. Then the hybrid DAE solver checks whether any event conditions in when-equations, whenstatements, if-expressions, etc. have become true and therefore should trigger events. If there is no event, the continuous DAE solver is used to numerically solve the DAE until an event occurs or we have reached the end of the prescribed simulation time. If the conditions for an event are fulfilled, the event is fired, that is, the conditional equations associated with the event are activated and solved together with all other active equations. This means that the variables affected by the event are determined, and new values are computed for these variables. Then a new initial value problem has to be solved to find a consistent set of initial values for restarting the continuous DAE solver, since there might have been discontinuous changes to both discrete-time and continuous-time variables at the event. This is called the restart problem. Of course, firing an event and solving the restart problem may change the values of variables, which in tum causes other event conditions to become true and fife the associated events. This iterative process of firing events and solving restart problems is called event iteration, which must terminate before restarting the continuous DAB solver.
Any Events? Solve continuous DAE and ad vance time until event or end time
Fire event and solve for consistent initial/restart values
End Time? .
Figure 18-6. General structure of hybrid DAB solution algorithm.
The overall structure of the hybrid DAE solution algorithm is displayed in Figure 18-6 and summarized below: 1. Solve an initialization value problem of finding a consistent set of initial values before starting solution of the continuous part, equation (17-5) on page 654, of the hybrid DAB. 2.
Solve the continuous DAE part (17-5) of the hybrid DAE using a numerical DAB solver. During this phase the values of the discrete variables q as well as the values of the conditions c from the when-equations, -statements, if-expressions, etc. of the model are kept constant. Therefore the functions ft ...) and g(...) in (17-5) are continuous functions of continuous variables, which fulfills the basic requirements of continuous DAE solvers.
684 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica 3. During solution of the continuous DAE, all relations rel(...) occurring in the conditions care constantly monitored. If one of the relations changes value causing a condition to change value from false to true, the exact time instant of the change is determined, the continuous DAE solution process is halted, and an event is triggered. 4.
At an event instant, when an event has been fired, the total system of active equations (17-5), (17-6), and (17-7) (Section 17.1.3, page 655) is a mixed set of algebraic equations, which is solved for unknowns of type Real, Boolean, and Integer.
5.
After the processing of an event, the algorithm continues with step (1) of solving the restart problem of finding a consistent set of initial values. After this step solving the continuous part of the hybrid DAE is restarted if the check in (3) does not indicate new events to be processed in (4).
18.2.5.2· Varying Structure of the Active Part of the Hybrid DAE Even though the total hybrid DAB system of equations is structurally time invariant, i.e., the set of variables and the set of equations is fixed over time, it is the case that conditional equations in hybrid DAEs can be activated and deactivated. This means that some variables in the state vectors x and q as well as certain equations can be disabled or deactivated at run-time during simulation, as well as enabled or activated. Such activation or deactivation is caused by events. A disabled variable is kept constant whereas a disabled equation is removed from the total system of active equations that is currently solved. Thus the active part of the hybrid DAB can be structurally dynamic, i.e., at run-time change the number of active variables and equations in the DAE.
18.2.5.3 Finding Consistent Initial Values at Start or Restart As we have stated briefly above, at the start of the simulation, or at restart after handling an event, it is required to find a consistent set of initial values or restart values of the variables of the hybrid DAE equation system before starting continuous DAE solution process. At the start of the simulation these conditions are given by the initial conditions of the problems (including start attribute equations, equations in initial equation sections, etc., see Section 8.4, page 250) together with the system of equations defined by (17-5), (17-6), and (17-7) (see page 655). The user specifies the initial time of the simulation, to, and initial values or guesses of initial values of some of the continuous variables, derivatives, and discrete-time variables so that the algebraic part of the equation system can be solved at the initial time t=10 for all the remaining unknown initial values. At restart after an event, the conditions are given by the new values of variables that have changed at the event, together with the current values of the remaining variables, and the system of equations (17-5), (17-6), and (17-7). The goal is the same as in the initial case, to solve for the new values of the remaining variables. In both of the above cases, i.e., at events, including the initial event representing the start of simulation, the process of finding a consistent set of initial values at start or restart is performed by the following iterative procedure, called event iteration: Known variables: x, u, t, p Unknown variables: i, y,q,qpre'c loop Solve the equation system (1) for the unknowns, with if q = qp~ then exit loop;
q~e
fixed;
qpre := q;
end loop
In the above pseudocode we use the notation qpre corresponding to pre(q) in Modelica.
Chapter 18 Techniques and Research 685
18.2.5.4 Detecting Events During Continuous-time Simulation Event conditions c are Boolean expressions depending on discrete-time or continuous-time model variables. As soon as an event condition changes from false to true, the event occurs. It is useful to divide the set of event conditions into two groups: conditions which depend only on discrete-time variables and therefore may change only when an event is fired, and conditions which also depend on continuoustime variables and may change at any time during the solution of the continuous part of the DAE. We call the first group discrete-time conditions, and the second group continuous-time conditions. The first group causes no particular problems. The discrete-time conditions are checked after each event when the discrete-time variables might have changed. If some of the conditions change from false to true, the corresponding events are simply fired. The continuous-time conditions, however, are more complicated to handle. Each Boolean event condition needs to be converted into a continuous function that can be evaluated and monitored along with the continuous-time DAE solution process. Most numerical software, including DAE solution algorithms, is designed to efficiently detect when the values of specified expressions cross zero.
18.2.5.5 Crossing Functions To be able to detect when Boolean conditions become true, we convert each continuous-time Boolean event condition into a so-called crossing function. Such a function of time crosses zero when the Boolean condition changes from false to true. For example, the simple.condition expression y>S3 changes from false to true when y- 53 crosses zero from being less than zero to being greater than zero, as depicted in Figure 18-7. The body of the corresponding crossing function is simply y- 53.
true false
0
v» 53 y-53
~
event
(a crossing function)
time
Figure 18-7. A boolean condition expression y>S3, with its corresponding crossing function y-53 that crosses zero at the event, thereby determining the time of the event. The decision to react on changes of event conditions in Modelica from false to true rather than from true to false is arbitrary; it could also have been the other way around.
18.2.5.6 Shattering-The Zena Effect An interesting phenomenon called shattering, or the Zeno effect, occurs for certain models (e.g. our wellknown bouncing ball example, Section 2.15, page 50) where events caused by continuous-time conditions becoming true may occur arbitrarily close to each other. In the bouncing ball example the bouncing events occur closer and closer in time-which eventually causes problems for the Modelica crossing function event detection mechanism since some small "epsilon" step size is needed (floating point precision is always limited) to detect when the crossing function switches from being negative to positive. In our Modelica bouncing ball example, after some time (depending on the simulator), the ball falls through the ground. The reason for this behavior ofthe simulator is that the crossing function mechanism needs to determine the time instant when the height becomes negative. However, in order to detect this zero crossing the crossing function need to be computed also for a height of the ball that is actually not
686 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica zero but a small negative number, say -l.e-IO. After restart, the ball velocity of the ball may be so small that it never reaches the height=O boundary and therefore no new event is generated. As a result, the ball flies a little bit higher, say up to -O.5e-l0 and then falls down through the ground.
18.2.6 State Variable Selection for Efficient Simulation In Section 18.2.2 we stated that the continuous-time part of a Modelica model can be represented as a differential algebraicequationsystem (DAE), (18-23),also shown here for convenience: g(x(t), x(t), y(t), u(t» = 0
hi (x(t),u(t), y(t» = 0
(18-48)
where x(t) is the set of dynamic variables, u(t) represents the input variables, and y(t) represents the output variablesand/or algebraicvariables. At least conceptuallythis DAE is transformed into ODE explicit state space form, e.g. (2-4) in Chapter 2 and (18-49) below, to simplifysolution: x(t) = !(x(t),u(t» y(t) = h2 (x(t),u(t»
(18-49)
However, for a DAE not all dynamic variables are needed in the iterative numerical solution of the equation system. There is a vector of state variables x" (t) , which is a subset of the vector x(t), possibly extended by some algebraic variables from y(t). The state variables are independent of each other, whereas the remaining dependent dynamic variables x d (t) and remaning dependent algebraic variabales y d (t) can be computedfrom the state variables. In Chapter 2 we illustrated this transformation for the simple circuit model (see Section 2.20.1, page 58). We summarizeour definition of state variables: •
The set of state variables, X s (t), is a subset of dynamic and algebraic variables that are "independent" of each other. The remaining dependent variables should be directly computable from the state variables.
There are two importantreasonsfor partitioning the equationsystembased on state variables: • •
Increased performance, since iterative numerical solution involving a small set of state variables is usually much faster than for a large numberof variables. Increasednumericalstabilitywith the right choice of state variables.
Modelica environments usually have support for automatic selection of state variables. The selection is static if it does not change during simulation. Certain environments also have dynamic automaticselection, i.e., the set of variables in X s (r) can vary dynamically over time. Automatic selection of state variables is usually both efficient and reliable. Users should not in general need to bother about state variable selection. However, there are certain situations where it is valuable to be able to manually influence the state variable selection,as will be discussedin the next section. 18.2.6.1 Manual State Selection Using the stateSelect Attribute
As we remarked previously, both the efficiencyand the numerical stabilityof a simulationis influencedby the selected set of state variables. The user has the possibility to manually influence the choice of state variables via the stateSelect attribute available for all variables of Real type. This attribute has a default value StateSelect. default. It is an instance of the predefined StateSelect enumeration type with five different enumeration values, whichis defined as follows includinginformative comment strings:
Chapter 18 Techniques and Research 687 type StateSelect = enumeration ( never "Do not use as state at all." avoid "Use as state, if it cannotbe avoided (but only if variable appears differentiated and no other potential state with attribute defaul t , prefer, or a.lways can be selected)." default "Use as state if appropriate, but only if variable appears differentiated." , prefer "Prefer it as stateover thosehaving the defaultvalue (also variables can be selected, whichdo not appeardifferentiated)." , always "Do use it as a state." I
I
) i
For example, a variable x which we would like to influence regarding selection as a state variable can be declared with a modification of the stateSelect attribute. The choice StateSelect .prefer will increase its chances to be selected: Real x(stateSelect = StateSelect.prefer); The different alternatives in the StateSelect enumeration type have the following meaning: • •
•
•
•
never--a variable with this stateSelect value will never be selected as a state variable. avoid--the variable should be avoided as a state variable, i.e., it is selected as a state variable only if it appears differentiated and there is no configuration of state variables without it with defaul t, prefer, or always attribute values. default-this is the default for all Real variables, and means that a variable might be a state variable if its derivative appears in the model. However, the variable does not necessarily become a state variable-this depends on the automatic state selection by the Modelica tool. prefer-the variable is preferably selected as a state variable over those that have the attribute value default, avoid, or never. Note that the variable does not need to appear differentiated in the model in order to be used as a state variable. always--the variable will always be selected as a state variable.
There are several situations where manual state selection might be appropriate to avoid certain problems or to improve performance. Here we mention a few such cases:
•
•
•
•
Numerical cancellation--if there are both variables with relative quantities and variables with large absolute values, e.g. absolute angle and relative angle, it is best to choose the variables with relative quantities as state variables by using StateSelect. prefer. 'The absolute variables can be computed from the relative ones, whereas the other way around can lead to numerical cancellation from differences between almost equal large numbers. Function inversion--by using StateSelect. prefer for variables that usually occur as inputs to certain functions, e.g. thermodynamic property functions, we can avoid numerical function inversion and thereby increase performance. Expensive dynamic state selection--for example, in 3D mechanical systems with kinematic loops a static selection of state variables is not possible and dynamic state selection is often necessary to avoid singularities. However, for many common systems there is a known set of state variables that gives efficient computation and avoid singularities. For example, regarding mechanical joints the relative position and velocity variables of the driving mechanism is such a stable selection that can be chosen by using StateSelect. always. Secondary sensor variables--adding secondary sensor variables just for measurement, for example to compute the velocity which is the derivative of the position, should not influence the selection of the set of state variables. Therefore sensor variables might be marked by the attribute value StateSelect.avoid.
However, in general the best advice is to let state selection be done automatically. Only if there are good reasons in special situations, should we use manual state selection. It is recommended not to use the state
688 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica selection attribute values StateSelect. never and StateSelect. always in Modelica library classes, since it is hard to predict in what context a library class will be used.
18.3 Selected Modelica-Related Research and Language Design The following is a short overview of a selection of Modelica-related research activities and current work on certain language extensions. The overview is by no means complete, and is by necessity and laziness biased toward activities in which the author of this book is involved.
18.3.1 Layered Model Configuration An important problem in industry is to handle complex product configurations and variants. Most products exist in many variants and configurations, caused by evolution over time, customers choices of options, local market adaptations, etc. For example: •
A typical car contains thousands of components, has many variants and adaptations to several countries, and customizations depending on customer choices.
•
Cell phone system software from major vendors is typically installed in different variants in over a hundred countries worldwide, with many local adaptations.
There is clearly a combinatorial explosion of variants and configurations, causing problems in handling, configuring, and maintaining the software and hardware for complex products. The same combinatorial explosion occurs when modeling these products. A simple example is an entertainment control unit (ECU) in a typical car, depicted in Figure 18-8. In this example we have: • •
Choice between two different kinds of CD radios. Optional CD changer and GPS navigation units.
ECU:
Entertainment Control
Unit for Car
Figure 18-8. Car entertainment unit with CD radio variants and optional CD changer and GPS navigation. This gives rise to at least 2 x 2 x 2 = 2 3 = 8 configurations (CD radio variant 1 or 2, with/without CD changer, with/without GPS navigation), which in this particular case is not an impressive number, but quickly increases to astronomical numbers when there are thousands of components, options, and local adaptations. What solutions exist to handle this complexity? Two methods have been applied extensively in the software industry:
Chapter 18 Techniques and Research 689
Conditional compi/ation-eonditional inclusion directives such as the C preprocessor #ifdef ... #endif commands makes it possible to represent many variants within a single software module. Version handling systems-each variant and configuration is explicitly represented, dependencies between versions are tracked to some extent, and compact storage of versions is often supported via computed differences. Some example systems are CVS, secs, RCS, etc.
•
•
However, there are problems as well as advantages with these approaches: •
The conditional compilation approach has the advantage that many configurations can be represented by a single software module. The main disadvantage is that the modules become unstructured and hard understand because of the unstructured mix of pieces from all variants. Another problem is that it is not possible to perform a consistency check without explicitly generating and compiling all variants, which is infeasible in realistic cases.
•
In the version handling system approach, each produced variant or configuration is explicitly represented by a single module or set of models. This makes the modules easier to understand and consistency checks are possible. Another advantage is that software and system evolution over time can be represented. However, the drawback is still the combinatorial explosion of variants and configurations even though only used versions are stored. The maintenance problem also increases-it is clumsy to propagate enhancements and bug fixes between modules.
Can this situation be improved? Perhaps the two approaches can be combined? We would like to find a way to express a conjigurable meta model that can represent a set of model variants and configurations, and is amenable to a consistency checking. However, system evolution over time would still be represented by explicit model versions in a version handing system. 18.3.1.1 The Layer Approach
25
The so-called layer approach to model configuration and variant representation is a proposal for a restricted fonn of conditional inclusion construct in Modelica that allows consistency checking without generating all configurations. The name layer is inspired from layers in CAD drawings. If we take a closer look at variants and configurations, the problem can actually be decomposed into several subproblems: Choice of different variants of a given component, e.g. CDRadio, with no change to the topology of the system structure. 2. Optional inclusion of an anticipated component, e.g. CDChanger or GPSNavigator. In this case the topology can change since the component and the connections to that component may not be present. 3. Possible inclusion of nonanticipated components, changes to the basic system structure, etc. Such (sometimes drastic) changes to the system structure and topology may occur when a system design evolves over a long time period. 1.
A possible layer construct in Modelica would make it easier to express configurable models in the language, by conditional inclusion of optional declarations and equations/connections. When a layer is enabled, its declarations and equations behave as if placed directly within the enclosing class. The structure of the layer construct is as follows:
layer The layer and conditional variant type constructs described in this section were not accepted as part of the standard Modelicalanguage specified by the Modelica Association. Instead, a simpler but almost as powerful conditionalcomponentdeclaration construct was adopted for MOOeHca 2.2. A more cumbersome approach to model configurations using the current Modelica language is described in Section 18.3.1.2.
25
690 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica < equations-connections> end layer;
The first configuration problem, different variants of a given component, could be expressed as follows using the layer construct: layer (constructionYear < 2002) model CDRadio = CD0815 extends /*constrained by*/ Radiolnterface; end layer; layer (constructionYear >= 2002) model CDRadio = CD4711 extends /*constrained by*/ Radiolnterface; end layer; CDRadio cdRadio; However, if a model should be statically checkable, including the contents of all its layers, all those layers need to be simultaneously enabled. This creates a potential problem using the above solution for variant representation since both definitions of CDRadio will be simultaneously available, i.e. a multiple definition conflict. To avoid this problem, a conditional modeldefinition construct could be used: model CDRadio = if constructionYear < 2002 then CD0815 else CD4711 extends I*constrained by*1 Radiolnterface; Multiple definition conflicts are impossible using this construct. The whole EntertainmentUni t model corresponding to Figure 18-8, page 688, is given below using the new layer and conditional model definition constructs: model EntertainmentUnit parameter Boolean cdChangerUnit; parameter Boolean gpsUnit; parameter Integer constructionYear; Port supply; EntertainmentEcu ecu; WirerS] wla, wlb; Wire[4] w2a; Wire[3] w3a; ConnectorBlock xl (numPins=5), ConnectorBlock x2 (numPins=4), ConnectorBlock x3 (numPins=3);
II Variants of single CDRadio model class model CDRadio = if constructionYear < 2002 then CD0815 else CD4711 extends I*constrained by*1 RadioInterface; CDRadio cdRadio; layer (cdChangerUnit) "Conditional topology layer cdChangerUnit" Wire[4] w2b; SomeCDChanger changer; equation for i in 1:4 loop connect(x2.n[i], w2b[i] .p); connect(w2b[il.n, changer.p[il); end for; connect (changer.p [1] , radio.n[l]); end layer; layer (gpsUnit) "Conditional topology layer gpsUnit" Wire [3] w3b; GPSModule gps; equation for i in 1:3 loop connect(x3.n[i], w3b[i] .p); connect{w3b[i] .n, gps.p[i]); end for;
Chapter 18 Techniques and Research
691
end layer; equation II All permanent connections ... end EntertainmentUnit; However, we will need to impose certain restrictions on declarations and equations within the layers to avoid conflicts and make consistency checking possible when all layers are enabled. The second configuration modeling problem, of a checkable model allowing topology changes due to conditional inclusion of anticipated components, can be handled by the model skeleton approach depicted in Figure 18-9. for the EntertainmentUni t model.
!l I
CDRadio variants
ECU
"':,.':-::T,,:'7,:-~~
!
- r: - ..:-::-;-,'1
,'. ,'CQCharigerJ3ase
1::~;:~'·wll:1.:;:,~,(t,:.ii,
.} .: _ .. '~ ....'
~,"'·.~-"·-·""···:r'::·~:"'- ~
"
..
.
'dPSNa~igatOraase
..... - ... -, I
I
Figure 18-9. Skeleton model of car EntertainmentUnit model with empty optional base components. A model skeleton includes (possibly empty) placeholders for all possible anticipated model components and connections. To avoid inconsistencies when all layers are enabled for checking purposes, we impose the following restrictions on layers:
•
H all layers are enabled, then all identifier references should be valid, including type references, instance reference in connections and equations, etc. Duplicate definitions are not allowed. Type variants should be expressed using the conditional short type definition construct.
•
All references in a layer, except in connections, may only refer to identifiers in the same layer or in enclosing layers. All connect-equations referring to identifiers are conditional, i.e., are valid but have no effect if one or more of the connectors are not present.
The idea is that that the layers primarily depend on the surrounding model skeleton, which makes checking feasible without a combinatorial explosion of combinations. The previous EntertainmentUni t model actually fulfils these constraints. However, it is easy to construct models containing violations of these rules, for example the LayerConstraints model below.
model LayerConstraints Real wI, w2; Pin pI; layer Ll 'parameter Integer il = 1; type MyRadio = Integer; Real w3; Pin p2i equation wI = iI; II OK, both wI and il are in enclosing scope connect (p2,p3) ; II Only has effect if both layers Ll and L2 are active end layer; layer L2 parameter Integer i2=iIi MyRadio r; Pin p3i equation w3 = i2; II error
II Error since il is defined in layer Ll II Error since MyRadio defined in other layer
692 Peter Fritzson Principlesof Object-OrientedModeling and Simulation with Modelica end layer; end LayerConstraints;
18.3.1.2 Model Configurations with Current Modelica Base Models and Redeclare A natural question is to what extent checkable model configurations can be specified in the current Modelica language, without the new layer and conditional type variant language extensions. The answer is yes, to a certain extent. We cannot create a single model that represent all configurations as in the previous layer example, but we can create two levels of models that together achieve something similar. In this approach the fixed, nonconfigurable model skeleton is represented by a set of base classes, one for each optional anticipated component, and a model (e.g. EntertainmentUnit) with replaceable declarations for all these optional components, e.g. as follows: model CDChangerBase Pin p [5] ; end CDChangerBase; II Note: class not partial, can be used for components model GPSNavigatorBase end GPSNavigatorBase; model EntertainmentUnit replaceable Radiolnterface Port supply;
cdRadio;
replaceable CDChangerBase cdChanger; replaceable GPSNavigatorBase gpsNavigator; equation connect(x2.n[l:4], cdChanger.p[2:5]); connect(cdRadio.n[l], cdChanger.p[l]); connect(ecu.w3a[l:3], gpsNavigator.p[l:3]); end EntertainmentUnit; model Car replaceable EntertainmentUnit eu; end Car;
Different versions of derived models can be declared as follows. Additional versions can be added when needed. model CDChanger extends CDChangerBase; Wire[4] w2b; replaceable ActualCDChanger cdChanger; equation connect(p[2:5] , w2b(1:4] .p); connect(p[l] , cdChanger.p[l]); connect (w2b[l:4) .n, cdChanger.p[2:5])i end CDChanger; model CDChangerlO=CDChanger(redeclare Magellanl cdChanger}; model GPSNavigator end GPSNavigator;
Finally we express some configurations. In this approach, each configuration has to be expressed using redeclarations of the basic Car model, containing the EntertainmentUnit. In the layer approach, it is enough with simple modifications of EntertainmentUni t, and the set of base classes need not be declared. However, a configuration tool, e.g. with a graphical user interface, could
Chapter 18 Techniques and Research 693 generate these base classes automatically from specified graphical information. Note that a separate model is used to represent each configuration. model Car1999 "Simple configuration example. Disable the GpSNavigator" extends Car(redeclare CD0815 eu.cdRadio, redeclare GPSNavigatorBase eu.gpsNavigator); end Car1999; model Car2002 "Simple configuration example. Just a radio" extends Car(redeclare CD4711 cdRadio); end Car2002; model Car2003 "More advanced configuration example extends Car(redeclare Configurations.CDRadio redeclare Configurations.CDChanger redeclare Configurations.GPSNaviagor
with choices" eu.cdRadio, eu.cdChanger, eu.gpsNavigator);
replaceable package Configuration = Configurations.BaseConfigurations annotation(choices( ... )); encapsulated package Configurations import Basic.*; partial package BaseConfigurations replaceable partial model CDRadio = Radiolnterface; replaceable partial model CDChanger = CDChangerBasei replaceable model GPSNavigator = GPSNaviagtorBasei end BaseConfigurations; package Luxury=Configurations( redeclare model CDRadio = CD5612, redeclare replaceable model CDChanger = CDChanger, redeclare model GPSNavigator = GPSNavigatorlO ) ;
package Standard=Configurations( redeclare model CDRadio CD4711, redeclare model CDChanger = CDChangerBase "Choice of GPSNavigator is left open"; end Configurations; end Car2003; Car2003 myCar(redeclare package Configuration
Car2003.Configurations.Luxury) ;
18.3.2 Debugging Equation-Based Models An equation-based model representation is a high-level representation with many advantages as we have advocated in this book. However, since the abstraction distance between the model representation and the executable simulation code is larger for equation-based languages than for more primitive languages, the debugging problem becomes more challenging. The abstraction distance makes the availability of highquality debuggers an important factor regarding the ease-of-use of equation-based languages. It can be a tricky problem for a model debugger to map between the high-level model representation and the executable code since the equations have undergone many transformations and optimizations before generation of the executable code. You may have encountered problems such as "missing equation" during the model compilation phase-there is some equation missing. However, where should one be inserted? Another important
694 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica problem is to find out exactly which part of a model is causing a deviation from expected model behavior during simulation. We will briefly mention some recent results and ongoing work in static analysis-based debugging, as well as recent research on declarative algorithmic model debugging at run-time. 18.3.2.1 Overconstrained Equation Systems-Too Many Equations
One problem encountered when building equation-based models is the situation when there are too many equations compared to the number of variables. We say that the equation system is overconstrained. Some equation(s) should be removed or additional variables inserted. A static debugging approach has been developed based on static analysis of the bipartite graph representation of the model equations as depicted in Figure 18-10. "eql" "eq2" "eq3" "eq4" "eq5" "eq6" "eq7" "eq8" "eq9" "eqIO" "eqtt" "eql2" "eqI3" "eqI4" "eqt5"
Rl.v • -Rl.n.v + Rl.p.v • Rl.n.i + Rl.p.i 0 Rl.i • Rl.p. i Rl. i Rl.R • Rl. v Rl.i • 23 AC.v. -AC.n.v + AC.p.v 0 '"' AC. n , i + AC. P . i AC. i • AC. P . i AC. vw:AC.VA*sin (2*time*AC. f*AC. PI) G.p.v. 0 AC.p.v • Rl.p.v AC. P • i + Rl. P . i • 0 Rl.n.v • AC.n.v AC.n.v • G.p.v AC.n. i + G.p. i + R1.n.i • 0
"varl" "var2" "var3" "var4" "varS" "var6" "var7" "var8" "var9" "varlO" "varll" "var12" "var13" "yar14"
Rl.p.v Rl.p.i Rl.n.v Rl.n.i Rl.v Rl.i AC.p.v AC.p.i AC.n.v AC.n.i AC.v AC.i G.p.v G.p.!
eql
varl
eq2
var2
eq4
var3
eq3
var4
eq5
var5
eq7
var8
eq6
var6
eq8
varlO
eq9
var7
eql2
varl2
eqlO
var9
eql S
varl4
eqll
well-constrained part
eq13
eq14
overconstrained part
Figure 18-10.Decomposition of the bipartite graphof an overconstrained equation systeminto a wellconstrained and an overconstrained part. The bipartite graph of the equation system is divided into an overconstrained and a well-constrained part. A rather advanced analysis of the overconstrained part can usually pinpoint the error or present a few error alternatives to the user. 18.3.2.2 Underconstrained Equation Systems-Too Few Equations
The companion problem of too many equations is too few equations-e-leading to underconstrained equation systems as shown in Figure 18-11. This is a harder debugging problem to handle since there are usually many alternative error corrections at the intermediate code level. I--------------------~
: eql 1
varl : 1
,
1
, eq2
var2 :
: eq3
var3 :
1 1
,------1-----: eq4 1 1 I : 1 1 I
1 1
part
- --------------------~
var4 : 1
eq5
well-constrained
I
var5 : 1 1 1
var6 2
underconstrained part
Figure 18-11.Matching covering edges marked with fat lines,and decomposition of the bipartitegraph of an underconstrained equationsystem. The bipartite graph is first divided into a well-constrained part and an underconstrained part. The rest of the analysis concerns the underconstrained part, which is subject to two main debugging strategies. The first strategy considers the removal of "free" variables while the second strategy considers the addition of new equations to the equation system. New equations can be introduced at different levels in the model hierarchy. The large number of error correction alternatives may require substantial interaction
Chapter 18 Techniques and Research 695 between the debugger and the user, which fortunately can be reduced through semantic filtering techniques (see below). Another problem is the complex interaction between the under- and overconstrained subsystems when they appear simultaneously. 18.3.2.3 Semantic Filtering of Error Candidates
Semantic filtering means that many error candidates are eliminated before being presented to the user, based on semantic information about the modeling language or design rules related to a model library. For example, connections usually expand into several equations. Therefore those error candidates that only involve deletion or insertion of one of the equations resulting from a connection should not be considered. This is one example of semantic filtering 18.3.2.4 Semiautomatic Algorithmic Model Debugging at Run-Time
The debugging methods mentioned above are static, that is, they perform a static analysis of the model to find errors before the model is executed, i.e., simulated. However, the term "debugging" is usually associated with locating and correcting errors that appear during execution, i.e., during simulation. The simulation results may not be what should be expected for a certain model. We would like to provide debugging support to partially automate the process of finding the part of the model that causes the faulty behavior. There is a method for semiautomatic debugging of programs in declarative languages called algorithmic debugging. This method works by comparing the execution results to a formal or informal specification, and uses this comparison to locate the position of the error in the model. The specification can be provided by the user as a small Modelica model or by answering questions during the debugging procedure. We have previously adapted this technique for declarative lazy functional languages and declarative transformed imperative programs. Our current work is one of the first examples of algorithmic debugging for equation-based languages.
18.3.3 Automatic Generation of Parallel Code from Modellca Using parallel computers is one way of speeding up simulations. However, to actually achieve speedup the code must be parallelized--divided into tasks which can run mostly in parallel.
(a) TaskGraph
(b) Clusteredtask grilpb
Figure 18-12. (a) Task graphwithcommunication cost on the edges,nodenumberin the upperhalf of a circularnodeand node,computation cost in the lowerhalf. (b) Clustered task graph wherethe tasks have beenclustered into two groups with zero internal communication cost and two remaining communication edges between the clusters. Another important condition for speedup is that costly communication between the tasks is minimized. The ratio of work to communication must be sufficiently high. If the amount of work in certain tasks is too small they need to be clustered into bigger tasks, provided that the communication to other tasks is not
696 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica increased. An example of a task graph together with a clustered version of the same task graph is depicted in Figure 18-12. Which parts of the simulation code contain code that can be parallelized? There are essentially three kinds of parallelism in an ODE/DAE simulation: • • •
Parallelism over the numerical method. A small amount of parallelism can be extracted from certain numerical solvers, e.g. Runge- Kutta solvers. Parallelism over time. This is mostly applicable to discrete simulations and to a much lesser extent to continuous simulations which develop sequentially over time. Parallelism over the system of equations, which is the approach taken in this research. This means parallelizing the right-hand sides, that is, the code in the function f in an ODE system and the function g in a DAE system (for example, see equation (17-5)).
The automatic parallelizer builds a detailed task graph of all arithmetic operations and function calls in the right-hand sides. The edges represent data-flow dependences. The most difficult problem in this automatic parallelization effort is to find good algorithms for task clustering combined with good task scheduling. Task duplication can also be used to avoid some communication.
18.3.4 Grey-Box Model Identification Model identification from measurement data is an alternative way of creating a mathematical model of a system. This approach works best for linear systems, but is useful also for certain nonlinear systemspartly since a real system can sometimes be approximated by a linear system within a restricted operating region. In linear identification the mathematical model to be fitted to the measurement data is often a set of difference equations, whereas in nonlinear identification neural networks or local linearizations are used. The usual kind of identification is called black-box identification, meaning that we have no information about the system apart from its interfaces and measurement data of input and output signals. However, a more accurate model with more predictive power can be identified using grey-box identification, meaning that we have some information about the model and would like to identify the rest. For example, we might have an approximate Modelica model with unknown values for a number of model parameters, which could be determined using gray-box identification. A method for identification of linear DAEs have recently been developed, which can be applied to DAEs resulting from linear Modelica models ..
18.3.5 Model Verification Model verification is different from model validation. Model validation compares the model against measurements of the modeled system, and hopefully validates that there is agreement between the real system and the model, for its intended use and with the desired accuracy. By contrast, model verification verifies whether some property of the model holds. For example, we might be interested in verifying that the model is deadlock free, that all combinations of input data give behavior within a reasonable range, etc. Much work on model verification has been done for purely discrete models, e.g. in digital circuit design, based on a static analysis technique called model checking. It is a research challenge to extend this analysis to continuous and hybrid system models.
18.3.6 Diagnosis In the first chapter of this book we mentioned that there are several uses of models, even though we have emphasized simulation throughout most of this text. However, diagnosis is an important use of models and
Chapter 18 Techniques and Research 697 an active research area. Diagnosis is related to model debugging, but there are several differences in approach and point of view. For example, consider a car with a strange faulty behavior. We would like to use a model of the car to help pinpoint which parts of the car might cause the faulty behavior. This can be quite useful for technicians in the repair shop. Many diagnosis approaches are based on probability analysis. For example, interval arithmetic can be used to perform probability-based computation on relevant variable values represented as intervals. A variable value lying outside its normal interval can be traced back to some subsystem with a variable outside its normal interval that is causing the problem in the first place.
18.4 Summary As indicated in the introduction, this chapter covers three topics: numeric and symbolic techniques for simulation, i.e, solution of equation systems e.g. resulting from Modelica models, some Modelica language extension design activities, and a selection of ongoing Modelica-related research. We started the presentation by an introductory discussion of numeric and symbolic solution techniques. Then followed an overview of basic numeric ODE solution techniques, followed by DAB solution techniques building on the ODE techniques. We discussed the index of DAE systems, where high index can lead numerical problems. Symbolic techniques for index computation and index reduction were also presented based on bipartite graph representations of equation systems. Then we presented an algorithm skeleton for solving hybrid DAE systems including automatic detection and handling of events together with solution of the continuous part of the DAE system between events. We also discussed automatic and manual selection of state variables when solving DAEs. Regarding ongoing developments in Modelica Language design, three activities were briefly presented: language extensions to handle PDE problems, user defined overloaded matrix operators e.g. used for convenient access to the external LAPACK library and other matrix libraries, and specification of model configurationsor variants. Finally, the following research activities were briefly described: debugging of equation-based models, automatic generation of parallel code from Modelica, grey-box identification, model verification, and model diagnosis.
18.5 Literature Here we have grouped the literature references for this chapter according to topic. First we present the references for numerical methods, graphic algorithms, and symbolic manipulation and analysis of equation systems: •
•
Numerical methods and solution methods--a short introductionto the solution of ODEs is given in (Ljung and Glad 1994), whereas a more in depth presentation is given in (Brenan, Campbell, and Petzold 1989; Hairer, Nersett, and Wanner 1991). Stiff solvers and models are covered in (Aiken 1985), and methods for stiff and DAE problems in (Hairer and Wanner 1991). Using explicit and implicit Euler methods for Modelica, as well as the mixed mode integration technique, are discussed in (Schiela and Olsson 2000). Sparse Matrix methods are covered by (Duff, Erisman, and Reid 1986). A set of common ODE solverr-ODEPACK--is presented in (Hindmarsh 1983). The DAE solver DASSL is described in (petzold 1982). The DSBLOCK format for interfacing to several solvers is first presented in (Otter 1992). Graph algorithms and theory is presented in (Dolan and Aldous 1993; Gibbons 1985; Gilli and Garbely 1996; Murota, 1987; Murata, 2000; Nuutila and Soisalon-Soininen 1993). Tarja.ns algorithm for finding strongly connected components in graphs is described in (Tarjan 1972).
698 Peter Fritzson Principlesof Object-Oriented Modeling and Simulation with Modelica Bipartite graph coverings and matchings are described in (Dulmage and Mendelsohn 1963; Hopcroft and Karp 1973; Uno 1997; Uno 2001). •
Symbolic manipulation, analysis of equations, and symbolic/numeric solution methods is presented in (Leitold and Katalin 2001; Maffezzoni, Girelli, Lluka 1996; Mah 1990; Ramirez 1998; Ramos, Angel, and Ignasi 1998; Unger, Kroner, and Marquardt 1995). The notion of DAB index is presented in (Gunter and Feldmann 1995; Reissig, Martinson, and Barton 2000). Work on index for partial differential equations has recently appeared (Martinson and Barton 2000), (Elmqvist 2003b). Tearing is discussed in (Mah 1990; Elmqvist and Otter 1994). Dynamic state selection is described in (Mattsson, Olsson, and Elmqvist 2000).
Some of the ongoing work on extending the Modelica language and related technology is presented in the following articles: •
Layers for model configuration (Lunde, Elmqvist, Olsson, Otter, Fritzson 2003).
•
Meta programming, i.e., programming for the sake of constructing and modifying programs, is a common use of Lisp systems (Sandewall 1978; Steele 1990), and Mathematica (Wolfram 1997). Meta programming in general is discussed in (Sheard 2001). Ongoing work regarding meta programming of Modelica models is described in (Aronsson, Fritzson, Saldamli, Bunus, and Nystrom 2003).
Literature references and further reading on the research topics mentioned in this chapter are listed below: •
Modelica equation debugging-Debugging Modelica: (Bunus and Fritzson 2002a; Bunus and Fritzson 2002b; Bunus 2002; Bunus and Fritzson 2002c; Bunus and Fritzson 2003a).
•
Algorithmic debugging for Modelica is described in (Bunus and Fritzson 2003b) whereas algorithmic debugging for other languages is presented in (Shapiro 1982; Fritzson 1993) (Fritzson, Shahmehri, Kamkar, and Gyimothy 1992; Kamkar 1993; Nilsson and Fritzson 1994; Shahmehri, Kamkar and Fritzson 1995; Nilsson 1998). Parallel simulation-automatic parallelization of Modelica models is described in (Aronsson and Fritzson 2002; Aronsson 2002; Aronsson and Fritzson 2003). Parallel simulation-rnanual parallelization, e.g. the BEAST simulator (Fritzson, Fritzson, Nordling, and Persson 1997; Nordling 1996; Nordling 2003). Verification-model checking for model verification: (Clarke, Grumberg, and Peled 2000), and verification in hardware design (Kern and Greenstreet 1999). System identification in general including grey box identification-{Ljung 1999), and identification for linear DAEs (Gerdin, Glad, Ljung 2003). Diagnosis-s-a Modelica-like language extended with uncertainty interval computations is described in (Lunde 2000). Some approaches to.model-based diagnosis in automotive applications are given in (Nyberg and Nielsen 1997; Frisk and Nyberg 2001; Nyberg 2002).
. • • • • •
A general modeling framework for embedded system specification, Ptolemy, is described in (Lee 2001; Lee 2002).
699
Chapter 19
Environments
Several programming environments are currently available for the design and simulation of Modelica models. Certain environments also have facilities for postprocessing results of simulations, 3D visualization of mechanical systems simulation, CAD integration, special support for real-time and hardware-in-the-Ioop simulation, and support for integrated modeling, simulation, postprocessing and documentation. The first full Modelica environment to appear was Dymola, soon followed by MathModelica. The OpenModelica open source environment also supports the full Modelica language but currently does not provide the same level of computational efficiency and solution facilities for tricky equation systems as Dymola and MathModelica, which is essential for handling certain models and class libraries, as well as industrial applications. Some subset implementations are also available from other universities.
19.1 Common Characteristics Most Modelica environments have a number of common characteristics. Models need to be entered and edited, translated to a form that can be executed/simulated, and equation systems to be solved. Therefore essentially all Modelica environments contain variants of the following modules:
•
•
• •
A Modelica compiler or interpreter, translating Modelica to some interpreted form such as byte code or abstract syntax trees, or to a compiled language such as C, C++, etc., which is further translated into executable machine code by standard compilers. An execution and run-time module. This module executes executable code from translated Modelica expressions, functions, and equations. The module include numerical solvers for solution of the resulting equation system as well as event handling facilities for the discrete and hybrid parts of the Modelica language. An editor for textual model editing. This can be any standard text editor, or a special-purpose builtin text editor. A graphical model editor. This is a graphical connection editor for component based model design by connecting instances of Modelica classes.
19.2 OpenModelica The computational and simulation goals of the OpenModelica effort are as follows:
700 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica •
•
Providing an interactive computational environment for the expression, algorithm, and function parts of the Modelica language. It turns out that with support of appropriate tools and libraries, Modelica is very well suited as a computational language for development and execution of both low level and high level numerical algorithms, e.g. for control system design, solving nonlinear equation systems, or to develop optimization algorithms that are applied to complex applications. Providing a rather complete implementation of the Modelica language, including simulation of equation based models and additional facilities in the programming environment. However, the goal is not to reach the level of performance and quality provided by several commercial Modelica environments.
The research related goals and issues of the open source implementation of a Modelica environment include but are not limited to the following: •
•
• • • • •
Development of a complete formal specification of Modelica, including both static and dynamic semantics. Such a specification can be used to assist current and future Modelica implementers by providing a semantic reference, as a kind of reference implementation. Language design, e.g. to further extend the scope of the language, e.g. for use in diagnosis, structural analysis, system identification, etc., as well as modeling problems that require partial differential equations. Language design to improve abstract properties such as expressiveness, orthogonality, declarativity, reuse, configurability, architectural properties, etc. Improved implementation techniques, e.g. to enhance the performance of compiled Modelica code by.generating code for parallel hardware. Improved debugging support for equation based languages such as Modelica, to make them even easier to use. Easy-to-use specialized high-level (graphical) user interfaces for certain application domains. Visualization and animation techniques for interpretation and presentation of results.
The complete formal specification for Modelica was initially developed in Natural Semantics or Structured Operational Sematnics, which is currently the most popular and widely used semantics specification formalism. This specification was used as input for automatic generation of Modelica translator implementations being part of the OpenModelica environment, using the RML compiler generation tool. The availability of a formal specification facilitates language design research on new language constructs to widen the scope of the language, as well as improving its abstract properties. More recently, Modelica is instead specified in the MetaModelica extended subset of Modelica. The OpenModelica environment thus provides a test bench for language design ideas that, if successful, can be submitted to the Modelica Association for consideration regarding possible inclusion in the official Modelica standard.
19.2.1 The OpenModelica Environment The interactive OpenModelica environment currently consists of the following components: •
•
•
An interactive session handler, that parses and interprets commands and Modelica expressions for evaluation. The session handler also contains simple history facilities, and completion of file names and certain identifiers in commands. It is based on the ReadLine library which is available in most Linux and Unix distributions. A Modelica compiler, translating Modelica to C code or lower level code, with a symbol table containing definitions of classes, functions, and variables. Such definitions can be predefined, userdefined, or obtained from libraries. An execution and run-time module. This module currently executes compiled binary code from translated expressions and functions. In the future it will also support simulation of equation based
Chapter 19 Environments
701
models, requiring numerical solvers as well as event handling facilities for the discrete and hybrid parts of the Modelica language. A textual model editor. Any text editor can be used. We have so far primarily employed Gnu Emacs, which has the advantage of being programmable for future extensions. A Gnu Emacs mode for Modelica and a Modelica syntax highlighting for the UltraEdit text editor has previously been developed. There is also a free Modelica editor that recognizes the syntax to some extent, and marks keywords and comments using different colors. Both the Emacs mode and the free editor hides Modelica graphical annotations during editing, which otherwise clutters the code and makes it hard to read. More recent developments include a Modelica Eclipse plugin, with many powerful facilities. A graphical model editor. This is a graphical connection editor, for component based model design by connecting instances of Modelica classes.
•
•
Textual Model Editor
Interactive session
Graphic Model Editor
Execution
Figure 19-1. The architecture of the OpenModelica environment. Arrows denote data and control flow. The interactive session handler receives commands and shows results from evaluating expressions that are translated and executed.
19.2.1.1 Interactive Session with Examples The following is an interactive session with the OpenModelica environment including some commands and examples. First we start the system, which responds with a header line: OpenModelica 1.4.2
We enter an assignment of a vector expression, created by the range construction expression 1:12, to be stored in the variable x. The type and the value of the expression is returned. »
X := 1:12 Integer [12] : {I, 2, 3, 4, 5, 6, 7, S, 9, 10, 11, 12}
The function bubblesort is called to sort this vector in descending order. The sorted result is returned together with its type. Note that the result vector is of type Real I r l , instantiated as Real [12], since this is the declared type of the function result. The input Integer vector was automatically converted to a Real vector according to the Modelica type coercion rules. »
bubblesort(x) Real [12]: {12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, I}
Now we want to try another small application, a simplex algorithm for optimization. First read in a small matrix containing coefficients that define a simplex problem to be solved: » a := read(nsimplex_in.txt n ) Real [6, 9]: {{-I,-I,-I, 0, 0, 0, 0,0, o},
{-I, { 1, { 2, { 3, { 0,
1, 0, 1, 0, 0, 0, 0, S}, 4, 0, 0, 1, 0, 0, 0, 45}, 1, 0, 0, 0, 1, 0, 0, 27}, -4, 0, 0, 0, 0, 1, 0, 24},
0, 1, 0, 0, 0, 0, 1, 4}}
702 Peter Fritzson Principles of Object-OrientedModeling and Simulation with Modelica Then call the simplex algorithm implemented as the Modelica function simplexl. This function returns four results, which are represented as a tuple of four return values: »
simplexl(a) Tuple: 4
Rea 1 [8]: { 9 , 9 , 4, 5 , 0 , 0, 33, o} Real: 22
Integer: 9 Integer: 3
It is possible to compute an expression, e.g. 12: -1: 1, and store the result in a file using the wri te command: » write(12:-l:1,ntest.dat n) We can read back the stored result from the file into a variable y: »
y := read("test.dat") Integer [l2] : {12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
It is also possible to give operating system commands via the system utility function. A command is provided as a string argument. The example below shows system applied to the UNIX command cat, which here outputs the contents of the file bubblesort. rna to the output stream. » system("cat bubblesort.mo") function bubblesort input Real [:] Xi output Real[size(x,l)] y; protected
Real t i algorithm
y
:= Xi
for i in l:size(x,l) loop for j in l:size(x,l) loop if y[i] > y[j] then t := y I i l r
y[i]
:= y[j] i .- t;
y[j]
end if; end for; end for; end bubblesort;
Another built-in command is cd, the change current directory command. The resulting current directory is returned as a string. » cd (" .. ") String: "/home/petfr/modelica"
19.2.2 The Modelica Translation Process The Modelica translation process is depicted in Figure 19-2 below. The Modelica source code is first translated to a so-called flat model. This phase includes type checking, performing all object-oriented operations such as inheritance, modifications etc., and fixing package inclusion and lookup as well as import statements. The flat model includes a set of equations declarations and functions, with all objectoriented structure removed apart from dot notation within names. This process is a partial instantiation of the model (code instantiation), called elaboration in subsequent sections. The next two phases, the equation analyzer and equation optimizer, are necessary for compiling models containing equations. Finally, C code is generated which is fed through a C compiler to produce executable code.
Chapter 19 Environments 703
Figure 19-2. Translation stages from Modelica code to executing simulation.
19.2.3 Modelica Static and Dynamic Semantics The complete semantics, i.e. meaning, of the constructs in any programming language, also including the Modelica language, is usually divided into two major parts: • •
Static semantics. Dynamic semantics.
The static semantics specifies compile time issues such as type checking, equivalence between different representations of the program such as a form with inheritance operations present, and the corresponding form with inheritance and modifications expanded, elaboration of the object-oriented model representation, conversion between different levels of the intermediate form, etc. Such a static semantics is currently given by our formal specification of Modelica, It should be noted that the semantics specification for an equation based language such as Modelica differs from semantics specifications of ordinary programming languages, since Modelica equation based models are not programs in the usual sense. Instead Modelica is a modeling language (specification language) used to specify relations between different objects in the modeled system. The dynamic semantics specifies the run-time behavior including the equation solving process during the simulation, execution of algorithmic code, and additional run-time aspects of the execution process. We do not currently have a formal specification of the Modelica dynamic semantics, but intend to develop such a specification in the future. The current dynamic run-time behavior is based on hand implementation in the C programming language of the primitives referred to by the Modelica flat form intermediate representation.
19.2.3.1 An Example Translation of Models into Equations. As an example, the Modelica model B below is translated into equations, where model B refers to the model A:
704 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica model A Real X,Yi equation x = 2 * Yi end Ai model B A ai Real x[lO]; equation x[S] = a.Yi end B;
The resulting equations appear as follows: B.a.x = 2 * B.a.y B.x[S] = B.a.y
The object-oriented structure is mostly lost which is why we talk about a flat set of equations, but the variable names in the equations still give a hint about their origin. What the translator actually does is translating from the Modelica source code to an internal representation of the resulting set of equations. This internal representation is then further translated to C code. For functions, declarations, and interactively entered expressions, the C code can be generated fairly directly, whereas for equations several optimization stages must be applied before generating the C code.
19.2.4 Automatic Generation and Formal Specification of Translators The implementation of compilers and interpreters for non-trivial languages is a complex and error prone process, if done by hand. Therefore, formalisms and generator tools have been developed that allow automatic generation of compilers and interpreters from formal specifications. This offers two major advantages: • •
High level descriptions of language properties, rather than detailed programming of the translation process High degree of correctness of generated implementations. The high level specifications are more concise and easier to read than a detailed implementation in some programming language
The syntax of a programming language is conveniently described by a grammar in a common format, such as BNF, and the structure of the lexical entities, usually called tokens; are easily described by regular expressions. However, when it comes to the semantics of a programming language, things are not so straightforward. The semantics of the language describes what any particular program written in the language "means", i.e. what should happen when the program is executed, or evaluated in some form. Many programming language semantic definitions are given by a standard text written in English which tries to give a complete and unambiguous specification of the language. Unfortunately, this is often not enough. Natural language is inherently not very exact, and it is hard to make sure that all special cases are covered. One of the most important requirements of a language specification is that two different language implementers should be able to read the specification and make implementations that interpret the specification in the same way. This implies that the specification must be exact and unambiguous. For this reason formalisms for writing formal specifications of languages have been invented. These formalisms allow for a mathematical semantic description, which as a consequence is exact, unambiguous and easier to verify. One of the most widely used formalisms for specifying semantics is called Natural Semantics. A computer processable Natural Semantic specification language called RML, for Relational Meta Language, with a compiler generation tool, has previously been developed at PELAB, and is used for the formal specification of Modelica in the OpenModelica project.
Chapter 19 Environments
705
19.2.4.1 Compiler Generation
Writing a good compiler is not easy. This makes automatic compiler generation from language specifications very interesting. If a language specification is written in a formal manner, all the information needed to build the compiler is already available in a machine-understandable form. Writing the formal semantics for a language can even be regarded as the high-level programming of a compiler. The different phases of the compilation process are shown in Figure 19-3. More specifically, it shows the translation process of a Modelica translator, which compiles, or rather translates, the Modelica source file. All the parts of the compiler can be specified in a formal manner, using different formalisms such as regular expressions, BNF grammars, and Natural Semantics specifications. At all stages, there is a tool to convert the formalism into an executable compiler module. Specification Formalism
Generator Tool
Regular expressions
ANTLRs
BNF
ANTLRp
grammar Natural semantics specification
Representation
• ~
rm/2c
Set of equations -------- and functions
I co~e C
gen
I
- - - - - - C code
Figure 19-3. Phases in generating Modelica compiler modules from different kinds of specifications. The semantics module performs elaboration of the models including type checking and expansion of class structures, resulting in a set of equations, algorithms and functions.
19.2.5 Natural Semantics and RML We have previously mentioned that a compiler generation system called RML is used to produce the Modelica translator in the open source project, from a Natural Semantics language specification. The generated translator is produced in ANSI C with a translation speed and quality comparable to hand-written translators. Below we give a short overview of the Natural Semantics formalism, and the corresponding RML specification language for expressing Natural Semantics in a computer processable way.
19.2.5.1 Natural Semantics A Natural Semantics specification consists of a number of rules, similar to inference rules in formal logic, A rule has a structure consisting of clauses above a horizontal line followed by a clause under the line. A clause such as a => b means a gives b.
c=>bl\e=>! a=:)b All clauses above the line are premises, and the clause below the line is the consequence. To prove the consequence, all the premises need to be proved. A small example of how rules typically appear is shown
706 Peter Fritzson Principles of Object-OrientedModeling and Simulationwith Modelica below, where a rule stating that the addition of a Real expression with an Integer expression gives a Real result. typeof(el) => Real Atypeof(e2) => Integer elaborate(el + e2)
=> Real
19.2.5.2 RML As mentioned previously, Modelica semantics was initially specified using the RML specification language, which is based on Natural Semantics and uses features from languages like SML (Standard ML) to allow for strong typing and datatype constructors. The RML source, e.g. a Modelica specification, is compiled by an RML compiler (rml2c) to produce a translator for the described language. The RML compiler generates an efficient ANSI C program that is subsequently compiled by an ordinary C compiler, e.g. producing an executable Modelica translator. The RML tool has also been used to produce compilers for Java, Pascal and a few other languages.
19.2.5.3 Correspondence between Natural Semantics and RML. The correspondence between Natural Semantics and RML is perhaps easiest to understand using an example. The following three Natural Semantics rules specifies the types of expressions containing addition operators and Boolean constants: typeof(el) => Real Atypeof(e2) => Real typeof(el + e2) => Real
typeof(el) => Integerl Atypeof(e2) => Integer typeof(el + e2) => Integer
typeof(FALSE) => Boolean The corresponding three RML rules are collected in a relation called typeof, which maps expressions to types: =>
relation typeof :: Exp rule
typeof(el)
=>
rule
typeof(el)
typeof(ADD(el,e2» axiom end
=>
=
Real & typeof(e2) =>
typeof(ADD(el,e2»
Type
=>
Real
Integer & typeof(e2) =>
typeof(FALSE)
Real
=>
Integer
Integer =>
Boolean
19.2.6 The Formal Specification of Modelica in Extended Modelica The specification is separated into a number of modules, to separate different stages of the translation, and to make it more manageable. This section will very briefly cover some of the most important parts of the specification. In all, the specification contains many thousand lines of the MetaModelica extended subset of Modelica. The top level function in the semantics is called main, in RML (left) and MetaModelica (right):
Chapter 19 Environments 707
relation main = rule Parser.parse(f) => ast & SCode.elaborate(ast) => seodel & Inst.elaborate(seode1) => seode2 & DAE.dump(scode2) & main ( [f] ) end
function main input String f; II file name algorithm ast := Parser.parse(f); seodel := SCode.elaborate(ast); seode2:=Inst.elaborate(scodel); DAE.dump(seode2); end main;
19.2.6.1 Parsing and Abstract Syntax The function Parser. parse is actually written in C, and calls the parser generated from a grammar by the ANTLR parser generator tool. This parser builds an abstract syntax tree (AST) from the source file, using the AST data types in a MetaModelica module called Absyn. The parsing stage is not really part of the semantic description, but is of course necessary to build a real translator.
19.2.6.2 Rewriting the AST The AST closely corresponds to the parse tree and keeps the structure of the source file. This has several disadvantages when it comes to translating the program, and especially if the translation rules should be easy to read for a human. For this reason a preparatory translation pass is introduced which translates the AST into an intermediate form, called Seode. Besides some minor simplifications the SCode structure differs from the AST in the following respects: •
•
All variables are described separately. In the source and in the AST several variables in a class definition can be declared at once, as in Real x, y [1 7] ;. In the SCode this is represented as two unrelated declarations, as ifit had been written Real Xi Real y [17] i. Class declaration sections. In a Modelica class declaration the public, protected, equation and algorithm sections may be included in any number and in any order, with an implicit public section first. In the SCode these sections are collected so that all public and protected sections are combined into one section, while keeping the order of the elements. The information about which elements were in a protected section is stored with the element itself.
One might have thought that more work could be done at this stage, like analyzing expression types and resolving names. But due to the nature of the Modelica language, the only way to know anything about how the names will be resolved during elaboration is to do a more or less full elaboration. It is possible to analyze a class declaration and find out what the parts of the declaration would mean if the class was tc be elaborated as-is, but since it is possible to modify much of the class while elaborating it that analysis would not be of much use.
19.2.6.3 Elaboration and Instantiation 1'0 be executed, classes in a model need to be instantiated, i.e. (code) and data objects are created according to the class declaration. There are two phases of instantiation:
•
•
The symbolic, or compile time, phase of instantiation (code instantiation) is usually called elaboration. No data objects are created during this phase. Instead the symbolic internal representation of the model to be executed/simulated is transformed, by performing inheritance operations, modification operations, aggregation operations, etc. The creation of the data object, usually called instantiation (data instantiation) in ordinary objectoriented terminology. This can be done either at compile time or at run-time depending on the circumstances and choice of implementation.
The central part of the translation is the code instantiation or elaboration of the model. The convention is that the topmost model in model instance hiearchy implicitly given in the source file is elaborated, which means that the equations in that model declaration, and all its subcomponents, are computed and collected.
708 Peter Fritzson Principlesof Object-OrientedModeling and Simulationwith Modelica The elaboration of a class is done by looking at the class definition, elaborating all subcomponents and collecting all equations, functions, and algorithms. To accomplish this, the translator needs to keep track of the class context. The context includes the lexical scope of the class definition. This constitutes the environment which includes the variables and classes declared previously in the same scope as the current class, and its parent scope, and all enclosing scopes. The other part of the context is the current set of modifiers which modify things like parameter values or redeclare subcomponents. model M constant Real c = 5; model Foc parameter Real p = 3; Real X; equation X = P * sin (time) + c; end Foo; Fcc f(p
= 17);
end M; In the example above, elaborating the model M means elaborating its subcomponent f, which is of type Fco. While elaborating f the current environment is the parent environment, which includes the constant c. The current set of modifications is (p = 17), which means that the parameter p in the component f will be 17 rather than 3.
19.2.7 Summary of OpenModelica The first version of the OpenModelica environment was to a large extent based on a Modelica compiler automatically generated from a formal Natural Semantics specification of Modelica. This formal specification was recently converted into a specification using extended Modelica (MetaModelica) intended to become a reference specification and implementation for Modelica users and implementors. Recent extensions to the OpenModelica environment is an Eclipse plugin and a free electronic notebook. One goal for the open source project is to provide an interactive and efficient computational environment for using Modelica as a high level strongly typed programming language for computational applications. Other goals include research as well as providing simulation of equation based models in Modelica, however with somewhat lower performance and handling models of less complexity than what is currently managed by commercial implementations such as Dymola and MathModelica.
19.3 MathModelica MathModelica is an integrated interactive development environment for advanced system modeling and simulation. The environment integrates Modelica-based modeling and simulation with graphic design, advanced scripting facilities, integration of program code, test cases, graphics, and documentation. Mathematical type setting and symbolic formula manipulation are provided via an optional connection to Mathematica. The user interface consists of a graphical model editor and optional electronic notebooks. The model editor is a graphical user interface in which models can be assembled using components from a number of standard Modelica libraries. Notebooks are interactive documents that combine simulation models and technical computations with text, graphics, tables, code, and other elements, i.e, so called literate programming. The accessible MathModelica internal form allows the user to extend the system with new functionality, as well as performing queries on the model representation and write scripts for automatic model generation. Furthermore, extensibility of syntax and semantics provides additional flexibility in adapting to unforeseen user needs.
Chapter 19 Environments 709
19.3.1 Background Traditionally, simulation and accompanying activities have been expressed using heterogeneous media and tools, with a mixture of manual and computer-supported activities: • • • • •
A simulation model is traditionally designed on paper using traditional mathematical notation. Simulation programs are written in a low-level programming language and stored on text files. Input and output data, if stored at all, are saved in proprietary formats needed for particular applications and numerical libraries. Documentation is written on paper or in separate files that are not integrated with the program files. The graphical results are printed on paper or saved using proprietary formats.
When the result of the research and experiments, such as a scientific paper, is written, the user normally gathers together input data, algorithms, output data and its visualizations as well as notes and descriptions. One of the major problems in simulation development environments is that gathering and maintaining correct versions of all these components from various files and formats is difficult and error-prone. The MathModelica vision of a solution to this set of problems is to provide an integrated computersupported modeling and simulation environment that enable the user to work effectively and flexibly with simulations. Users will then be able to prepare and run simulations as well as investigate simulation results. Several auxiliary activities accompany simulation experiments: requirements are specified, models are designed, documentation is associated with appropriate places in the models, input and output data as well as possible constraints on such data are documented and stored together with the simulation model. The user should be able to reproduce experimental results. Therefore input data and parts of output data as well as the experimenter's notes should be stored for future analysis. 19.3.1.1 Integrated Interactive Programming Environments An integrated interactive modeling and simulation environment is a special case of programming environments with applications in modeling and simulation. Thus, it should fulfill the requirements both from general integrated environments and from the application area of modeling and simulation mentioned in the previous section. The main idea of an integrated programming environment in general is that a number of programming support functions should be available within the same tool in a well..integrated way. This means that the functions should operate on the same data and program representations, exchange information when necessary, resulting in an environment that is both powerful and easy to use. An environment is interactive and incremental if it gives quick feedback, e.g. without recomputing everything from scratch, and maintains a dialogue with the user, including preserving the state of previous interactions with the user. Interactive environments are typically both more productive and more fun to use. There are many things that one wants a programming environment to do for the programmer, particularly if it is interactive. What functionality should be included? Comprehensive software development environments are expected to provide support for the major development phases, such as: • • • •
Requirements analysis. Design. Implementation. Maintenance.
A programming environment can be somewhat more restrictive and need not necessarily support early phases such as requirements analysis, but it is an advantage if such facilities are also included. The main point is to provide as much computer support as possible for different aspects of software development, to free the developer from mundane tasks so that more time and effort can be spent on the essential issues. The following is a partial list of integrated programming environment facilities, some of which are already mentioned in (Sandewall 1978), that should be provided for the programmer:
710 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica •
Administration and configuration management of program modules and classes, and different versions of these. Administration and maintenance of test examples and their correct results. Administration and maintenance of formal or informal documentation of program parts, and automatic generation of documentation from programs. Support for a given programming methodology, e.g. top-down or bottom-up. For example, if a topdown approach should be encouraged, it is natural for the interactive environment to maintain successive composition steps and mutual references between those. Support for the interactive session. For example, previous interactions should be saved in an appropriate way so that the user can refer to previous commands or results, go back and edit those, and possibly re-execute. Enhanced editing support, performed by an editor that knows about the syntactic structure of the language. It is an advantage if the system allows editing of the program in different views. For example, editing of the overall system structure can be done in the graphical view, whereas editing of detailed properties can be done in the textual view. Cross-referencing and query facilities, to help the user understand interdependences between parts of large systems. Flexibility and extensibility, e.g. mechanisms to extend the syntax and semantics of the programming language representation and the functionality built into the environment. Accessible internal representation of programs. This is often a prerequisite to the extensibility requirement. An accessible internal representation means that there is a well-defined representation of programs that are represented in data structures of the programming language itself, so that userwritten programs may inspect the structure and generate new programs. This property is also known as the principle of program-data equivalence.
• • •
•
•
• • •
19.3.1.2 Vision of Integrated Interactive Environment for Modeling and Simulation The vision for the MathModelica integrated interactive environment is to fulfill essentially all the requirements for general integrated interactive environments combined with the specific needs for modeling and simulation environments, e.g.: • • • • • • • •
Specification of requirements, expressed as documentation and/or mathematics; Design of the mathematical model; Symbolic transformations of the mathematical model; A uniform general language for model design, mathematics, and transformations; Automatic generation of efficient simulation code; Execution of simulations; Evaluation and documentation of numerical experiments; Graphical presentation.
The design and vision of MathModelica is to a large extent based on earlier experience in research and development of integrated incremental programming environments, e.g. the DICE system and the ObjectMath environment, and many years of intensive use of advanced integrated interactive environments such as the InterLisp system and Mathematica. The InterLisp system was actually one of the first really powerful integrated environments, and still beats most current programming environments in terms of powerful facilities available to the programmer. It was also the first environment that used graphical window systems in an effective way, e.g. before the Smalltalk environment and the Macintosh window system appeared. Mathematica is a more recently developed integrated interactive programming environment with many similarities to InterLisp, containing comprehensive programming and documentation facilities, accessible intermediate representation with program-data equivalence, graphics, and support for mathematics and computer algebra. Mathematica is more developed than InterLisp in several areas, e.g. syntax,
Chapter 19 Environments 711 documentation, and pattern-matching, but at the time of this writing less developed in programming support facilities.
19.3.1.3 Mathematlca and Modelica It turns out that the Mathematica is an integrated programming environment that fulfils many of the requirements. However, it currently lacks object-oriented modeling and structuring facilities as well as generation of efficient simulation code needed for effective modeling and simulation of large systems. These modeling and simulation facilities are provided by the Modelica language. The Mathlvlodelica solution to the problem of a comprehensive modeling and simulation environment is to combine Mathematica and Modelica into an integrated interactive environment. This environment provides an internal representation of Modelica that builds on and extends the standard Mathematica representation, which makes it well integrated with the rest of the Mathematica system. The realization of the general goal of a uniform general language for model design, mathematics, and symbolic transformations is based on an integration of the two languages Mathematica and Modelica into an even more powerful language called the MathModelica language. This language is Modelica in Mathematica syntax, extended with a subset of Mathematica. Only the Modelica subset of MathModelica can be used for object-oriented modeling and simulation, whereas the Mathematica part of the language can be used for interactive scripting. Mathematica provides representation of mathematics and facilities for programming symbolic transformations, whereas Modelica provides language elements and structuring facilities for objectoriented component based modeling, including a strong type system for efficient code and engineering safety. However, this language integration is not yet realized to its full potential in the current release of MathModelica, even though the current level of integration provides many impressive capabilities. Future improvements of the MathModelica language integration might include making the object-oriented facilities of Modelica available also for ordinary Mathematica programming, as well as making some of the Mathematica language constructs available also within code for simulation models. The current MathModelica system builds on experience from the design of the ObjectMath modeling language and environment, early MathModelica prototypes, as well as on results from object-oriented modeling languages and systems such as Dymola and Omola, which together with ObjectMath and a few other object-oriented modeling languages have provided the basis for the design of Modelica. ObjectMath was originally designed as an object-oriented extension of Mathematica augmented with efficient code generation and a graphic class browser. In many ways the MathModelica product can be seen as a logical successor to the ObjectMath research prototype.
19.4 The MathModelica Integrated Interactive Environment The MathModelica system consists of three major subsystems that are used during different phases of the modeling and simulation process, as depicted in Figure 19-4 below.
~--.I ......
'----{
........
---_.....
Figure 19-4. The MathModelica system architecture. These subsystems are the following: •
The graphic Model Editor used for design of models from library components.
712 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica • • •
The optional interactive Notebook facility, for literate programming, documentation, running simulations, scripting, graphics, and symbolic mathematics with optional Mathematica coupling. The Simulation center, for specifying parameters, running simulations and plotting curves. The optional 3D graphics and CAD subsystem, discussed in Section 15.11, page 611.
A menu palette enables the user to select whether to use the Notebook interface for editing and simulations, or the Model Editor combined with the Simulation Center graphical user interface. Additionally, MathModelica is loosely coupled to two optional subsystems for 3D graphics visualization and automatic translation of CAD models to Modelica, A key aspect of MathModelica is that the modeling and simulation is done within an environment that also provides a variety of technical computations. This can be utilized both in a preprocessing stage in the development of models for subsystems as well as for postprocessing of simulation results such as signal processing and further analysis of simulated data.
19.4.1 Graphic Model Editor The MathModelica Model Editor is a graphical user interface for model diagram construction by "dragand-drop" of model classes from the Modelica Standard Library or from user defined component libraries, visually represented as graphic icons in the editor. A screen shot of the Model Editor is shown in Figure 19-5. In the left part of the window three library packages have been opened, visually represented as overlapping windows containing graphic icons. The user can drag models from these windows and drop them on the drawing area in the middle of the tool.
:. r: . G;J dr _
"_
_
...__
....~
~ m"""''-~l.. '~'-~'J"."-~""'-.-'-' •.•..•. r .
x
....
r..~
~
f
.
,,~.
:t
'.
.
,,~
. •l
·:···:··m··
Figure 19-5. The Graphic Model Editor with the class browser to the left, the graphic editing area in the middle and the instance component browser to the right. Courtesy MathCore Engineering AB. The Model Editor depicted in Figure 19-5 is implemented based on the Qt graphical library, which means that it also can easily be ported to the Linux, Unix, and MacinTosh platforms.
Chapter 19 Environments 713 The Model Editor can be viewed as a user interface for graphical programming in Modelica. Its basic functionality consists of selection of components from libraries! connection of components in model diagrams, and entering parameter values for different components For large and complex models it is important to be able to intuitively navigate quickly through component hierarchies. The Model Editor supports such navigation in several ways. A model diagram can be browsed and zoomed. The Model Editor is well integrated with optional interactive electronic Notebooks via the optional Mathematica coupling. A model diagram stored in a notebook is a tree-structured graphical representation of the Modelica code of the model, which can be converted into textual form by a command.
19.4.1.1 Simulation Center The Simulation Center is a subsystem for running simulations, setting initial values and model parameters, plot results, etc. These facilities are accessible via a graphic user interface accessible through the simulation window (Figure 19-6). However, remember that it is also possible to run simulations from the textual user interface available in the notebooks.
~11
:t~
,:-t :"t~
n (~t~ntVolt.t ,n a fMfl
:'!': ..1c
,n :';"!
(in:Q'xit .Ir~:ft~~t~1r 1 lr~tt!MathModelicaFullForm], HoldPattern[ Extends [TYPE [Modelica.Electrical.Analog. Interfaces.OnePort,{},{},{}l ] ]
]
]
]
{Modelica.Electrical.Analog.Basic.Inductor, Modelica.Electrical.Analog.Basic.Capacitor, Modelica.Electrical.Analog.Basic.Conductor, Modelica.Electrical.Analog.Basic.Resistor} All 64 three-type combinations, e.g. {Inductor, Inductor, Inductor}, {Inductor, Inductor, Capaci tor}, etc., their prefixes not shown for brevity, of these 4 types are computed by taking a generalized outer product of the three types lists, which is flattened. typecombinations = Flatten[Outer [List, types, types, types], 2] Length [typecombinations]
i
64
We generate a list of 64 synthetic model names by concatenating the string "f oo" with numbers, using the Mathematica string concatenation operation "0": names
=
Table[ToExpression[nfoo"ToString[i]], {i,64}1
{fool, fo02, fo03, fo04, fo05, fo06, fo07, fo08, fo09, foo10, fo051, fo052, fo053, fo054, fo055, fo056, fo057, fo058, fo059, fo060, fo061, fo062} Here all 64 test models are created by the call to MapThread which applies CircuitTemplateFn to each combination. MapThread[CircuitTemplateFn, {names, typecombinations}1
i
We retrieve the definition of one of the automatically generated models, fo053, and unparse it from its internal representation to the Modelica textual form: GetDefinition[foo53, Format->ModelicaForm] model fo053 Modelica.Electrical.Analog.Basic.Resistor ai Modelica.Electrical.Analog.Basic.Capacitor bi Modelica.Electrical.Analog.Basic.lnductor c; Modelica.Electrical.Analog.Basic.Ground gi equation connect(g.p,a.p) ; connect(a.n,b.p)i connect(b.p,c.p) ; connect(b.n,g.p) ; connect(c.n,g.p) ; end fooS3;
728 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica We are now creating a Total model within which all 64 generated models will be instantiated. First create an empty model: Model [Total,J ;
Then use the wi thin statement to move the current scope inside the model and then make a declaration, i.e. instantiation of the first test model: Within[Total] ; Declare[fooll m1l
Since we are free to use Mathematica scriptingwe had better use a loop for the 63 remaining declarations: Do[
With[{type = names[[i]], instanceName = ToExpression[nmnToString[iJJ}, Declare[type instanceName] ]
,
{i, 2, Length[names]} ] ;
Finally we movethe scope back to the globalscope. EndWithin []
Retrievethe generated model Total, where we have abbreviated the output to save some space. GetDefinition[Total, Format->ModelicaForm] model Total
fo064 m64; fo02 m2; fool m1; end Total;
Finally, simulatethe Total model to verifythat the test models are semantically correct. Simulate (Total, {t,O,l}];
19.5.3 Summary of MathModelica This overview has presented a numberof importantissues concerning integrated interactive programming environments, especially with respect to the MathModelica environment for object-oriented modeling and simulation. We have especially emphasized environment properties such as integration and extensibility. One of the current strong trends in software systems is the ongoing unification of documents and software. Everything will eventually be integrated into a uniform, to some extent XML-based, representation. The integration of documents, modelcode, graphics, etc. in the MathModelica environment is one exampleof this trend. Another important aspect is extensibility. Experience has shown that tools with built-in extensibility mechanisms can cope with unforeseen user needs to a great extent, and therefore often have a substantially longer effectiveusage lifetime. The MathModelica system is currently one of the better existing examples of advanced integrated extensible environments. However, as most systems, it is not perfect. There are still a numberof possible future improvements in the systemincluding enhanced programmability and extensibility.
19.6 The Dymola Environment Dymola-Dynamic Modeling Laboratory-is a comprehensive industrial strength modeling and simulation environment for Modelica, with special emphasis on efficient real-time simulation. One of the
Chapter 19 Environments 729 main application areas is simulation in the automotive industry, e.g., hardware-in-the-loop simulation of automatic gearboxes. The history of Dymola goes back to 1978 when Hilding Elmqvist presented his Ph.D. thesis on methods for component-based modeling and simulation with acausal equations and automatic symbolic manipulation of equation systems into a state space form suitable for numerical solvers. His thesis also described a small modeling language called Dyrnola, meaning Dynamic Modeling Language. However, at that time the computational power and memory capacity of computers was too small to use these methods on most realistic industrial problems. Eventually the capacity of computers increased enough to resume the development of Dymola. In 1992 Hilding Elmqvist founded the Dynasim company. A new and extended version of the Dymola language and tool soon appeared, including full object orientation together with support for discrete event and hybrid simulation. When the design of the Modelica language had matured enough the Dymola tool was enhanced with support for the Modelica modeling language, which eventually replaced the Dymola language as the standard modeling language of the tool. A new interpretation of Dymola was coined-Dynamic Modeling Laboratory. The structure of the Dymola tool is similar to the previously presented OpenModelica and MathModelica environments. It contains the following main parts: •
A Modelica compiler including a symbolic optimizer to reduce the size of equation systems. A simulation run-time system including a numeric solver for hybrid DAB equation systems. A graphic user Interface including a connection editor. A text editor for editing Modelica models.
• • •
Here we will just take a brief look at some aspects of the Dymola environment regarding the most recent version, Dymola 5.1. The description is not complete and is shorter than for the previous two environments-not because there is less material to present-but primarily because this author has not been involved in the development of Dymola, in contrast to the case for OpenModelica and MathModelica. Additional information regarding Dymola is available in the Dymola user's manual and in a number of papers mentioned in the Dymola references section at the end of this chapter.
19.6.1 Graphical and Textual User Interface The Dymola environment includes both a graphical connection editor and a text editor, depicted in Figure 19-15, as wen as tree browsers for the package/class hierarchy and the instance (component) hierarchy. The following are a few characteristics of the user interface: •
•
• •
Both tree browsers (for the package hierarchy and the instance and extends hierarchy) can display small icons at the left of corresponding names of classes and components. A class icon can be dragged from the package hierarchy browser into the graphical connection editor where it will appear as an icon representing an instance, or into the text editor window where it will appear as text. The icon representation can be created with the built-in graphical editor which allows insertion of graphical elements such as lines, rectangles, ellipses, polygons, and text strings. Import of scalable bitmaps created by other tools is also possible. The hierarchical structure of a model is shown in the component hierarchy browser. A built-in text editor for editing models is available. This editor offers syntax highlighting, e.g. to show different colors for keywords, type names, and variable names in declarations.
730 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
. . SimpleCar : $···Chauis g .... Engine $... ~omponent$ ; ! Cam ChamberVotume 1· Combustion \ ControWolurne ~ CrankSider i··· .. Dynamometer
r~
! \
!
$....
Figure 19·15. The Dymola5.1 graphical user interface. Courtesy Dynasim AB.
19.6.2 Real-Time Hardware-in-the-Ioop Simulation One of the most powerful features of Dymola is' real-time simulation. This is commonly used for hardware-in-the-loop simulation, i.e., when a hardware component is replaced by a component with similar properties, but simulated in software using a computer. However, multi-domain hierarchical modeling often leads to stiff equation systems, for which the solutions contain both slowly varying and fast varying parts. The usual use of the explicit Euler method (Section 18.2.1.1) when real-time constraints are imposed does not work well since its requires a too small step size causing a too large computational effort. Unfortunately, the explicit Euler method become some unstable if the step size is increased. The solution is to use the implicit Euler method instead, which however requires the solution of a small nonlinear equation system at each step, which usually is too computationally intensive. Fortunately the method of in-line integration can help in these cases. Instead of calling a separate solver to perform the integration, the discretization formulas of the integration method are expanded in-line together with the model equations. The whole equation system is symbolically reduced to a more efficient form, which in many cases dramatically increases the efficiency of solving' the nonlinear system at each integration step.
19.6.3 Other Facilities Dymola also contain additional facilities not described here, including a 3D graphic animation option, integration with CVS to support version handling, etc.
Chapter 19 Environments 731
19.7 Summary We started this chapter with a generic description of the structure and parts of typical Modelica modeling and simulation environments. The first environment to be presented was the OpenModelica environment, largely an open-source effort based on generation of the compiler from a formal specification-see a separate summary in Section 19.2.7, page 708. The second environment to be described was MathModelica-an industrial-strength environment emphasizing integration, interactivity, and extensibility with unification between documentation and code and accessible internal representation-see as separate summary in Section 19.5.3, page 728. The third and final environment to be described was Dymola, emphasizing high performance real-time simulation.
19.8 Literature This section provides literature references related to three Modelica environments for modeling and simulation: OpenModelica, MathModelica, and Dymola. Regarding the OpenModelica environment - the large part of this environment related to the Modeliea language is automatically generated from a formal specification of Modelica in the Natural Semantics formalism using the RML tool. Natural semantics and RML are described in (Kahn 1987; Pettersson 1999; Fritzson 1998). The generation of the OpenModelica translator from natural semantics in the RML form as well as other aspects of the environment are briefly described in (Kagedal and Fritzson 1998; Fritzson, Aronsson, Bunus, Engelson, Johansson, Karstrom, Saldamli 2002; Aronsson, Fritzson, Saldamli, and Bunus 2002). A related approach in the sense of using a formal specification language, but using a partial specification of VHDL-AMS in denotational semantics instead of natural semantics is described in (Breuer, Madrid, Bowen, France, Petrie, and Kloos 1999). The ANTLR parser generator used for the OpenModelica frontend is described in (Schaps 1999). The MathModelica environment has its roots in interactive programming environments for languages such as Lisp with the InterLisp system: (Teitelman 1969; Teitelman 1974; Teitelman 1977), common principles and experience of early interactive Lisp environments as described in (Sandewall 1978), interactive and incremental Pascal with the DICE system: (Fritzson 1983; Fritzson 1984). Smalltalk-80: (Goldberg and Robson 1989), Mathematica: (Wolfram 1988; Wolfram 1997), interactive environment generation and Simula: (Hedin and Magnusson 1988; Lindskov, Knudsen, Lehrmann-Madsen, and Magnusson 1993) etc. The immediate predecessor of the MathModelica environment is the ObjectMath language and environment, described in (Fritzson, Viklund, Herber, Fritzson 1992; Fritzson, Viklund, Fritzson, and Herber 1995; Viklund and Fritzson 1995), based on an analysis of the needs for high-level computational modeling and simulation tools in (Fritzson, Fritzson 1992). MathCode - a productized code generator from the ObjectMath environment is described in (Fritzson 1998). The early ObjectMath prototype also lead to the development of BEAST (Bearing Simulation Tool), an object-oriented simulation tool capable of execution on parallel processors described in (Fritzson, Nordling 1995; Fritzson, Fritzson, Nordling, and Persson 1997; Nordling 2003). Successive versions of the MathModelica environment are described in (Fritzson, Engelson, and Gunnarsson 1998; Jirstrand, Gunnarsson, and Fritzson 1999; Jirstrand 2000; Fritzson, Jirstrand, and Gunnarsson 2002). Some versions of MathModelica use Visio, (Visio 2001), for implementing the graphical user interface (GUI), other versions base the GUI on the QT (Dalheimer 2002) library. The used parser generator PCCTS is described in (Parr 1997). The interactive integrated capabilities of MathModelica of combining programs, documentation, and graphics in a live document are partly inspired by early work on (noninteractive) literate programming in the LaTeX document processing system, (Knuth 1984; Knuth 1994), but mostly by the interactive Mathematica environment with its notebooks, also used for teaching mathematics (Davis, Porta, and Uhl 1994). The DrModelica electronic notebook based on MathModelica, with the examples and exercises of this book, has also been inspired by DrScheme (Felleisen, Findler, Flatt, and Krishnamurthi 1998) and
732 Peter Fritzson Principles of Object-Oriented Modeling andSimulation withModelica DrJava (Allen, Cartwright, and Stoler 2002), and is somewhat related to the idea of elucidative programming (Nermark 2000). The first version of DrModelica is described in (Lengquist-Sandelin and Monemar 2003; Lengquist-Sandelin, Monemar, Fritzson, and Bunus 2003). The current Dymola environment, interpreted as the Dynamic Modeling Laboratory, with Modelica as its modeling language, is described in (Dynasim2003; Bruck, Elmqvist, Mattsson, and Olsson 2002), and in a book draft (Elmqvist, Otter, Mattsson, and Olsson 2002). Dynamic selection of states in Dymola is presented in (Mattsson, Olsson, and Elmqvist 2000). The techniques for fast real-time and hardware-inthe-loop simulation supported by Dymola are discussed in (Elmqvist, Mattsson, and Olsson 2002), partly based on earlier work on inline integration (Elmqvist, Cellier, and Otter 1995). Mixed-modeintegration is described in (Shiela and Olsson 2000). Initialization of DABs in Modelica, implemented in Dymola, is presented in (Mattsson, Elmqvist, Otter, and Olsson 2002). Dymola, meaning the Dynamic Modeling language, one of the most important predecessors of the Modelica language, is briefly described in Appendix F, and in more detail in (Elmqvist 1978;Cellier 1991; Elmqvist, Bruck, and Otter 1996).Hybrid capabilities were introduced in 1993as described in (Elmqvist, Cellier, and Otter 1993).Some of the ideas for information zooming and graphic capabilities in Dymola were already prototyped in the Lies system (Elmqvistand Mattsson 1982). There are also some other efforts in implementing subset Modelica-based simulationenvironments, e.g. (Larsson and Krus 2003), as well as ongoing work in Germany, Canada, and France.
739
Appendix B-Mathematica-style Modelica Syntax
The MathModelica environment provides a Mathematica style of Modelica syntax as an alternative to the standard Modelica syntax. The idea is to provide a seamless integration of the Modelica language into the Mathematica language. The result is a kind of extended Mathematica language where object-oriented modeling and equation support has been included from Modelica but with slight syntactic changes. The Mathematica-style Modelica syntax has been constructed according to the following procedure. Whenever there exists an identical Mathematica construct for a Modelica construct, we use the Mathematica syntax for that construct. In other cases we construct a Mathematica-style variant to represent the Modelica construct. To use this syntax style you have to define your cell type/format style of the notebook cell to be StandardForm instead of the cell type InputForm with Modelicalnput or ModelicaExport styles used for cells with standard Modelica syntax.
Mathematica vs. Modelica Syntax In order to show the difference between the standard Modelica textual syntax and the Mathematica-styIe syntax, we first show a simple Modelica model in a Modelica-style input cell: class SecondOrderSystem x(start=O) ; xdot (star,,:=O) ; parameter Real a=l; equation
xdot
= der (x) ;
=
der(xdot)+a*der(x)+x end SecondOrderSystem;
1;
The same class in the Mathematica-style Modelica syntax appears below. Note the use of the simple prefix syntax: a keyword followed by square brackets surrounding the contents of the construct. All reserved words, predefined functions, and types in Mathematica-style Modelica start with an uppercase letter just as in Mathematica. Equation equality is represented by the == operators since = is the assignment operator in Mathematica. The derivative operator is the mathematical apostrophe (') notation rather than der ( ). The semicolon (;) is a sequencing operator to group more than one declaration, statement, or expression together. Class [SecondOrderSystem, Real x[{Start == O}l; Real xdot[{Start O}l; Parameter Real a == 1; Equation [ ]
]
xdot == x ' ; xdot' + a*x' + x
1
740 Peter Fritzson Principlesof Object-OrientedModelingand Simulation with Modelica Note that the Start attribute values, e.g. for x and xdot, are defined using declaration modifier equations Start==O. These Start attributes are used as hints for the initial conditions when the simulation starts. The simulator is free to deviate somewhat from these hints if needed to obtain a consistent set of initial values by solving an equation system for the initial values. However, if the attribute Fixed is True (default Fal se), then the initial variable value is required to be the Start attribute value. In Mathematica all infix, prefix, or postfix operators also have a function-call style representation. This style is called FullForm, whereas the style where operators as shown in the short infix- etc. notation is called Input Form. The functions InputForm [) and FullForm [) in Mathematica allow the user to easily switch between these syntax styles. Moreover, the MathModelica palette has functions to easily convert a Modelica class definition between the Modelica standard syntax and the Mathematica-style Modelica syntax. The following are some examples of operators shown in Modelica, Mathematica Input Form, and Mathematica FullForm syntax styles:
Operator
Modelica Standard Mathematica InputForm syntax
Addition Assignment Equation equality Predicate equality Array construction Statement sequence
A+b+c+d
a+b+c+d
A := b
a = b a == b a === b
A = b A
==
b
{A,B,C} A;B;C;
{A,B,C} A;B;C;
Mathematica FuliForm Plus(a,b,c,d) Set(a,b) Equal (a,b) Same(a,b) List(A,B,C) CompoundExpression(A,B,C, Null)
Quick Overview of Mathematica-Style Modelica Constructs This is a quick overview of the constructs in Mathematica-style Modelica according to the usage help strings defined in the MathModelica Mathematica environment. For example, if you type ??Class, you will get the help information associated with Class. Algorithm: :usage Annotation::usage Assert: : usage Boolean: : usage Class: : usage Connect::usage Connector::usage Declare: : usage Discrete: : usage Equation: :usage Extends: : usage External: : usage Final: : usage Flow: : usage InitialAlgorithm::usage InitialEquation::usage ModelicaBlock::usage MatrixCat: :usage Member: : usage Model: : usage ModelicaModel::usage Output: : usage Package: : usage
"Algorithm[algs)"i "Annotation[classModification]"i "Assert[expr,\"string\"]"i "Boolean" i "Class[ident,composition]"i "Connect[a,bl"; "Connector[ident,composition]"; "Declare[declaration)"; "Discrete"; "Equationleqnsl"i "Extends[typeSpec)"; "External"; "Final[typeDefinition)"; "Flow" i "InitialAlgorithm[algs)"; "InitialEquation[eqns]"i "ModelicaBlock[ident,composition]"; "MatrixCat[expressionList)"i "Member [a,bl or a.b"i "Model[ident,composition)"i "ModelicaModel[typeDefinition)"i "Output" i
"Package";
Appendix B-Mathematica-style Modelica Syntax 741 Parameter: :usage Partial: :usage Prefixed: : usage Protected: :usage Public: : usage Record: : usage Redeclare: :usage Replaceable: :usage SetType: : usage Type: : usage UnionType: :usage When: :usage
"Parameter" ; "Partial"i "Prefixed" i "Protected [compositionJ "; "Public[composition]"i "Record[ident,composition)"i "Redeclare[typeDefinition]"i "Replaceable[typeDefinition]"i "SetType[ident,typespec]"j "Type[ident,typespec)"i "UnionType[ident,typespec]"i "When[expr,eqn)"i
PatternList: :usage "PatternList[patternList)"; ModelicaFunction: :usage "ModelicaPunction[ident,composition)"i ModelicaBlock: :usage "ModelicaBlock[ident,composition)"i Terminate: :usage "Terminate[\"string\"J"i ReplaceableConstrained: :usage= IIReplaceableConstrained[extendeciName,modificationJ "i External::usage "External[language,ExternalCall[ ... J,annotation]"i ExternalCall::usage "ExternalCall [varName, ident, {expr, ... } l ' i ModelicaModel: :usage "ModelicaModel[typeDefinitions,Within->name)"i Modelicalmport: :usage "Modelicalmport[id, name,Wildcard,comment]"i ElementModification: :usage "ElementModification [component, binding, classmodification, attributes, {comment, ... }] "i ElementRedeclaration: :usage "ElementRedeclaration[declaration)"i When::usage "When[expr,eqn] or When[expr,algs, {}] or When[expr,algs,{ElseWhen[expr,algs], ... }] "i
Mathematica-style Modelica Examples The following classes of the simple circuit model, first presented in Chapter 2, are shown here in Mathematica-style Modelica syntax. Type [Voltage=Real [{Unit=="V"})] Type [Current=Real [{Uni t== "A"}] ] Connector [Pin, Voltage Vi Flow Current i Partial Model [TwoPin, "Superclass of elements with two electrical pins", Pin {p,n}; Voltage Vi Current ii Bquation[ v==p.v-n.vj O==p.i+n.i; i==p.i ] ]
Model[Resistor,"Ideal electrical resistor", Bxtends[TwoPin] i Parameter Real R[{Unit=="ohm"}] "Resistance"i Equation [ R i==v
742 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
ModelfCapacitor, "Ideal electrical capacitor", Extends [TwoPin] ; Parameter Real C[{Unit == "F"}] "Capacitance"; Equation [ V'== i/C ]
]
Model [Inductor, "Ideal electrical inductor", Extends [TwoPin] ; Parameter Real L[{Unit == "H"}l "Inductance"; Equation [ L i' == v
Model [VsourceAC, "Sine-wave voltage source", Extends [TwoPin] ; Parameter Real VA==220 "Amplitude [V]"i Parameter Real £==50 "Frequency [Hz]"; Protected [ Constant Real PI==Modelica.Constants.pi ] ;
Equation [ v==VA sin[«2 PI) f) time] ]
]
Model [Ground, "Ground", Pin p; Equation [ p.v==O ] ]
Model [Circuit, Resistor Rl[{R==lO}]; Capacitor C[{C==O.Ol'}]; Resistor R2[{R==lOO}]; Inductor L[{L==O.l'}l; VsourceAC AC; Ground G; Equation [ Connect[AC.p,Rl.p] ; Connect[Rl.n,C.p] i Connect [C.n,AC.n] ; Connect[Rl.p,R2.p]i Connect[R2.n,L.p] ; Connect[L.n,C.n] ; Connect [AC.n,G.p] ]
1
743
Appendix C-Solutions to Exercises
parameter Integer age; protected Integer birthYear; equation birthYear • thisYear - age I / / Normal equation end Birthyear: class HartinsBirthyear Birthyear martinsBirthyear (age • 30) II Modification equation end MartinsBirthyear;
i
Exercise 2-7: There are more variablesthan equations, which is typical for partialclasses; the keyword partial is therefore missing. Exercise 2-8:
Chapter 2 Exercise 2-1: A class is a fundamental unit of modeling in Modelica, providing the structure for an object. Classes can contain equations, where the computationsare performed. Since x + y = sum is an equation and not an assignment, the equation can also be written as sum = x + y without changing the meaningof the expression. class Add ,arameter Integer x • 1; parameter Integer y - 2; Real S1Jm; equation sum· x + Y! end Add;
record Test Boolean (2) truthvalues • {false, true); Integer(5) ints. {13, 2, 5, 4, 87}; String(3, 4) strings. {{"blue", "Hartin.", "yellow", "cake"}, {"Anna", "sun", "star", "heaven"}, {"candy", "Sofia", "sweet", "Balthasar")} i Real[l, 5) reals s ((4.3, 7.132, 6.5, 4.0, 2.1}}; end Test;
Exercise 2-9: Yes. (You didn't think so, did you?) Exercise 2-10: class Average parameter Real a; parameter Real b; Real result; algorithm result :.. (a + b) I 2; end Average;
Exercise 2-2:
class Averagelnst Average aver(a - 15, b . 23;; end Average Inst ;
Instances are notions of classes and objects.
Exercise 2-11:
class DogInst
Note that the sum is calculated in an equation section to show that it is possibleto mix algorithmand equation sections in a class.
Dog d;
end Doglnst i class DogTim Dog t (name. "Tim") ; end DogTim;
Exercise 2-3: function Average input Real a; input Real bi output Real result i algorithm result :- (a + b) 12; end Average i class AverageTest Real res; equation res. Average (4, 6) end AverageTest;
j
class AverageExtended parameter Real a; parameter Real b; parameter Real c; parameter Real d; Real sum; Real aver; Real nrOfVariables • 4; equation Bum .. a + b + c + d;
algorithm aver : .. sum I nrOfVariables; end AverageExtended; class AverageExtlnst AverageExtended aver(a • 15, b • 23); end AverageExt Inst ;
Exercise 2-12:
Exercise 2-4: partialclass introducesa datatype. A partial class is incomplete, so you cannot create an instance of it.
class introduces a variant. extendsconnects a variant to a datatype, Exercise 2-5: record Bicycle Boolean has wheels • true i Integer nrOfWheels 2i end Bicycle; II:
class ChildrensBike extends Bicycle; Boolean forKids • true; enc! ChildrensBike;
Exercise 2-6: class Birthyear parameter Integer thisYear • 2002; / / Oeclaration equation
class Lights Integer 9witch; Boolean off .. true i equation if off then switch .. 0; else switch. 1 i end if; end Lights; class LightSwitch Boolean on; equation when sanple (5, 5) then if rem(time, 5) •• 0 then on • true; else on • false; end if; end when; end LightSwit;ch;
Exercise 2-13:
744 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica A package is a restricted and enhancedclass that is primarily used to managename spaces and organize Modelicacode. A package has the restrictionsof only containing declarationsof classes, including all kinds of restrictedclasses, and constants. Variable declarationsare not allowed. package MyPackage function division input Real a; input Real b; output Real result; algorithm result :. a I b; end division; constant Integer k • 5; end MyPackage;
Exercise 3-6: class Matrices parameter Real ml [2, 3); II A matrix with two rows and three columns parameter Real m2[S); II An array with 5 elements Real m3(1, 6); II A matrix with one row and six columns constant Real [2, 1) m4 • {{4}, {7)}; IIMatrix with two rows and one column end Matrices;
class MyPackInst Real x • MyPackage .division{lO, 5); end MyPacklnst;
Exercise 3-7: If nothing is specified,the default start value of all numerical variablesis zero, apart from function results and local variables where it is unspecified.Other start values can be specified by setting the start attributeof instance variables. You can also set the initial value like this:
Chapter 3
when (initial (» x dot. -51 end-when;
Exercise 3-1: class Multiply parameter Real x • 2; parameter Real y • 3; Real product; equation product .. x·y; end Multiply;
class Variables Real length1 (start • 3.5); II Initial value 3.5 Real length2 (start • 2.0); II Initial value 2 Real length3; II Initial value 0 or (start • 0) end Variables;
Exercise 3-8:
model Mult iply parameter Real x • 2; parameter Real y • 3; Real product; equation product • x·y; end Multiply;
record Dog Integer nrOfLegs • 4; String name. "dog"; end Dog;
Exercise 3-9: A type can conceptuallybe viewed as a set of values. If x has the type Real, this means that x belongs to the set of values representedby the type Real. The subtype relation between types is analogous to the subset relationbetweensets. If a type A1 is a subtypeof A, the set of values corresponding to type A I is a subset of the set of values correspondingto type A. The supertype relation is the inverse of the subtype relation.
Exercise 3-2: function AddTen input Real x; output Real result; algorithm re suI t :. X + 10; end AddTen; class AddTenCall Real res; equation res. AddTen(3. 5) end AddTenCall;
;
class Room Real length Real width Real height end Room;
Exercise 3-3: class Addition class Add Real x • 1; Real y • 2; Real z; equation
x
+
only at event instants,whereascontinuous-timevariables may change value both betweenand at events. A parameteris a special kind of constant, which is implemented as a static variablethat is initializedonce and never changes its value during a specificexecution.
• 5; • 4.3; • 2.1;
Exercise 3-10: class Access parameter Real a 1 Real b; Real c; protected Integer d, e; equation
y • z;
end Add; end Addition;
Exercise 3-4:
b • 2.0;
e • 1.3;
class Student Inst Student s; end Student Inst ;
d • 5; e • 7;
end Access; class StudentAlice Student stud (name • "Alice", nrOfBooks • 65) end StudentAlice; class StudentBurt Student stud{name • "Burt", nrOfBooks • 32) end StudentBurt;
I
class Accesslnst Access ace (a • 7.4); end AccessInst;
I
Exercise 3-5: A variable is a place to store a piece of information. Just as you might store a friend's phone number in your own memory,you can store this informationin a computer's memory.Variablesare your way of accessing your computer's memory. There are two different kinds of variables, discrete-time and continuous-time variables. Discrete-timevariableschange value
Chapter 4 Exercise 4-1: class Bird extends Animal; Integer wings. 2; Integer legs • 2; B001 ean eanFl y • true;
Appendix C-Solutions to Exercises 745 end Bird;
Exercise 4-7 :
talks stilt have the value false.
Exercise 4-2: partial class Vehiclp. Real speed; end Vehicle; class Car extends Vehicle; Real motorEffecti end Car; class Boat extends Vehicle; Real boat Weight ; end Boat; class Train extends Vehicle; Real nrOfCarriages; end Train; class Bicycle extends Vehicle; Real NrOfGears; end Bicycle; class Trainlnst Train superTrain(nrOfCarriages • 55); end Trainlnst;
Exercise 4-3: class Person String name; Real weight; protected Integer 10; end Person; class Employed extends Person; protected Real salary; end Employed; class Programmer extends Eq>loyed; String favProgLang; Boolean drinksJoltCola; end Programmer;
salary and 10 are protected variables in Employed.
In the class Employed2 name, weight, salary and 10 are protected variables.
class Temperature parameter Real temp (um t • "degC") end Temperature;
i
class Temp20 .. 'femperature(tell'q) • 20); modeI Teq>20b extends Temperature (temp. 20); end Te1l'q)20b;
Exercise 4-8: class Today Date date (dayName (nameOfDay ... "Wedr.esday"), date '"' '2, month • "October", year • 2(02); LunchAppoinlment lunchApp (lunchTime .. 12, lunchDate.. "Frederick") ; end Today; class Tomorrow Date date (dayName. nameOfDay • "Thursday", date 3, month ... "October", year. 2002); LunchAppointment lunchApp (lunchTime ... 12, Iuncbnat e "Steven") ; end Tomorrow; III
Exercise 4-9: class Point parameter Real x; parameter Real y i parameter Real z; end Point; class Redeclaration replaceable Point P(x end Redeclaration; class MyPoint extends Point end MyPoint;
III
1, Y • 2, z ... 3);
(z ... 4);
c.lass PointRed Redeclaration myPoint (redeclare MyPoint P); end Point Red ;
No, because then MyPoint would not be a subclass of Point.
Exercise 4-10: class A parameter Real salt; end A; class Asub / / Asub is a subtype of A extends A(salt. 20); parameter Real pepper; parameter Real basil; end Asub;
Exercise 4-4: A modifier modifies one or more declaration(s) from an inherited class by changing some aspect(s) of the inherited declarations.
class Alnst replaceable A a (salt • 100); end AInst;
class Test parameter Integer test (start • 3, min .. - 22, fixed • true); end Test;
The result after redeclaration is: Asub a (salt. 1, pepper
Exercise 4-5: class ModArray Integer A1 (5) (fixed. true); II Modifies the fixed value for the whole array Boolean truthvalues (2) (I,tart • (false, false}); / I Modifies the start value for the whole array Real A2 (2,2] (unit (1,2] • "kV"); /* Modifies the start value for a certain place in the matrix */ Integer A3[2,3) (start. ({l, 0, 5), ()}) i /* Modifies the start value for the first row in the matrix *1 String A4 [2,2) (start .. {{ "Pippi", "Pippi"}, {"Pippi ", "Pippi " }}) ; enri ModArray;
.. 2)
class Alred extends Alnst (redeclare Asub a (pepper • 200»; end Alred; class AIred2 Alnst t (redeclare Asub a (pepper • 200»; end AIred2
Exercise 4-11: class MoreRed parameter Real vl (3) ; parameter R.eal v2 ( : 1 ; Integer x • 2; end MoreRed;
Notice that you don't need the keyword replaceable for vl and
v2. class MoreRed2 • MoreRed(redeclare parameter Integer x, redeclare parameter Real vI (5) , redeclare parameter Real v2 (121) ;
Exercise 4-12: class Bananas Banana lightBanana (unit ... 109"); Banana swedishBanana (fixed • true) ;
II Correct
746 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica / / Error, since fixed is declared final end Bananas;
Exercise 4-13:
It is a way of expressingclasses or programsas generic patterns. Becauseinstead of writing manysimilar piecesof code with essentiallythe same structure,youcan directly express the generalstructureand providethe specific infonnation as parameters.
boolean right (fixed • true); parameter Integer h 15; constant Integer m .. h + 28; parameter Real k .. 32; end Happy; II
Chapter 7 Exercise 7-1: record Matrix Real mI(7)
Chapter 6 Exercise 6-1:
o o
A keyword is a reservedword. Becausethey are reservedfor constructing elementsin the Modelicalanguage,they cannot be used as identifiers.
o
For example: end, class, and, connect, else and parameter. But there are over 40 of them, so you can find many more.
o
Real, Integer, Boolean and String.
o
An unnamedconstant that has differentfonn dependingon their type.
o o
true, one of the two booleanliteral values. The freedomof the expressionto change value during simulation. The degrees of variabilityare constant,parameter, discrete-time, and continuous-time variability. o Constantexpressions have constant variability, i.e., neverchange value. In constant expressionsthe time derivativeis equal to zero. o Parameterexpressionshave parameter variability,remainconstantduring timedependentsimulation,and have time derivative equal to zero. o Discrete-timeexpressions: They have discrete-time variability meaningthat they are piecewise constant and change their values only at event instantsduring simulation. Time derivativeis equal to zero. These expressions may include constantor parameterexpressionsor discrete-time variables,as well as applications of operatorsand functionswithdiscrete-time arguments.
o
o
Continuous-time expressions: They have continuous-time variabilityand may change their values at any time during simulation. They may includeconstant, parameter,and discrete-time expressionsas well as continuoustime Real variables,as wen as applicationsof operatorsand functions.
Exercise 6-2:
The constant m cannot be set to a nonconstant value, in this case h +28. class Happy
II
{17.1, 62.7, 7.S, 37.0, 25, 4.121,
I2.333336};
Integer m2(4, 2] {{44, 5}, {2, 800}, {7, 23}, {2032, 77}}; String[l, 5] m3 .. {{"MagnuS", "circle", "boy", "Marina", "Miranda"}}; string m4( : ) ; Boolean m5 r.. 2]; Boolean m6 (0) ; end Matrix; IS
Exercise 7-2:
The expandedtype is St udent [42 I
35].
Exercise 7-3:
A rangevector is a vectorcontaininga range o,f numericvaluesincreasingor decreasingby a fixed increment or decrementvaluefor each additional element.
{5, 10, 15,20,25} Exercise 7-4: vl has the value (3,4,5,6, 7, 8)
•
v2 has the value (-20, -19, -18, -17, -16, -15, -14,13,-12, -11)
•
v3 has the value ( 11.3, 12.3, 13.3, 14.3, 15.3)
•
v4 is an empty vector
•
v5 has the value ( 1.1,2.1, 3.1)
These vectorsare just examplesof how the vectorscan be constructed. There is morethan one solutionto every vector. class RangeVectors2 Real vI(S) .. 15.0 3: 27.0; Real v2(3) .. -6.5 : -2 : -10.S; Integer v3 [0) ; end RangeVectors2;
Exercise 7-5:
The arrays that are concatenated must have the same numberof dimensions. The concatenation dimensionk, that is used, must exist. Arraysmusthave identicaldimensionsizes with the exceptionof the size of dimensionk •
Argumentarraysmust have equivalentmaximally expandedelementtypes, where the elementtype of the resultarray is the elementtype of the maximally expandedtype of the arguments.
•
arrayl has the result ({22, 34,15), {66, 78, 52}}
•
array2has the result ( (22, 34, 15), {66, 78, 52}} array3has the result {{11, 12}, (13, 14}) array4has the result {{7, 2}, {5, 42}, (24, 74)} arrayShas the result ({7, 2), (5,42), (24, 74)} array6has the result (( I, 2), (II, 12), (13, 14), (3,
4» •
array7has the result ({1, 2, 35, 73), (72, 51, 12, 23}) These are examplesof how you could concatenatethe arrays in the exercise.
Appendix C-Solutions to Exercises 747 class MyArrayConcat Real (2, 2] myArray1 • Real(l, 4) myArray2. Real (2, 4) myArray3 .. (12; 24); Real [4, 2) myArray4 .. [20,50; 31, 22); end MyArrayConcat;
cat (1,
({ 1, 2)},
({ 11, 12}});
cat Iz , {{l, 2}}, ((11, 12}}); cat tz , (21, 32, 43; 66, 77, 55), cat (1,
(ro ,
•
v7 gets the first and second elements of the third row of V, i.e., (44,11, 77)
•
vBgets the 3:rd through 4:th elements of Y as {25, 26}
•
v9 gets the 1:st to 5:th elements step 2 elements as (23,25,27}
40; 55, 78),
myArrayl has the result (( 1, 2). (11, 12)}
Exercise 7-8:
•
myArray2 has the result ({I, 2, II, 12}}
•
myArray3 has the result ( (21, 32, 43, 12}, (66, 77, 55,24) ) myArray4 has the result ( (JO, 40), (55,78), {20, 50}, (31, 22})
Exercise 7-6: This is an example of how you could concatenate the arrays in the exercise. class MoreConcat Real[!, 2,1] a1 .. {{{!}, {2}}}; Real [l, 2, 2] a2 .. {( {3, 4}, { S , 6}}}; Real [1, 2,3) a3 .. {{{7, 9, 9}, (ro, 11, 12}}}; Real U, 2, 6] aReady; equation aReady .. cat (3, aI, a2, a3); end MoreConcat;
aReady has the result {{1,3,4, 7,8, 9}, (2,5,6, 10, 11, 12l)
class Concatenate Real (1, 2) A .. (SO, 32]; Real{2, 1] B • [3; 7]; Real [5) a • {4, 9, 7, 5, 2}; Real [1, 3J V1 • [A, 60); Real (1, 4J V2 • (V1, 50); Real (1, 3] V3 .. cat (2, A, {{20}}>; Real [3, 1] V4 .. [B; 60]; Real[3, 1] VS • catU, B, ({20}}); Real (6) v '" cat (1, a, {18}>; end Concatenate;
i)
The result is {50, 32, 60}
ii)
The result is {50, 32, 60, 50}
iii)
The result is {50, 32, 20}
iv)
The result is {(3), {7}, (60)}
v)
The result is {(3), (7}, {20}}
vi)
The result is {4, 9, 7, 5, 2, 18}
Exercise 7-9:
Exercise 7-7: class Arraylndexing Real arrayl [2, 3]; Real array2 (2, 3]; algorithm arrayl :- fill (1, 2, array2 :.. fill (1, 2, array1[l,1] :e 10; arrayl [2, 1 J :.. 23; array2 [2,1] : .. 100; array2 (2,2) : .. 100; array2 [2,3] : .. 100; end Arraylndexing;
No; elementwise operations for the combination of an array and a scalar operand are not defined for addition. No; elementwise operations for the combination of an array and a scalar operand are not defined for subtraction.
3); 3);
•
The result of array2 {{10, 1, I}, {23, 1, I}} •
The result of array2 {( 1,1,1}, {100, 100,
ioor:
class Arraylndexing2 Real arrayl (2, 2] • fill (9, 2, 2); Real array2(2, 4] .. £i11(7, 2, 4); Real vI (2] .. {2, 20}; Real v2 [4] .. (6, 7, 8, 9); Real array! {2} .. vI; end Arraylndexing2;
The result of array I is {{9, 9}, {2, 20}} •
The result of array2 {(7, 7,7, 7), {6, 7, 8, 9}}
class Slice Real(3, 3) V .. {{22, 14,71), (33, 41, 17), (44, 11, 77)}; Real [3, 2) W .. {{12, 13}, {23, 89}, {99, 43}}; Real (5) Y .. {23, 24, 25, 26, 27}; Real vl [3] • V ( :, 1); Real v2(3) • V[3, :]; Real v3 (l) • V (3, {2 }] ; Real v4 (3] • W(:, 2); Real vs (2) .. Y ({I, 2}); Real v6 (2) • W(3, {I, 2}); Real v7(.,,] .V(3, 1:2); Real v8 {2} • Y (3 :4) ; Real v9[3] • Y(l:2:S]; end Slice;
•
os, yes! The result is (22, 28, 24}.
Exercise 7-10: class MatrixMul tiplication Real Ml[2, 3] '" {2, 3, 4; S, 6, ?]; Real M2(3, 2) e (5, 6; 3, 2; 1, 7); Real prod [2, 2]; equation prod. • Ml·M2; end MatrixMultiplication;
Exercise 7-11: •
The result of mult I is 4.
•
The result of multi is {8, 8}.
•
The result of mult I is {{4, 4 }, {4, 4}}.
•
The result of mult1 is {84}. Oh, yes! The result is {4, 3.5, 2.5, 4.25, 3).
•
No; Elementwise operations for dividing a scalar operand with an array are not defined for division.
class Exponent Real m(2, 2J; equation m - {{I, 3}, {4, 5}} end Exponent;
A
2;
The result is {{13, 18}, {24, 37}}.
v I gets the value {22, 33, 44}. v2 gets the third row of V, i.e., the vector {44, 11, 77}.
•
v3 gets the second element (in brackets) in the third row in V, i.e., {II}.
•
v4 gets the second row of W, i.e., {13,88,43}
•
v5 gets the first and second elements of Y, i.e., (23, 24}
•
v6 gets the first and second elements on the third row ofW, i.e., {99, 43}
Chapter 8 Exercise 8-1: Equations are more powerful than assignments, since one equation can express several different assignments. •
A declaration equation is the equation used when declaring a variable, usually constants or parameters. Such equations are actually required for constants, but are optional for parameters. It is also possible to
748 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica specifya declaration equationfor a normal state variable,but this will makethe variablebehaveas a kind of constant. Modifierequationsoccur,for example, in a variable declaration when there is a needto modifythe default value of an attributeof the variable. A modifierequationreplacesthe declaration equation, if present,for an attributeof the specifictype. Exercise 8-2: class Repetitive Integer rep [7] i equation for i in 1: 7 loop rep [i) .. 15; end for; end Repetitive;
Exercise 9-1: function Sum input Real (:] x ; output Real sum; algorithm for i in 1: size (x, 1) loop sum :. sum + x [i) ; end for; end Sum; function Average input Real [:] x; output Real average; protected Real sum; algorithm average :. Sum (x) / size (x. 1) ; end Average;
class RepetitiveWithoutFor Integer rep (7) ; equation rep[l] • 15; rep [2] • 15; rep [3] • 15; rep(4] .. 15; rep [5] • 15; rep [6) - 15; rep(?] - 15; end RepetitiveWithoutFor,
class LargestAverage parameter Integer [:l Al • {1, 2, 3, .. , S}; parameter Integer[;] A2 - {?, 8, 9}; Real averageAl, averageA2; Boolean A1Largest (start - false); algorithm averageAl : - Average (Al) ; averageA2 : - Average (A2) ; if averageAl > averageA2 then A1Largest true; else A1Largest : - false; end if; end LargestAverage;
Exercise 8-3: class Repeat Integer repeater (4) ; equation for i in 1: 4 loop repeater [i] • i + 3; end for; end Repeat;
Exercise 9-2: Loopthroughall elements in the arrayexcept the first.The smallestvalueis initiallythe first valuein the array.
function Rapper input Integer rap [ : ] ; output Integer sum • 0; algorithm for i in 1: size (rap, 1) loop sum :- sum + rap [i) ; end for; end Rapper;
class FindSmallest Real A[:]; Real smallest; Integer place; algorithm smallest : - A [1] ; place :- 1; for i in 2: size (A, 1) loop if A (1) < smallest then smallest :- AU] ; place :- i; end if; end for; end FindSmallest;
class RapperInst Integer x; equation x ... Rapper ( { 1, 2, 3, 4}); end RapperInst;
Exercise 8-4: It is not good fromthe programmer'spointof view.The variableinsidethe for-clause is hidden,whichis all right,but they are by the programmer easily mixedtogether. Exercise 8-5: • A hybrid modelis a modelwith mixedcontinuous and discreteparts.
Well,the thing is that one can use bothconstructsfor hybridmodels.The if-equations maycontain continuous-time expressions and when-equations may containonly discrete-time expressions. Exercise 8-6: function MatrixAddition input Integer matrix1 [ :, :); input Integer matrix2 [ :, :]; output Integer matrixSum [2, 2); algorithm for i in 1: size (IM.trix1, 1) loop for j in l:size(matrix2, 2) loop matrixSum [i, j] : - matrixl [i, j] + matrix2 [i, j J ; end for; end for; end MatrixAddition; class MatrixAdditionCall Real [2, 2) MA MatrixAddition ([1, 2; 3, 4], I:
[1, 2; 3, 4]);
end MatrixAdditionC4ll;
Chapter 9
class FindSmallestElement FindSmallest f indsmallest (A- ( 9, 5, 8, 7, 2, .. }); end FindSmallestElement;
Exercise 9-3: If the operatorabs is usedoutsidea whenclause, stateevents are triggered. If this is not desired, the noRvent functioncan be appliedto it. class SumCalculation constant Real e • 0.000001; Real sum(start .O)i Real next (start •.1.0) ; Integer It (start - 1); Integer posneg(start - 1); II if the sign is + or algorithm while noBvent (abs (next» >- e loop sum :. sum + next; II Add the sum to the next term It :. k + 1; / I calculate a new next posneg : - - posneg; next :. posneg/ (k*k) ; end while; end SUmCalculation;
Exercise 9-4: class LightSwitch Boolean on; algorithm when sample(5, 5) then if rem(time, 5) •• 0 then on : - true; else on :- false; end if; end when; end LightSwitch;
Appendix C-Solutions to Exercises 749 class LightSwitchExtended Boolean on; algorithm when time < 5 or time >= 25 then on := false; elsewhen saq>le(5, 1) then i f rem(time, 5) .... 0 then on :e true; else on :- false; end if; end when; end LightSwitchExtended;
Exercise 9-5: model BilliardBalls parameter Real c " 0.9; / / Elasticity constant of balls Real position1 (start .. 1); / / Position of ball Real position2 (start .. 10); / / Position of ball Real velocity1 (start - 10); / / Velocity of ball Real velocity2 (start .. -15); / / Velocity of ball equation tier (position1) .. velocity1; der (position2) .. velocity2; der (velocityl) - 0; der(velocity2) " 0; algorithm when position1 >- position2 then reinit (velocity1, -c*velocity1); reinit (velocity2, -c*velocity2); end when; end BilliardBalls;
Exercise
9~:
function NFaculty input Integer n r output Integer fak .. 1; algorithm for i in 2:n loop fak :- i*fak; end for; end NFacul t y ; class NFacultyCall Real n .. NFaculty (4) end NPC1~ultyCall;
j
Exercise 9-7: function FindName input String nameArray[:) ; input String name; output Integer index; protected Integer i, length .. size (nameArray, 1); algorithm index :- -1; i
:- 1;
while index •• -1 and i -1, "FindName: Fai led") ; end FindName; class TestFindName Integer findLisp; String nameArray[:) .. {"C++", "Lisp", "Java", "Ada", "Modelica" } ; String lisp .. "Lisp"; equation findLisp - FindName (nameArray, lisp); end TestFindName; class TestFindName2 Integer findPascal; String name Array ( :J - {"C-++", "Lisp", "Java", "Ada", "Modelica" } j String pascal cr "Pascal"; equation findPascal .. FindName (nameArray, pascal); end Test FindName2 ;
Exercise 9-8: funct ion ScalarProduct input Integer VI [ : ) ; input Integer V2 (size (V1, 1»); output Integer scalarProduct; algorithm BcalarProduct :.. VI *V2; end ScalarProduct; class Orthogonal
Integer Vl [ :) .. {I, 2, 3}; Integer V2 (:J .. {- 3, 0, l}; Integer scalarProduct; Boolean orthogonal; algorithm scalarProduct :. ScalarProduct (V1, V2); if scalarProduct -- 0 then orthogonal : n true; end if; end Orthogona 1 ;
Chapter 10 Exercise 10-1:
A packageis simplya containeror namespacefor namesof classes,functions, constants,and other alloweddefinitions. A packageis also one of the restrictedclasses. •
Addingthe word encapsulated to the packagekeeps the packagewell structured as well as beingeasier to understandand maintain. Exercise 10-2: package Geomet ry constant Real PI • 3.1415926536; type Distance .. Real (unit • "m"); function RectangleArea input Distance B; input Distance H; output Distance area; algorithm area : .. B*H; end RectangleArea; fur..ctior. TriangleArea input Distance B; input Distance H; output Distance area; algorithm area :- RectangleArea(B, H)/2; end TriangleArea; function CirclePerimeter input Distance radius; output Distance peritr.eter; algoritM perimeter :. 2*PI*radius; end CirclePerimeter; function CircleArea input Distance radius; output Distance area; algorithm area : .. PI*radius A 2 ; end CircleArea; end Geometry; class GeometryUser Geometry. Distance rectangleArea Geometry. RectangleArea(4, 5); Geometry. Distance triangleArea Geornetry. TriangleArea (4, 5); Geometry. Distance circlePerimeter Geometry. CirclePerimeter (3.5) ; Geometry. Distance circleArea Geometry. CircleArea (3.5) ; end GeometryOser;
Exercise 10-3: There are manyfactorsto considerwhen designing a package, for example,the nameof the packageor the structuring of the packageinto subpackages. Otherfactors that are importantto considerare reusability and encapsulation of the packageas well as considering dependencies on other packages. Exercise 10-4: A genericpackageis a packagewith some kind of formalparameter, e.g. a replaceable type.
•
A local packageis simplya packagethat is declared directlyinsidea class that is not a package.
750 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica Yes,thereactuallyis. A nonencapsulated package is a package declared without the prefixencapsulated. Also largeencapsulated packages, containing protecteddeclarations, can be internally structured into nonencapsulated packages. That is becauseused declarations maynot be availablein the new location for that certain subclass. Whencopyingor moving an encapsulated packageor class,at mostthe importstatements
insidethis package or class, including subpackages and localclasses,needto be updated. Exercise 10-5:
Yes,as a matterof fact it is possible to inheritpackages. class GeometryUser extends Geometry; Distance rectangleArea Distance rectangleArea Distance circlePerimeter Distance circleArea end GeometryUser;
• RectangleArea (4, 5); • TriangleArea (4, 5); • CirclePerimeter (3. S) ; • CircleArea(3. 5);
751 Release Notes:
Appendix D-Modelica Standard Library The package Modelicais a standardizedand pre-defined packagethat is developed togetherwith the Modelicalanguage from the Modelica Association,see http://www.Modelica.org.lt is also called the MOOeHca Standard Library. It provides constants, types, connectors,partial models and model componentsin variousdisciplines. The Modelicapackage is free softwareand can be redistributed and/or modifiedunder the terms of the Modellca License displayedat the front pages of this book. The versionreproducedin this appendixcontains most of the Modelicastandard libraryin the fonn it was available in September2003, includingthe new versions of the Blocks and MultiBodysublibraries.Some componentsare not includeddue to lack of time and space. The most recent version,as well as older versionsnof the library can be downloadedfrom www.modelica.org.This particlar version, used for the examples in this book, is availablefrom the book web page www.dnnodelica.org. The Modelicapackageconsists currentlyof the following subpackages: Constants Mathematicaland physical constants(pi, eps, h, ...) Slunits Sf-unit type definitions(such as Voltage,Torque) Icons Icon definitions of general interest Math Mathematical functions(such as sin, cos) Blocks Input/outputblocks. Electrical Electric and electronic components. Mechanics Mechanicalcomponents(currently: I D-rotational and I D-translational components,and Componentsfor modeling 3D mechanicalsystems.) Thermal Thermalcomponents(currently: I-D heat transfer with lumped elements) Fluid Thermodynamic fluid and gas models (under construction). Media Media models(under construction).
In the Model iea package the followingconventions are used: '"Class and instance names are written in upper and lower case letters, e.g., "ElectricCurrent". An underscoreis only used at the end of a name to characterizea lower or upper index, e.g., body_low_up. '" Type names start always with an upper case letter. Instance names start always with a lower case letter with only a few exceptions,such as "T" for a temperatureinstance, if this is common sense. '" A package XXX has its interfacedefinitions in subpackage XXX.lnterfaces, e.g., Electrical.Interfaces. '"Preferredinstance names for connectors: p.n: positive and negativeside of a partial model. a.b: side "a" and side "b" of a partial model (i.e., connectors are completelyequivalent). Main Author: Peoplefrom the Modelica Association Homepage: http://www.Modelica.org
(preliminary)Version 2.0 (Sept-Nov 20(3). Added new subpackagesMultiBody,and early versions of Flaid, Media. Version 1.5 (December 16,2002) Encapsulatedall example models, added new package Thennal.HeatTransferfor modelingof lumped heat transfer, added model LossyGearin Mechanics.Rotational to model gear efficiency and bearing frictionaccording to a new theory in a robust way, added 10 new models in Electrical.Analog and added several other new modelsand improvedexisting models. In total, 55 new componentshave been added. A descriptionof the changesis available. Version 1.4.1 (June 28,2001) (earlier release notes are not includedhere)
Modelica.Constants Mathematical constantsand constantsof nature This packageprovidesoften neededconstants from mathematics, machinedependentconstantsand constants from nature. The latter constants (name, value,description)are from the following source: Peter 1. Mohr and Barry N. Taylor (1999): CODATA Recommended Valuesof the FundamentalPhysical Constants; 1998.Journal of Physicaland ChemicalReference Data, Vol. 28, No.6, 1999and Reviewsof Modern Physics, Vol. 72, No.2, 2000. See also http://physics.nist.gov/cuulConstants/ Copyright © t 999-2002,Modellea Associationand DLR. Main Author:Martin Otter. Types and constants constant Real e,.Modelica .Math. exp (1. 0) ; constant Real pi:2*Modelica.Math.asin(1.0); constant Real D2R=pi/190 "Degree to R!!dian"; constant Real R2D..190/pi "Radian to Degree"; constant Real eps,.1.e-l5 "Biggest number such that 1.0 + eps II: 1.0"; constant Real small,.1. e-60 "Smallest number such that small and -small are representable on the machine"; constant Real inf=1.e+60 "Biggest Real number such thr\t inf and -inf are representable on the machine"; constant Integer Integer 1nf-2147483647 "Biggest Integer number such that Integer_int and - Integer_int a:=e representable on the machine"; constant SI. Velocity c ..299792458 "Speed of light in vacuum" ; constant SI.Acceleration g_n..9. 80665 "Standard acceleration of gravity on earth"; constant Real G(final unit-"m3/(kg.s2)") ... 6.673e-l1 "Newtonian constant of gravitation" i constant Real h(final unit-"J.s") • 6.62606876e-34 "Planck constant"; constant Real k (final unit-"J/K") .. 1.3806503e-23 "Boltzmann constant"; constant Real R(tinal unit="J/{mol.K)") - 8.314472 "Po101ar gas constant"; constant Real sigma(final unit-"W/(m2.K4)") ,. 5.670400e-B "Stefan-Boltzmann constant"; constant Real N A(tinal unit-"l/mol") • 6 .02214199~23 "Avogadro constant"; constant Real mue 0(fina1 unit="N/A2") • 4*pi*1.e-7 "Magnetic constant"; constant Real epsilon_O (final unit_"F/m") • 1/ (mue_O*c*c) "Electric constant It; constant NonSI. Temperature_degC T_zero "Absolute zero temperature II ; constant Real E-e; constant Real PI-pi; constant Real EPS.eps; constant Real SMALL-small; constant Real INF.!nf; constant Real INTEGER_INF.lnteger_inf; constant Real c-c. constant Real H-h; constant Real K..k; constant Real RO.R; constant Real SIGMA=sigma; constant Real G EARTH-g n; constant Real T=ZERO-T_zero; lS-273.l5
752 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Modelica.Slunits Type definitions based on SI units accordingto ISO 31-1992 This packageprovidespredefinedtypes,such as Mass, Length, Time, based on the international standardon units: ISO 3 t-t 992 "Generalprinciplesconcerning quantities,units and symbols" ISO 1000-1992 "SI units and recommendations for the use of their multiples and of certain other units". For more information on units, see also the book of Francois Cardarelli"ScientificUnit Conversion - A Practical Guide to Metrication" (Springer1997). The following conventionsare used in this package: Modelicaquantitynames are definedaccordingto the recommendations of ISO 31. Some of these name are rather long, such as "ThennodynamicTemperature". Shorteralias names are defined,e.g., "typeTemp_K= ThermodynamicTemperature;". Modelicaunits are definedaccordingto the SI base units without multiples (only exception"kg"). For some quantities, more convenientunits for an engineer are definedas "displayUnit", i.e., the default unit for display purposes(e.g., displayUnit="deg" for quantity="Angle"). The type name is identicalto the quantityname,following the conventionof type names. An quantityand unit attributesare definedas final in order that they cannot be redefinedto anothervalue. Similiarquantities, such as "Length,Breadth,Height, Thickness,Radius"are definedas the samequantity(here: "Length"). The orderingof the type declarations in this packagefollows ISO 31: Chapter 1: Space and Time Chapter 2: Periodicand RelatedPhenomena Chapter 3: Mechanics Chapter 4: Heat Chapter 5: Electricityand Magnetism Chapter 6: Lightand RelatedElectro-Magnetic Radiations Chapter 7: Acoustics Chapter 8: PhysicalChemistry Chapter 9: Atomicand NuclearPhysics Chapter 10: NuclearReactions and IonizingRadiations Chapter 11: (notdefinedin ISO 31-1992) Chapter 12: Characteristic Numbers Chapter 13: Solid State Physics Conversionfunctions betweenSI and non-SIunits are available in subpackageConversions. Main Author:MartinOtter Copyright© 1999-2002, ModelicaAssociation and DLR.
Types andconstants type Angle - Real ( final quantity-"Angle", final unit-"rad" , displayUnit-"deg"); type SolidAngle • Real (final quantity. "SolidAngle" , final unit.,"sr"); type Length - Real (final quantity-"Length", final unit-"m"); type PathLength - Length; type position. Length; type Distance .. Length (min.O); type Breadth .. Distance; type Height - Distance; type Thickness - Distance; type Radius - Distance; type Diameter .. Distance; type Area - Real (final quantity.. "Area" , final unit.. "m2") ; type Volume .. Real (final quantity-"Volume", final unit."m3"); type Time .. Real (final quantity.. "Time" , final unit_ns"); type Duration - Time; type AngularVelocity - Real ( final quantity-"AngularVelocity", final unit-"rad/s", displayUnit.. "rev/min") ; type AngularAcceleration - Real (final quantity="AngularAcceleration", final unit- nrad/s2"); type velocity - Real (final quantity-"Velocity",
final unit="m/s"); type Acceleration - Real (final quantity="Acceleration" , final unit-"m/s2"); type Period. Real (final quantity="Time", final unit_"s") ; type Frequency", Real (final quantity. "Frequency" , final unit .. "Hz") ; type AngularFrequency .. Real (f inal quantity="AngularFrequency", final unit. "s-1"); type Wavelength .. Real (final quantity-"Wavelength", final unit="m ll ) ; type Wavelenght .. Wavelength; type WaveNumber", Real (final quantityc"WaveNumber", final unit="m-l"); type CircularWaveNumber .. Real (final quantitycllCircularWaveNumber", final unit -"rad/m") I type AmplitudeLevelDifference - Real (final quantity="AmplitudeLevelDifference" , final unit_"dB") I type PowerLevelDifference .. Real (final quantityc"PowerLevelDifference", final unit-"dB"); type DampingCoefficient .. Real (final quantityc"Dampingcoefficient", final unit -"s-l"); type LogarithmicDecrement .. Real (final quantity:: II LogarithmicDecrement " , final unit-"Np/S"); type AttenuationCoefficient .. Real (final quantity-"AttenuationCoefficient", final unit-"m-1"); type PhaseCoefficient c Real (final quantity= " PhaseCoefficient " , final unit- "m-1"); type PropagationCoefficient .. Real (final quantity.. "PropagationCoefficient" , tinal unit-"m-1"); type Damping - DampingCoefticient; type Mass .. Real ( quantity="Mass", final unit-"kg", min=O) ; type Density cReal ( final quantity-"Density", final unit-"kg/m3" , displayUnit c"g/cm3", mineO); type Re1ativeDensity .. Real ( fi.na1 quantity="RelativeDensity", final unit."l", min-O); type SpecificVolume = Real ( final quantity="SpecificVolume", final unit-"m3/kg", min-O); type LinearDensity • Real ( final quantity.. "LinearDensity" , final unit.. "kg/m" , min=O); type SurfaceDensity .. Real ( final quantity="SurfaceDensity", final unit-"kg/m2" , min-O); type Momentum - Real (final quantity. "Momentum" , final unit.. "kg.m/s"); type ImpUlse = Real (final quantity-" Impulse" , final unit="N.s"); type AngularMomentum • Real (final quantity", "AngularMomentum", final unit- "kg.m2/s"); type AngularImpulse .. Real (final quantity="AngularImpulse" , final unit-"N.m.s" ); type MomentOflnertia .. Real (final quantity-"MomentOflnertia" , final unit- "kg.m2"); type Inertia:: MomentOfInertia; type Force - Real (final quantityo::"ForCe", final unit:: "N") ; type Weight 0:: Force; type Torque .. Real (final quantity. "Torque" , final unit-"N.m"); type MomentOfForce .. Torque; type Pressure .. Real ( final quantity-"Pressure", final unit-"Pa", displayUnit-"bar"); type AbsolutePressure - Pressure (min-O); type BulkModulus .. AbsolutePressure 1 type Stress .. Real (final unit-"pa"); type NormalStress - Stress; type ShearStress • Stress; type Strain - Real (final quantity="Strain", final unit,.."l"); type LinearStrain - Strain; type ShearStrain - Strain; type VolumeStrain • Real (final quantity-"VolumeStrain", final unit."1"); type PoissonNumber - Real (final quantity="PoissonNumber" , final unit.. "l"); type ModulusOfElastici ty - Stress; type ShearModulus - Stress; type SecondMomentOfArea - Real (final quantity.. "SecondMomentOfArea", final unit -"m4"); type SecondPolarMomentOfArea .. SecondMomentOfArea; type SectionModulus .. Real (final quantit y-" Sect i onModul us" , final unit-"m3"); type CoefficientOfFriction .. Real (final quantity-"CoefficlentOfFriction", final unit-"l"); type DynamicViscosity • Real ( final quantitys"DynamicViscosity", final unit-"Pa. s", min-O); type KinematicViscosity • Real ( final quantitysII KinematicViscosity" , final unit-"m2/s", mi-naO) ; type SurfaceTension - Real (final quantity-"SurfaceTension" , final unit-"N/m"); type Work - Real (final quantity::z"Work", final unit-"J");
Appendix D-Modelica Standard Library Modelica.Slunits 753 type Energy .. Real (final quantity.. "Energy" , final unitlll"J") ; type EnergyDensity .. Real (final quantity-"EnergyDensity" , final unit."J/m3"); type PotentialEnergy : Energy: type KineticEnergy .. Energy; type Power .. Real (tinal quantity="Power", tinal unit="W") ; type EnergyFlowRate .. Power: type EnthalpyFlowRate .. Real (final quantity-"EnthalpyFlowRate", final unit .. "W" ); type Efficiency .. Real ( final quantityo::"Efficieney", final unit="l", min=O); type MassFlowRate .. Real (quantity. "MassFlowRate" , final unit-"kg/s"); type VolumeFlowRate .. Real (f inal quantity-"VolumeFlowRate" , final unit-"m3/s") i type MomentumFlux - Real (f inal quanti ty", "MomentumFlllx" , final unit_liN") i type AngularMomentumFlux .. Real (f inal quantity-"AngularMomentumFlux", final unit="N .m") ; type ThermodynamicTemperature = Real ( final quantity-"ThermodynamicTemperature", final unit:"K", displayUnit."degC") i type Temp_K - ThermodynamicTemperature i type Temperature .. ThermodynamicTemperature; type CelsiusTemperature a Real (final quantitY-"CelsiusTemperature", final unit "degC") i type Temp_C. CelsiusTemperature; type LinearExpansionCoefficient .. Real (final quantity.. "LinearExpansionCoefficient" , final unit .. "l/K"); type CubicExpansionCoefficient .. Real (final quant i t y» "CUbicExpansionCoeff icient", final uni t=" 1/K") ; type RelativePressureCoefficient • Real (flnal quantity.. "RelativePres8ureCoefficient" , final unit .. " l/K") ; type PressureCoefficient a Real (final quantity-"PressureCoefficient", final unit="Pa/K") i type compressibility z Real (final quantity-"Compressibility", final unit. "l/Pa"); type IsothermalCompressibility .. Compressibility; type IsentropicCompressibility .. compressibility; type Heat. Real (final quantity","Energy", final unit-"J") ; type HeatFlowRate '" Real (final quanti ty= "Power" , final unit-"W"); type HeatFlux .. Real (final quantity-"HeatFlux", final unit""lIw/m type DensityOfHeatFlowRate - Real (final quantitya"DensityOfHeatFlowRate" , final unit="W/m2"); type ThermalConductivity - Real (final quantity-"ThermalConductivity", final unit .. "W/ (m.K)"); type CoefficientOfHeatTransfer = Real (final quantity= "CoefficientOfHeatTransfer" , final unit .. "W/ (m2. K)") ; type SurtaceCoefficientOfHeatTransfer .. CoefficientOfHeatTransfer; type Thermallnsulance '" Real (final quantity-"Thermallnsulance" , final unit: "m2. K/w") ; type ThermalResistance • Real (final quantity-"ThermalResistance", final unit .. "K/W"); type ThermalConductance '" Real (f inal quantity-"ThermalConductance", final unit ,.,IIW/K") i type ThermalDiffusivity '" Real (final quantity-"ThermalDiffusivity". final unit z"m2/s"); type HeatCapacity = Real (final quantity. "HeatCapacity" , final unit .. "J/K" ) ; type SpecificHeatCapacity = Real (final quantity-"SpecificHeatCapacity", final unit-"J/ (kg.K) II); type SpecificHeatCapacityAtConstantPressure '" SpecificHeatCapacitYi type SpecificHeatCapacityAtConstantVolume .. Speci f icHeatCapaci ty i type SpeclficHeatCapacityAtSaturation .. SpecificHeatCapacity i type RatioOfSpecificHeatCapacities .. Real (final qullntity"RatioOfSpecificHeatCapacities" , final unit-"l"); type Is.:!ntropicExponent = Real (final quantity-"IsentropicExponent", final unit ,.,111"); type Entropy. Real (final quantity2O"Entropy" , final unit-"J/K"); type SpecificEntropy - Real (final quantitya"SpecificEntropy", final unit20 "J/ (kg. K) II) ; type InternalEnergy • Heat; type Enthalpy - Heat; type HelmholtzFreeEnergy = Heat; type GibbsFreeEnergy - Heat; type SpecificEnergy ,. Real (final quantity-"SpecificEnergy" , final unit ..."J/kg" ) ; type SpecificInternalEnergy - SpecificEnergy, type SpecificEnthalpy .. SpecificEnergy; type SpecificHelmholtzFreeBnergy - SpecificEnergyi type SpecificGibbsFreeEnergy ... SpecificEnergy; type MassieuFunction • Real (final 0::
A2");
quantity-"MaSsieuFu'1ction", final unit="J/K" ); type PlanckFunction • Real (final quantity-"PlanckFunction" , final unit .. "J/K") ; type DerDensityByEnthalpy • Real (final unit-"kg. s,o, 2/m,o, 5 " ) ; type DerDensityByPressure - Real (final unit-"s"2/m"2") i type DerDensityByTemperature .. Real (final unit"'''kg! (rnA). K) ") ; type DerEnthalpyByPressure .. Real ( final unit="J. m. s,o,~/kg"'2") ; type DerEnergyByDensity "" Real (final unit",lIJ.m"3/k3") i type DerEnergyByPressure = Real (final unit",IIJ .m.s"2/kg ll ) ; type ElectricCurrent II Real (final quantity-"ElectricCurrent", final unitz"A"); type curzent. '" ElectricCurrent; type ElectricCharge '" Real (f inal quantity="Electr.icCharge" , final unit .. "C"); type Charge = ElectricCharge; type VolumeDensityOfCharge - Real ( final quantity="VolumeDensityOfCharge" , final unit="C/m3", min..O); type SurfaceDensityOfCharge .. Real ( final quantity "SurfaceDensityOfCharge", final unit-"C/m2", min=O); type EiectricFieldStrength III Real (final quantity="ElectricFieldStrength", final unit .. "V!m"); type ElectricPotential .. Real (final quantity= "ElectricPotential", final unit- "V"); type Voltage .. ElectricPotential; type PotentialDifference .. ElectricPotential; type ElectromotiveForce "" ElectricPotential; type ElectricFluxDensity .. Real (final quantityaIlElectricFluxDensity", final unit .. "C/m2"); type ElectricFlux .. Real (final quantity-"ElectricFlux", final unit-"C"); type Capacitance .. Real ( final quantity", "Capacitance" , final unit""F", min",O); type Permittivity - Real ( tinal quantity..."Permittivity" , final unito:"F/m", min=O); type PermittivityOfVacuum ... Permittivity; type RelativePermittivity :or Real (final quantity-"RelativePermittivity", final unit,."l") i type ElectricSusceptibility - Real (final quantity="ElectricSusceptibility", final unita"l"); type ElectricPolarization - Real (tinal quantity.. "ElectricPolarization" , final unit."C/m2") i type Electrization .. Real (final quantity-"Electrization" , final uni t= "V1m") ; type ElectricOipoleMoment .. Real (final quantity-"ElectricDipoleMoment", final unit-"C.m"); type CurrentDensity - Real (final quantity="CurrentDensity" , final unito::"A/m2") i type LinearCurrentDensity .. Real (final quantity.. "LinearCUrrentDensity" , final unit="A/m"); type MagneticFieldStrength - Real (final quantity.. "MagneticFieldStrength", final unit= "A/m") ; type MagneticPotentialDifference - Real (final quantity.. "MagneticPotentiaIDifference", final unit-"A") i type MagnetomotiveForce • Real (final quantitys"MagnetomotiveForce", final unit -"A"); type eurrentLinkage - Real (final quant Lt.y« "CurrentLinkage" , final unit="A"); type MagneticFluxDensity .. Real (final quantityo:"MagneticFluxDensity", final unit .. liT" ) ; type MagneticFlux :or Real (final quantitYII:"MagneticFlux", final uni t= "Wh") i type MagneticVectorPotential '" ~eal (final quantity. "MagneticVectorPotential" , final unit ..."WhIm") ; type Inductance .. Real ( final quantity-" Inductance" , final unit-"H", min-O); type Self Inductance - Inductance; type Mutual Inductance - Inductance I type CouplingCoefticient .. Real (final quantity.. "CouplingCoefficient ", final unit."l") i type LeakageCoefficient .. Real (final quantity-"Leak'.ageCoeffic1.ent", final unit -"1"); type Permeability .. Real (final quantity-"Permeability", final unit-"H/m"); type PermeabilityOfVacuum .. Permeability; type RelativePermeability .. Real (final quantity.."RelativePermeability", tinal unit."l"); type MagneticSuBceptibility • Real (final quantity-"MagneticSusceptibility", final unit="l"); type ElectromagneticMoreent - Real (final quantity-"ElectromagneticMoment" , final unit-"A.m2"); type MagneticDipoleMoment - Real (final quantity="MagneticDipoleMoment", final unit .. "Wb.m"); type Magnetization - Real (final quantity-"Magnetization" , final unit."A/m"); type MagneticPolarization = Real (final
754 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica quantity="MagneticPolarization", final unit-"T"); type ElectromagneticEnergyDensity - Real (final quantity="EnergyDensity", final unit-"J/m3"); type PoyntingVector .. Real (final quantity="poyntingVector" , final unit="W/m2") 1 type Resistance. Real ( final quantity="Resistance", final unit .. "Ohm", min=O); type Resistivity ... Real (final quantity-"Resistivity", final unit."Ohm.m") ; type Conductivity - Real (final quantity-"Conductivity", final unit.. "S/m" ) ; type Reluctance - Real (final quantity-"Reluctance", final un it", "H-1 ") ; type Permeance - Real (final quantitya"Permeance" ,. final unit="H") ; type PhaseDifference cReal ( final quantity-"Angle", final unit .. "rad", displayUnit:o:"deg"); type Impedance Resistance; type ModulusOfImpedance - Resistance; type Reactance .. Resistance; type OualityFactor - Real (final quantity.. "OualityFactor" , final unit="l"); type LossAngle :0: Real ( final quantity-"Angle", final unit="rad", displayUnit="deg"); type Conductance a Real ( final quantity-"Conductance", final unit-"S", min=O); type Admittance - Conductance; type ModulusOfAdmi ttance • Conductance; type Susceptance - Conductance; type InstantaneousPower .. Real (final quantitya "Power" , final unit= "W") ; type ActivePower - Real (final quantity-"power", final unit.. "W") 1 type ApparentPower = Real (final quantity-"Power", final unit .."VA"); type ReactivePower - Real (final quantity-" Power" , final unit.. "var") ; type PowerFactor '" Real (final quantity-"PowerFactor", final unit .. "l"); type Transconductance. Real (final quantity "Transconductance", final unit= "A/ (V·V)"); type InversePotential .. Real (final quantity="InversePotential", final unit- "l/V"); type RadiantEn~rgy .. Real (final quantity.. "Energy" , final unit="J"); type RadiantEnergyDensity - Real (final quantity="EnergyDensity", final unit.. "J/m3") 1 type SpectralRadiantEnergyDensity .. Real (final quantity"Spect ralRadiantEnergyDens i ty", final uni t-"J/m4") ; type RadiantPower .. Real (final quantity-"Power", final unit="W"); type RadiantEnergyFluenceRate .. Real (final quant Lt.ye "RadiantEnergyFluenceRate" , final uni t- "W/m2") ; type Radiantlntensity - Real (final quantity="Radiantlntensity", final unit= "w/sr"); type Radiance = Real (final quantity-"Radiance", final unit="w/sr.m2"); type RadiantExtiance - Real (final quantity="RadiantExtiance", final unit- "W/m2"); type Irradiance .. Real (final quantity.. "Irradiance" , final unit.. "W/m2"); type Emissivity - Real (final quantity-"Emissivity", final unit .. "l"); type SpectralEmissivity .. Real (final quantity="SpectralEmissivity", final unit -"1"); type Directiona1SpectralEmissivity - Real (final quantity"DirectionalSpectralEmissivity", final unit-"l"); type Luminouslntensity - Real (final quantity=II Luminouslntensity" , final unit- "cd"); type LuminousFlux - Real (final quantity-"LuminousFlux", final unit-"lm"); type QuantityOfLight - Real (final quantity= "QuantityOfLight " , final unit- "lm.s"); type Luminance II Real (final quantity. "Luminance II , final unit .. ll c d / m2" ) ; type LuminousExitance - Real (final quantity","LuminousExitance", final unit- "lm/m2"); type Illuminance - Real (final quantity-" Illuminance" , final unit."lx"); type LightExposure - Real (final quantity= "LightExposure " , final unit-"lx.s") 1 type LuminousEfficacy - Real (final quantity.. "LuminousEfficacy" , final unit- "lm/W") 1 type SpectralLuminousEfficacy - Real (final quantity="SpectralLuminousEfficacy" , final unit="lm/W") ; type LuminousEfficiency .. Real (final quantity="LuminousEfficiency", final unit -"1") 1 IS
type SpectralLuminousEfficiency • Real (final quantity"SpectralLuminousEfficiency", final unit-"l"); type CIESpectralTristimulusValues - Real (final quantity"CIESpectralTristimulusValues", final unit-"l"); type ChromaticityCoordinates - Real (final quantity="CromaticityCoordinates", final unit-"l") 1 type SpectralAbsorptionFactor co Real (final quantitya "SpectralAbsorptionFactor" , final unit-" 1") ; type SpectralReflectionFactor .. Real (final quantity-"SpectralReflectionFactor" , final unit-"l"); type SpectralTransmissionFactor a Real (final quantity. ·SpectralTransmissionFactor", final unit.. "l"); type SpectralRadianceFactor - Real (final quantity.."SpectralRadianceFactor" , final unit-"l"); type LinearAttenuationCoefficient • Real (final quantity"AttenuationCoefficient", final unit-"m-1"); type LinearAbsorptionCoefficient .. Real (final quantity. "LinearAbsorptionCoefficient " , final unit-"m-1"); type MolarAbsorptionCoefficient = Real (final quantity"Mo1arAbsorptionCoefficient", final unit-"m2/mol"); type RefractiveIndex .. Real (final quantity.. "RefractiveIndex" , final unit-"l"); type StaticPresBure = Real ( final quantity-"Pressure", final unit-"Pa", displayUnit-"bar", min-O); type SoundPressure - StaticPressure; type SoundParticleDisplacement .. Real (final quantity="Length", final unit-"m"); type SoundParticleVelocity = Real (final quantity="Ve1ocity", final unit="m/s"); type SoundParticleAcceleration - Real (final quantity="Acceleration", final unit.. "m/s2"); type VelocityOfSound = Real (final quantity-"Velocity", final unit="m/s"); type SoundEnergyDensity '" Real (final quantity="EnergyDensity", final unit- "J/m3"); type SoundPower DO Real (final quantity-"Power", final unit,.,"W"); type Soundlntensity - Real (final quantity-"SoundIntensity" , final unit-"W/m2"); type AcousticImpedance - Real (final quantity-"Acousticlmpedance", final unit.. "Pa.s/m3") 1 type SpecificAcousticlmpedance .. Real (final quantity.. II Spec if icAcoust iclmpedance " , final unit-"pa.s/m"); type MechanicalImpedance .. Real (final quantity="Mechanicallmpedance", final unit-"N.s/m"); type SoundPressureLevel .. Real (final quantity-"SoundPressureLevel", final unit -"dB") 1 type SoundPowerLevel ,. Real (f inal quantity="SoundPowerLevel", final unit-"dB"); type DissipationCoefficient - Real (final quantity","DissipationCoefficient", final unit-"l"); type ReflectionCoefficient - Real (final quantity", "ReflectionCoefficient" , final unit-"l"); type TransmissionCoefficient .. Real (final quantitye"TransmissionCoefficient", final unit-"l"); type AcousticAbsorptionCoefficient - Real (final quantity"ACousticAbsorptionCoefficient", final unit-"l"); type Soum)Reductionlndex - Real (f inal quantity-"SoundReductionIndeX'", final unit-"dB"); type EquivalentAbsorptionArea - Real (final quantity-"Area" , final unit="m2"); type ReverberationTime - Real (final quantity-"Time", final unit="s"); type LoundnessLevel e Real (final quantity.. "LoundnessLevel " , final unit="phon") I type Loundness .. Real (final quantity-"Loundness", final unit-"sone") 1 type RelativeAtomicMass - Real (final quantity-"RelativeAtomicMass", final unit ."1") 1 type RelativeMolecularMass - Real (final quantity-"RelativeMolecularMass", final unit-"l"); type NumberOfMolecules - Real (final quantity="NumberOfMolecules", final unit. "1"); type AmountOfSubstance • Real ( final quantity-"AmountOfSubstance", final unit-"mol", mineO); type MolarMass - Real (final quantity-"MolarMass", final unit-"kg/mol"); type MolarVolume - Real (final quantity-"MolarVolume", final unit-"m3/mol"); type MolarlnternalEnergy - Real (final quantity="MolarlnternalEnergy", final unit-"J/mol") 1 type MolarHeatCapacity .. Real (final quantity="MolarHeatCapacity", final unit. "J/(mol.K)"); type MolarEntropy - Real (final quantity-"MolarEntropy", final unit-"J/ (mol.K)" ); type NumberDensityOfMolecules • Real (final quantity. "NumberDens i tyOfMolecules " , final unit-"m3") ;
type MolecularConcentration ... Real (final quantity-"MolecularConcentration", final unit."m-3"); type MassConcentration - Real (final quantity="MassConcentration", final unit- "kg/m3"), type MassFraction - Real (final quantity-"MassFraction",
Appendix D-Modelica Standard Library Modelica.Slunits 755 final unit-"l"); type Concentration = Real (final quantity-"Concentration" • final unit-"mol/m3"); type VolumeFraction '" Real (final quantityc"VolumeFraction" • ~inal unit-"l"); type MoleFraction :: Real (final quantity.. "MoleFraction" , final '.mite"l"); type ChemicalPotential '" Real (f inal quantity-"ChemicalPotential". final unit. "J/mol"); type AbsoluteActivity ... Real (final quanti tyc "AbsoluteAct ivi ty" • final unit."l" ); type PartialPressure • Real ( final quantity. "Pressure" • tinal unit."Pa". displayUnit."bar". min=O); type Fugacity .. Real (final quantity..."Fugacity" • final unit-"Pa"); type StarJdardJU:>soluteActivity • Real (final quantity-"StandardAbsoluteActivity" • final unit="l"); type ActivityCoefficient - Real (final quantity-"ActivityCoefficient", final unit..."l"); type ActivityOfSolute ... Real (final quantity-"ActivityOfSolute", final unit::"l': ); type ActivityCoefficientOfSolute - Real (final quantity... "ActivityCoefficientOfSolute". final unit:"l"); type StandardJU:>soluteActivityOfSolute ... Real (final quantity- "StandardJ\bsoluteActivityOfSolute". final unit","l"); type ActivityOfSolvent .. Real (final quantityc "ActivityOfSolvent " • final unit: "1"); type OsmoticCoefficientOfSolvent ... Real (final quantity.. "OsmoticCoefficientOfSolvent", final unit-"l"); type StandardAbsoluteActivityOfSolvent '" Real (final quantity- "StandardAbsoluteActivityOfSolvent". final unit-"l"); type OsmoticPressure - Real ( final quantity-"Pressure". tinal unit-"Pa", displayUnite"bar", min=O); type StoichiometricNumber - Real (f inal quantity-"StoichiometricNumber", final unit-"l"); type Affinity - Real (final quantity.. "Affinity" , f1.nal unit-"J!mo1"); type MassOfMolecule = Real (final quantity","Mass". final unitc"kg"); type ElectricDipoleMomentOfMolecule - Real (final quantity"ElectricDipoleMomentOfMolecule". final unit-"C.m"); type ElectricPolarizabilityOfAMolecule .. Real ( tinal quantity.. "ElectricPolarizabilityOfAMolecule". final unit-"C.m2!V"}; type MicrocanonicalPartitionFunction so Real (final quantity"MicrocanonicalPartitionFunction", final unit .. "l"); type CanonicalPartitionFunction - Real (final quantity", "CanonicalPartitionFunction". final units"l"); type GrandCanonicalPartitionFunction .. Renl (final quantity"GrandCanonicalPartitionFunction". final unit-"l"); type MolecularPartitionFunction .. Real (final quantity"MolecularPartitionFunction". final unit","l"); type StatisticalWeight • Real (final quantity-"StatisticalWeight". final unit- "In); type MeanFreePath .. Length; type DiffusionCoefficient .. Real (final quantityc"DiffusionCoefficient". final unit="m2!s"); type ThermalDiffusionRatio .. Real (final quantity-"ThermalDiffusionRatio", final unit.. "l"), type ThermalDiffusionFactor - Real (final quantity-"ThermalDiffusionFactor". final unit .. "l"); type ThermalDiffusionCoefficient '" Real (final quantity"ThermalDiffusionCoefficient", final unit","m2!s"); type ElementaryCharge .. Real (final quantity-"ElementaryCharge", final unit","C" ); type ChargeNumberOflon - Real (final quantity-"ChargeNumberOfIcn", final unit- "1"); type FaradayConstant .. Real (f inal quanti ty." Far"ldayConstant ", final uni t= "C!mol"); type IonicStrength '" Real (final quantity-" IonicStrength" , final unit-"mol!kg"); type DegreeOfDissociation - Real (final quantitya"DegreeOfDissociation", final unit.. "l"); type IlectrolyticConductivity .. Real (final quantity-"ElectrolyticConductivity" • final unit_"S/m") ; type MolarConductivity a Real (final quantity-"MolarConductivity", final unit .. "S.m2/mol") j t'ype TransportNumberOfIonic - Real (final quantity-"TransportNumberOflonic", final unit"'''l''); type ProtonNumber - Real (final quantity="ProtonNumber". final unit-"l"), type NeutronNumber .. Real (final quantity-"NeutronNumber" • final unit-"l") 1 type NucleonNumber • Real (final quantity-"NucleonNumber" • final unit-"l") 1 type AtomicMassConstant - Real (f inal quanti ty-"Mass" •
final unit."kg"); type MassOfElectron • Real (final quantity-"MasB". final unit-"kg"); type MassOfProton .. Real (final quantltyc"Mass". final unit-nkg"); type MassOfNeutron - Real (final quantity="MaSs". final unit="kg"); type HartreeEnergy ... Real (final quantity. "Energy" , final unit .. "J"); type MagneticMomentOfParticle - Real (final quantity-"MagneticMomentOfParticle" , final unit",IIA.m2") ; type BohrMagneton '" MagneticMomentOfParticle; type NuclearMagneton • MagneticMomentOfParticle; type GyromagneticCoefficient • Real ( final quantity", "GyromagneticCoefficient" , final unit","A.m2/(J.s)"); type GFactorOfAtom - Real (final quantityc "GFactorOfAtom" • final unit="l"); . type GFactorOfNucleus - Real (final quantity-"GFactorOfNucleus". final unit .. "l" ); type LarmorAngularFrequency - Real (final quantity="Ang'.llarFrequency", final unit-"s-l"); type NuclearPrecessionAngularFrequency - Real (final quantity:: "AngularFrequency", final unit="s-l"); type CyclotronAngularFrequency - Real (final quantity="AngularFrequency". final unit-"s-l"); type NuclearQuadrupoleMoment - Real (final quantity-"NuclearQuadrupoleMoment". final unit-"m2"); type NuclearRadius - Real (final quantity-"Length". final unit .. "m"); type ElectronRadius .. Real (final quantity="Length", final unit-"m"); type ComptonWavelength - Real (final quantity.. "Length" • final unit- "m") ; type MassExcess - Real (final quantity-"Mass", final unit-"kg"); type MassDefect • Real (final quantity-"Mass". final unit-"kg"); type Relat\veMassExcess - Real (final quantity="RelativeMassExCess". final unit -"1"); type RelativeMassDefect .. Real (final quantity-"RelativeMassDefect". final unit -"1"); type PackingFraction - Real (final quantity.. "PackingFraction". final unit-"l"); type BindingFraction ". Real (final quantity-"BindingFract.ion", final unit .. " 1") ; type MeanLife '" Real (final quantity="Time". final unit-"s"); type LevelWidth "" Real (final quantity-"LevelWidth". tinal unit-"J") 1 type Activity. Real (final quantity-"Activity", final unit="Bq"); type SpecificActivity '" Real (tinal quantity-"SpecificActivity", final unit", "Bq/kg"); type DecayConstant - Real (f inal quantity. "DecayConstant" • final unit="s-l"); type Half Life '" Real (final quantity-"Time". final unit-"s"); type AlphaDisintegrationEnergy .. Real (final quantity-"Energy", final unit-"J"); type MaximumBetaParticleEnergy - Real (f:inal quantityc"Energy". final unit="J"); type BetaDisintegrationEnergy - Real (final quantity-"Energy", final unit="J") 1 type ReactionEnergy - Real (final quantity-"Energy", final unit-"J"); type ResonanceEnergy - Real (final quantity-"Energy". final unit."J") 1 type CrossSection - Real (final quantitylE"Area". final unit-"m2") 1 type TotalCrossSection • Real (final quantity-"Area". final unit="m2"); typ~ AngularCrossSection - Real (final quantity="AngularCrossSection". final unit="m2!sr"); type SpectralCrossSection - Real (final quantity-"SpectralCrossSection", final unit-"m2!J"); type SpectralAngularCrossSection .. Real (final quantity"SpectraIAngularCrossSection", final unit- nm2/ (sr .J) ") ; type MacroscopicCrossSection I: Real (final quantity'-"MacroscopicCrossSection", final unit-"m-l II) ; type TotalMacroscop!cCrossSection • Real (final quantity. "TotalMacroBcopicCrossSection", final unit- "m-l") ; type ParticleFluence - Real (final quantity-"ParticleFluence". final unit-"m-2" ); type ParticleFluenceRate • Real (final quantity-"particleFluenceRate", final unit-"s-1.m2"); type EnergyFluence - Real (final quantity-"EnergyFluence" • final unit-"J/m2"); type EnergyFluenceRate - Real (final quantity-"EnergyFluenceRate". final unit- "W!m2"); type CurrentDensityOfParticles .. Real (final quantity.. "CurrentDensityOfparticles". final unit-"m-2. 9-1") ; type MassAttenuationCoefficient - Real (final quantity-
756 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica "MaseAttenuationCoefficient", final unit-"m2/kg"); type MolarAttenuationCoefficient - Real (final quantity. "MolarAttenuationCoefficient", final unit-"m2/mol") I type AtomicAttenuationCoefficient - Real (final quantity"AtomicAttenuationCoefficient", final unit-"m2") I type HalfThickness - Real (final quantity-"Length", final unit","m"); type TotalLinearStoppingPower ... Real (final QUant i ty= "TotalLinearStoppingPower" , final unit="J/m") ; type TotalAtomicStoppingPower - Real (final quantity-"TotalAtomicStoppingPower" , final unit .. "J.m2") ; type TotalMassStoppingPower ... Real (final quantity="TotalMassStoppingPower", final unit","J .m2/kg"); type MeanLinearRange • Real (final quantity-"Length", final unit-"m"); type MeanMassRange - Real (f inal quantity="MeanMassRange" , final unit="kg!m2"); type Linearlonization • Real ( final quantity-"Linearlonization", final unit- "m-l"); type TotalIonization .. Real (final quantity="TotalIonization", final unit..." l"); type Mobility - Real (final quantity-"Mobility", final unit c"m2/V. s"); type IonNumberDensity = Real (final quantity-"IonNumberDensity", final unit- "m-)"); type RecombinationCoefficient .. Real (final quantity="RecombinationCoefficient" , final unit="m3/s") ; type NeutronNumberDensity - Real (tinal quantity="NeutronNumberDensity", final unitc"m-)"); type NeutronSpeed • Real (final quantity-"Velocity", final unit-"m/s"); type NeutronFluenceRate • Real (final quantity="NeutronFluenceRate", final unit -"s-1.m-2"); type TotalNeutronSourceDensity co Real (final quantity"TotalNeutronSourceOesity", final unit-"s-1.m-3"); type SlowingDownDensity • Real (final quantity="SlowingDownDensity", final unit -"s-l.m-)"); type ResonanceEscapeProbability co Real (final quantity... "ResonanceEscapeProbabil ity" , final unit-"l"); type Lethargy - Real (final quantity="Lethargy", final unit=" 1") ; type SlowingDownArea • Real (final quantity-"Area", final unit="m2"); type OiffusionArea - Real (final quantity-"Area", final unit-"m2"); type MigrationArea - Real (final quantity-"Area", final unit-"m2"); type SlowingDownLength • Real (final quantity="SLength", final unit-"m"); type DiffusionLength - Length; type MigrationLength - Length; type NeutronYieldPerFission - Real (final quantity="NeutronYieldPerFission", final unit-"l"); type NeutronYieldPerAbsorption - Real (final quantity"NeutronYieldPerAbsorption", final unit.."l It) ; type FastFissionFactor ... Real (final quantity="FastFissionFac'tor", final unit= "1"); type ThermalUtilizationFactor - Real (final quantity-"ThermalUtilizationFactor" , final unit-"l"); type NonLeakageProbability • Real (final quantity="NonLeakageProbability", final unit.. "l"); type Reactivity ... Real Uinal quantity-"Reactivity", final unit.. 1I1"); type ReactorTimeConstant - Real (final quantity-"Time", final unit-lis"); type Energylmparted - Real (final quantity-"Energy", final unit="J"); type MeanEnergylmparted - Real (final quantity-"Energy", final unit="J"); type SpecificEnergyImparted • Real (final quantity="SpecificEnergy", final unit -"Gy") I type AbsorbedDose - Real (final quantity="AbsorbedDose", final unit-"Gy"); type DoseEquivalent - Real (final quantity.. "DoSeEquivalent" , final unit="Sv"); type AbsorbedOoseRate .. Real (final quantity-"AbsorbedOoseRate", final unit- "Gy/s"); type LinearEnergyTransfer .. Real (fInal quantity-"LinearEnergyTransfer", final unit-"J/m"); type Kerma .. Real (final quantity-"Kerma", final unit-"Gy") ; type KermaRate II: Real (final quantity-"KermaRate", final unit-"Gy/S"); type MassEnergyTransferCoefficient .. Real (final quantity"MassEnergyTransferCoefficient", final unit-"m2/kg"); type Exposure • Real (final quantity-"Exposure", final unit="C/kg"); type ExposureRate - Real (final quantity-"ExposureRate", final unit="C/(kg.s) II);
type ReynoldsNumber = Real (final quantity-"ReynoldsNumber" , final unit:"!"); type EulerNumber ... Real (final quantity-"EulerNumber", final unit-"l"); type FroudeNumber - Real (final quantity-"FroudeNumber", final unit-"l"); type GrashofNumber - Real (final quantity- "GraehofNumber " , final unit." 1") ; type WeberNumber - Real (final quantity="WeberNumber", final unit-"l"); type MachNumber - Real (final quantity="MachNumber", final unit."l"); type KnudsenNumber .. Real (final quantity="KnudsenNumber" , final unit="l"); type StrouhalNumber - Real (final quantity-"StrouhaINumber" , final unit-"l"); type FourierNumber == Real (final quant Lt.y« II FourierNumber" , final unit-"l"); type PecletNumber - Real (final quantity="pecletNumber", final unit .. "1") ; type RayleighNumber II: Real (final quantity-"RayleighNumber" , final unit-"I"); type NusseltNumber == Real (final quantity="NusseltNumber" , final unit="l"); type BiotNumber • Nussel tNumber; type StantonNumber .. Real (final quantity-"StantOnNumber" , final unit","l"); type FourierNumberOfMaesTransfer .. Real (final quantity.. " FourierNumberOfMassTransfer" , final unit-"l"); type PecletNumberOfMassTransfer • Real (final quantity. "PecletNumberOfMassTransfer", final unit-"l"); type GrashofNumberOfMassTransfer - Real (final quantity"GrashofNumberOfMassTransfer", final unit-"l"); type NusseltNurnberOfMassTransfer - Real (final quantity. "NusseltNumberOfMassTransfer", final unit-"l") 1 type StantonNumberOfMassTransfer • Real (tinal quantity"StantonNumberOfMassTransfer", final unit-"l"); type PrandtlNumber • Real (final quantity="PrandtlNumber" , final unit-"I"); type SchmidtNurnber ... Real (final quantity- "SchmidtNumber " , final unit-"l"); type LewisNumber - Real (final quantity="LewisNumber", final unit..."l") ; type MagneticReynoldsNumber .. Real (tinal quantity="MagneticReynoldsNumber", final unit-"l"); type AlfvenNumber - Real (final quantity-"A1fvenNumber" I final unit."l"); type HartmannNumber = Real (final quantity- "HartmannNumber " , final unit="l"); type CowlingNumber lit Real (final quantity= "CowlingNumber" , final unit-"l"); type BraggAngle lit Angle; type OrderOfReflexion - Real (final quantitY.. "OrderOfReflexion", final unit."l" ); type ShortRangeOrderParameter • Real (tinal quantity="RangeOrderparameter", final unit."l"); type LongRangeOrderParameter • Real (final quantity="RangeOrderparameter", final unit-"l"); type DebyeWallerFactor - Real (tinal quantity="DebyeWallerFactor", final unit- "1"); type CircularWavenumber • Real (final quantity-"CircularWavenumber", final unit -"m-1"); type FermiCircularWavenumber .. Real (final quantity-" FermiCircul arWavenumber " , final unit_ t l m - 1 " ) ; type OebyeCircularWavenumber lit Real (final quantity="DebyeCircularWavenumber", tinal unit-"m-1") 1 type DebyeCircularFrequency .. Real (f inal quantity..."AngularFrequency", final unit-"s-l") I type DebyeTemperature - ThermodynamicTemperature; type SpectralConcentration - Real (final quantity="SpectralConcentration", final unit-"s/m3"); type GrueneisenParameter - Real (tinal quantity-"GrueneisenParameter", final unit-"l"); type MadelungConstant - Real (final quantity-"MadelungConstant", final unit-"l" ); type DensityOfStates - Real (final quantity-"OensityOfStates", final unit- "J-1/m-3"); type ResidualResistivity - Real (final quantity="ResidualResistivity", final unita"Ohm.m"); type LorenzCoefficient - Real (final quantity="LorenzCoefficient", final unit- "V2/K2"); type HallCoefficient lit Real (final quantity-"HallCoefficient", final unit- "m3/C") I type ThermoelectromotiveForce - Real (final
Appendix D-Modelica Standard Library Modelica.SIunits.Conversions 757 quantity="ThermoelectromotiveForce" , final unit."V"); type SeebeckCoefficient D Real (final quantity-"SeebeckCoefficient", final unit .nV/K"); type PeltierCoefficient = Real (final quantity-"PeltierCoeff icient ". final unit • "V") ; type ThomsonCoefficient = Real (final quantity-"ThomsonCoefficient", final unit ="V/K"); type RichardsonConstant '"' Real (final quantity-"RichardsonConstant", final unit
-"AI
(m2 .K2)");
type FermiEnergy = Real (final quantity-"Energy", final unit..."eVil) ; type GapEnergy .. Real (final quantityD"Energy", final unit-"eV"); type Oonorloni zationEnergy eo Real (f ina1 quantity-"Energy" , final unit-"eV"); type AcceptorIonizationEnergy == Real ( final quantity-"Energy", final unit .. "eV" ) ; type FermiTemperature '" ThermodynamicTemperature; type ElectronNumberDensity == Real ( final quantity=/lElectronNumberOensity/l, final unit="m3") ;
type HoI eNumberOens i ty .. Real ( final quantity-"HoleNumberOensity", final unit.. "m-3"); type IntrinsicNumberOensi ty = Real (f ina1 quantity."IntrinsicNumberDen~ity",unitD"m-3"); type OonorNumberOensity .. Real (final quantity-"DonorNumberDensity", final unit :/lm-3"); type AcceptorNumberDensity .. Real (final quantity. "AcceptorNumberDensity" , final unit="m-J"); type EffectiveMaEls : Mass; type MobilityRatio • Real (final quantity-"Mobi1ityRatio ll , final unit"'"l"); type RelaxationTime = Time; type CarrierLifeTime == Time; type ExchangeIntegra1 == Real (final quantity="Energy", final unit."eV"); type CurieTemperature .. ThermodynamicTemperature; type NeelTemperature '" ThermodynamicTemperatut'e; type LondonPenetrationDepth .. Length; type CoherenceLength - Length; type LandauGinzburgParameter - Real (final quant ity: "LandauGinzburgParameter " , final unit." l") ; type FluxiodQuantum : Real (f inal quantity-" FluxiodQuantum" , final unit.. "Wb");
Modelica.Slunits.Conversions Conversionfunctions to/fromnon SI units and type definitions of non SI units This packageprovidesconversion functions from the non SI Units defined in package Modelica.Slunits.Conversions.NonSIunits to the corresponding SI Units definedin packageModelica.Slunits and vice versa. It is recommended to use these functions in the following way: import 81 ... Modelica. 81units; import Modelica. S1units. Conversions." ;
II convert 25 degree Celsius to Kelvin parameter SI. Temperature T .. frotll_degC (25) ; /1 convert 180 degree to radian parameter S1.Angle phi .. from_deg (180) ; II convert 3600 revolutions per minutes 1/ to radian per seconds parameter SI.AngularVelocity w : from_rpm (J600) ;
The following conversionfunctions are provided. Note, that all of them have one Real input and one Real outputargument: There is the additionalpartial function ConversionIcon in this package.It containsjust the base icon for all the conversion functions. Modelica.Slunlts.Converslons.to_degC
Convert from Kelvinto °Celsius function to_degC "Convert from Kelvin to °Celsius" extends Conversionlcon; input Temperature Kelvin "Kelvin value"; output NonSlunits. Temperature_degC Celsius "Celsius value" ; algorithm Celsius :- Kelvin + Modelica.Constants.T zero; end to_degC; -
Modellca.Slunlts.Conversions.from_degC
Convertfrom °Celsiusto Kelvin function trom degC "Convert from °CelsiuB to Kelvin" extends Conversionlconi input NonSlunits. Temperature degC Celsius "Celsius
v~~";
-
output Temperature Kelvin "Kelvin value"; algorithm Kelvin :. Celsius - Modelica. Constants. T zero; end from_degC; -
Modellca.Slunlts.Converslons.to_degF
Convertfrom Kelvinto "Fahrenheit function to degF "Convert from Kelvin to °Fahrenheit" extends conversionIcon; input Temperature Kelvin "Kelvin value"; output NonSIuni ts . Temperature degF Fahrenheit "Fahrenheit value"; algorithm Fahrenheit :.. (Kelvin + Modelica.Constants.T zero)·(9/S) + 32; end to_degF; -
Modellca.Slunits.Conversions.from_degF
Convertfrom "Fahrenheit to Kelvin function from degF "Convert from °Fahrenheit to Kelvin" extends conversionIcon; input NonS1units. Temperature degF Fahrenheit "Fahrenheit value"; output Temperature Kelvin "Kelvin vitlue"; algorithm Kelvin := (Fahrenheit - 32)" (5/9) Modelica. Constants. T zero; end from_degF; -
Modelica.Slunits.Converslons.to_degRk
Convertfrom Kelvinto °Rankine function to degR.k "Convert from Kelvin to °Rankine" extends conversionlcon; input Temperature Kelvin "Kelvin value"; output NonSlunits. Temperature degRk Rankine "Rankine value"; algorithm Rankine :: (9/5) ·Kelvin; end to_degRk;
Modellca.Slunits.Converslons.from_degRk
Convertfrom °Rankineto Kelvin function from degRk "Convert from °Rankine to Kelvin" extends con;ersionlcon; input NonS1units. Temperature degRk Rankine "Rankine value"; output Temperature Kelvin "Kelvin value"; algorithm Kelvin :: (5/9) *Rankine; end from_degRk;
Modelica.Slunits.Converslons.to_deg
Convertfrom radian to degree function to_deg "Convert from radian to ("egree" extends ConversionIcon; input Angle radian "radian value"; output NonSlunits . Angle_deg degree "degree value"; algorithm degree : = (180. O/Modelica . Constants .pi) .radian; end to_deg;
Modellca.Slunlts.Conversions.from_deg
Convertfromdegreeto radian function from_deg "Convert from degree to radian" extends Conversionlcon; input NonSIunits . Angle_deg desree "degree value"; output Angle radian "radian value"; algorithm radian :.. (Modelica. Constants. pi/lOO. 0) ·degree; end from_deg;
Modellca.Slunlts.Converslons.to_rpm
Convertfrom radianper secondto revolutions per minute function to rpm "Convert trom radian per second to revolutions per minute" extends Conversionlcon; input AngularVelocity rs "radian per second value";
758 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica output NonSIunits . AngularVelocity_rpm rpm "revolutions per minute value"; algorithm rpm := (30/Modelica.Constants.pi)*rsj end to_rpm;
Modelics.Slunlts.Converslons.from_rpm
Convertfromrevolutions per minuteto radianper second function from rpm "Convert from revolutions per minute to radian per second" extends Conversionlcon; input NonSIunits . AngularVelocity_rpm rpm "revolutions per minute value"; output AngularVelocity rs "radian per second value"; algorithm rs :- (Modelica.Constants.pi/30'*rpm; end from_rpm;
Modellca.Slunlts.Converslons.to_kmh
Convertfrom metreper secondto kilometre per hour function to kmh "Convert from metre per second to kilometre per hour" extends Conversionlcon; input Velocity ms "metre per second value"; output NonSlunits. Velocity_kmh kmh "kilometre per hour value" ; algorithm kmh :.. 3.6 *ms; end to_kmh;
Modelics.Slunlts.Converslons.from_kmh
Convertfrom kilometre per hourto metrepersecond function from kmh "Convert from kilometre per hour to metre per second" extends Conversionlcon; input NonSlunits. Velocity_kmh kmh "kilometre per hour value" ; output Velocity ms "metre per second value" j algorithm ms :. kmh/3. 6; end from_kmh;
Modellca.Slunits.Conversions.to_dsy
Convertfrom secondto day function to_day "Convert from second to day" extends Conversionlcon; input Time s "second value"; output NonSIunits . Time_day day "day value"; algorithm day :c s/86400; end to_day;
Modelica.Slunits.Conversions.from_day
Convertfromday to second function from_day "Convert from day to second" extends Conversionlcon; input NonSlunits. Time_day day "day value"; output Time s "second value"; algorithm s : .. 86400*daYi end from_day;
Modelica.Slunlts.Converslons.to_hour
Convertfrom secondto hour function to hour "Convert from second to hour" extends Conversionlcon; input Time s "second value"; output NonSlunits. Time_hour hour "hour value"; algorithm hour po S/3600; end to_hour;
Modelica.Slunits.Converslons.from_hour
Convertfrom hourto second function from hour "Convert from hour to second" extends conversionlcon; input NonSIunits. Time_hour hour "hour value"; output Time s "second value"; algorithm s :~ 3600'*hour; end from_hour;
Modellca.Slunlts.Converslons.to_mlnute
Convertfromsecondto minute function to minute ·Convert from second to minute" extends ConversionIcon; input Time s "second value"; output NonSlunits. Time_minute minute "minute value"; algorithm minute := s/60; end to_minute;
Modelica.Slunits.Conversions.from_mlnute
Convertfromminuteto second function from minute "Convert from minute to second" extends Conversionlcon; input NonSIunits. Time minute minute "minute value", output Time s "second-value"; algorithm s :- 60*minute; end from_minute;
Modelica.Slunits.Conversions.to_lltre
Convertfromcubic metreto litre function to litre "Convert from cubic metre to litre" extends Conversionlcon; input Volume m3 "cubic metre value"; output NonSlunits. Volume litre litre "litre value"; algorithm litre : '" lOOO*m3; end to_litre;
Modellca.Slunlts.Conversions.from_lItre
Convertfromlitre to cubicmetre function from litre "Convert from litre to cubic metre" extends Conversionlconi input NonSlunits. Volume_litre litre "litre value"; output Volume m3 "cubic metre value"; algorithm m3 : = litre/lOOO; end from_litre;
Modellcs.Slunits.Converslons.to_kW
ConvertfromJouleto kilo Watthour function to kWh "Convert from Joule to kilo Watt hour" extends Conversionlcon; input Energy J "Joule value"; output NonSlunits . Energy_kWh kWh "kWh value"; algorithm kWh := J/3.6e6; end to_kWh;
Modelica.Slunits.Converslons.from_kWh
Convertfromkilo Watthourto Joule function from kWh "Convert from kilo Watt hour to Joule" extends Conversionlcon; input NonSlunits.Energy_kWh kWh "kWh value"; output Energy J "Joule value"; algorithm J :. 3. 6e6*kWh; end from_kWh;
Modellca.Slunlts.Converslons.to_bsr
ConvertfromPascalto bar function to bar "Convert from Pascal to bar" extends Conversionlcon; input Pressure Pa ·Pascal value"; output NonSIunits . Pressure_bar bar "bar value" I algorithm bar :~ Pa/leS; end to_bar;
Modellca.Slunlts.Converslons.from_bsr
Convertfrombar to Pascal function from bar "Convert from bar to Pascal" extends Conversionlcon; input NonSIunits. pressure_bar bar "bar value"; output Pressure Pa "Pascal value"; algorithm Pa :== leS'*bar; end from_bar;
Modellc8.Slunlts.Converslons.to_gps
Appendix D-Modelica Standard Library Modelica.Icons 759 Convertfrom kilogramper second to gram per second
end Into;
funct ion to_9PB "Convert from kilogram per seco r.d to gram per second" extends Convers Ionrcon , input M&ssFlowRate kgps "kg/s value" ; output NonSluni ts .Mas s Fl owRat e gps gpe "g / 8 value "; algorithm gpo , . 1000'kgpo ; end to_9ps;
Modellcs.lcons.L1brsry Icon for library
rqbr~rv~
Modellcs.Slunlts.Converslons.from_9Ps
model Library "Icon for library" end Library :
Convert from gram per second to kilogramper second
Modellca.lcons.Llbrsry2
function from gpo "Co nve rt frOm gram per second t o ki l og ram per second" extends ccnvere tontccm input NonSlunits .Ma s s Fl owRa t e 9p8 9p B "g/ 8 value"; output MassFlowRate kgps "kg /; value "; algorithm kgpo , . gpo /1000 ; end trom_9Ps ;
Iconfor librarywhere additional iconelementsshall be added
(. l~:~ ~ ,,:v' ·,.....· .
model Library2
"Ico n for l ibrary where additional icon elements shall be added"
Modellcs.Slunlts.Converslons.Converslonlcon
end Library2 j
Base icon for conversion functions
Modelics.lcons.Example
part ial function Convers i on Icon "Base icon fo r conversion funct ions" end. ConversionIcon ;
Icon for an examplemodel
Modelica.lcons
model Example "Ic on for an example model "
rExamPle~ end Example ;
Main Author: Martin Otter. Copyright (C) 1999-2003. ModelicaAssociation and DLR.
Modellca.lcons.TranslatlonaISensor Icon representing translational measurement device
~
rLliJ;}y~
QJ
C)
" il,t.,·,
Ubrory
Info
TranslationalSensor
RololionalSensor
--
ITmID lex~.~ 0)
D
t'Gnction log "na t u r a l
(base e)
extends basetconl ; input Real U ; output Real y ; external "C" y _ log (u ) ; end log ;
Modellca.Math.log10
llbR(rll!m«(l10 • siU]) ,303 23)) ;
logarithm (u shall be ,.
Nonnaldistribution randomfunction
func t ion normal variate " normally d istributed random v a r i ab l e " input Real mu "me a n va l ue " ; input Real sigma "standard deviation" ; input Seed a1 "input random seed- ; output Real x "g 8u 88 i a n random variate" ; output Seed 80 "output random seed" ; protected Seed 81 . s2 , Real e , zt , u1 , u2 ; Boolean break. f alse ; algorithm sl ,. si ; u2
0) •
! ..
1/ zero is a poor Seed . therfore substitute 1 ; H soll) • • 0 then eo Lt I ,. 1 , end if ; if eo Iz! • • 0 then so121 , . 1 , end if , H so(3} • • 0 then ao l al , . 1 , end if ; x : . rem( (so[1) /30269 .0 +80(2}/30307 .0 + eo la I / 30323 . 0 ) , 1. 0) ; end random;
Modellca .Math.Random.normalvarlate
Modelica.Math.exp
~ .i ldJ
Uniformdistribution random function Distribution uniformbetween 0 and I.
: _ 1;
while not break loop (U1 ,82) : _ randomhl) ; (u2. s1) , . randomls2); z , . NV MAGICCONST' IUl - 0 . S) lu3 ;
zz :_ %";'Z/4 .0 j break I end whUe;
%Z
OUlPort
~
BooJeantlPort
[>
BooJeanOJtPon
D
0 0500 0512SO 0 0 0 0 0 5iw~ ~ 0 D 0 DU 050
Me>
S1gnalSource
M'Me>
MVconlrol
Bookan8'ocklcon
BooIeanSlSO BooleanSigl'1'lISourceM12
a
This packagecontains interracedefinitions for continuous input/output blocks. In particularit containsthe following connector classes: Reallnput Connectorwithinput signalsof type Real. RealOutput Connectorwithoutputsignalsof typeReal. Booleanlnput Connectorwith input signalsof type Boolean. BooleanOutput Connector withoutputsignalsof type Boolean. lntegerlnput Connectorwithinput signalsof type Integer. IntegerOutput Connectorwith outputsignalsof type Integer. The following partialblockclassesare provided to model continuous controlblocks: Blocklcon Basicgraphical layoutof continuous block SO SingleOutputcontinuous controlblock MO MultipleOutputcontinuous controlblock StSO SingleInputSingleOutputcontinuous controlblock S12S0 2 SingleInputII SingleOutputcontinuous control block MultipleInputSingleOutputcontinuous control MISO block MIMO Multiple InputMultipleOutputcontinuous control block MIMOs Multiple InputMultipleOutputcontinuous control blockwithsame numberof inputsand outputs MI2MO 2 Multiple InputI MultipleOutputcontinuous controlblock SignalSource Baseclass for continuous signalsources Periodic Baseclass for periodiccontinuous signalsources SVcontrol Single-Variable continuous controller MVcontrol Multi-Variable continuous controller
The following partialblockclassesare provided to model Boolean'controlblocks: BooleanBlocklcon Basicgraphical layoutof Boolean block BooleanSISO SingleInputSingleOutputcontrolblock withsignalsof type Boolean BooleanSignalSource Baseclass for Booleansignalsources MI2BooleanMOs 2 Multiple InputI BooleanMultiple Output block withsame signal lengths Modellca.Blocks.lnterfaces.Reallnput
Connector withinputsignalsof type Real connector Real Input ~ input RealSignal "Connector with input signals of type Real" ,
Modellca.Blocks.lnterfaces.ReaIOutput
C>
Connectorwithoutputsignalsof type Real
connector RealOutput • output RealSignal "Connector with output signals of type Real",
Modelica.Blocks.lnterfaces.Booleanlnput ~
Connectorwithinputsignalsof type Boolean
connector BooleanInput - input Boolean "Connector with input signals of type Boolean" ,
[::>
Modellca.Blocks.lnterfaces.BooleanOutput
Connector withoutputsignalsof type Boolean
connector BooleanOutput • output Boolean ·Connector with output signals of type Boolean" ,
Modellca.Blocks.lnterfBces.Blocklcon
D
Basicgraphical layoutof continuous block
partial block BlockIcon "Basic graphical layout of continuous block" end. mecxrecm
o
Modelica.Blocks.lnterfaces.SO
SingleOutputcontinuous controlblock
partial block SO "Single OUtput continuous control block" extends BlockIcon; output RealOUtput y "Connector of Real output signal" , end SO,
o
Modellca.Blocks.lnterfaces.MO
MultipleOutputcontinuous controlblock
partial block MO "Multiple OUtput continuous control block" extends meexreen , parameter Integer nout (min _!) • 1 -Number of outputs", output RealOUtput y lnout l "Connector of Real output signals" ; end HO ;
Modellca.Blocks.lnterfaces.SISO
Appendix D-Modelica Standard Library Modelica.Blocks.Interfaces 763
o
end SISO ;
extends BlockJcon; parameter Integf3:r n-1 "Dimension of input and output vectors ."; input Reallnput ul Inl "Connec t o r 1 ot Real input signals " ; input Realinput uz Inl "Connector 2 of Reel input signals" ; output RealOutput y (nl "Co nnecto r of Real output signals " ; end MI2MO :
Modellca.Blocks.lnterfaces.SI2S0
Modelica.Blocks.lnterfaces.SlgnaISource
Single Input Single Output continuouscontrol block
part ial block 5150 "Si ng l e Input Single Ou t pu t continuous control block" extends BlockIcon ; i npu t ReallnptJt u "Connector of Real input sig na l"; output RealOUtput y "Co nn ec t o r of Real output sIgnal" ;
2 Single Input/I Single Output continuous control block
O
Block has two input vectors ul and u2 and one output vector y. All signals are scalar.
partial block 512 50 "2 Si ng le I nput / 1 S i ng l e Output conti nuous control block" extends Blocklcon; input 'Real Input ul "Connector of P.eal input signal 1 " ; input Reallnput u2 "Connector o f Real input s ignal 2 " j output RealOutput y "Connector o f keal output 8190all1; end 51250;
Modellca.Blocks.lnterfaces.MISO Multiple Input Single Output continuous control block
O
Block has a vector of continuous input signals and one continuous output signal.
partial block HISO "Mul t i p l e Input Single OUtput continuous control block " ext.ends Blocklcon ; parameter Integer nin'el "Number of inputs " , input RealInput u ln t n l "Connector of Real input signals ll ; output RealOutput y "Connector of Real output signal" ; end HISO;
Modellca.Blocks.lnterfaces.MIMO Multiple Input Multiple Output continuouscontrol block Block has a continuous input and a continuousoutput signal vector. The signal sizes of the input and output vector may be different.
O
partial block MIMO "MUltiple Input MUltiple Output continuous control block II extends BlockIcon : parameter Integer nin_1 "Number of inputs" ; parameter Integer nout.1 " Numbe r of outputs" : input Reallnput u (n in] "Connectior' of Real input 81gn&18 11 ; output RealOutput y(nout) "Connector o f Real output signals" ; end MIMO ;
Modellca.Blocks.lnterfaces.MIMOs Multiple Input Multiple Output continuouscontrol block with same number of inputs and outputs
O
Block has a continuous input and a continuous output signal vector where the signal sizes of the input and output vector are identical.
partial block MlHO. "MUltiple Input Multiple Output continuous control block with same number of inputs and outputs " extends BlockIcon ; parameter Integer n -l "Number of i npu t s (. number of outputs) " ; input RealInput u Inl "Connector of Real input signals" ; output RealOutput yIn) "Connector of Real output signals" ; end MIHO.;
Modellca .Blocks.lnterfacea.MI2MO 2 Multiple InputlMultipleOutput continuous control block Block has two Input vectors uI and u2 and one output vector y. All vectors have the same numberof elements. partial block MI2HO " 2 Multiple Input I MUltiple Output continuous cont rol block"
o
Base class for continuoussignal source
partial block SignalSource "Ba s e class for continuous signal source" extenda SO; parameter Real offBet.O ·offset of output; signal": parameter SIunits. Time startTime.O "o utput - offsl:!!t tor t ime < startTime" ; end SignalSource ;
o
Modellca.Blocks.lnterfsces.SVcontrol Single-variable continuouscontroller
partial block SVcontrol "Si ng l e - Va ri ab l e continuous controller" extends Blocklcon ; i npu t RealInput u s "Co nn ec t o r of setpoint input signal" ; input Real Input u m "Connector of measurement input signal II : output RealOUtput y "Connector ot actuator output signal" : end SVcon trol:
Modelica.Blocks.lnterfaces.MVcontrol
o
Multivariablecontinuouscontroller
partial block MVcontrol tlMu l ti · Va r i ab l e continuous controller" extends BlockIcon ; parameter Integer nu s .. 1 "Numbe r of setpoint i npu t s " ; parameter Integer nu=:n."'1 "Number of measurement i npu t s " ; parameter Integer ny_I "Number of actuator outputs" ; input Reallnput u_s Inu _s} "Connector ot setpoint input signals" : input Reallnput u m(nu m] "Connector ot measurement input signals " ; output RealOutput y Iny) "Corne c t o r of a.ctuator out.put; signals" ; end MVcontrol ;
Modellca.Blocks.lnterfaces.BooleanBlocklcon
r-..·. ·.·.1
I L._._......I
Basic graphical layout of Boolean block
I
partial block BooleanBlocklcon "Basic graphical layout of Boolean block"
end BooleanBlocklcon;
Modellca.Blocks.lnterfaces.BooleanSISO Single Input Single Output control block with signals of type Boolean partial block Boolean5ISO "Single Input Single Output control block with signals of type 900lean"
extends BooleanBlocklcon ; public input BooleanInput u IIConnector of accreen input signal" ; output BooleanOutput y ecoeeeeeor of Boolean output e ignal 11 ; end BooleanSISO ;
Modelica.Blocks.lnterfaces.BooleanSlgnaISource
764 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica p····_·_···-l
l.,..J
drive the integral outside of this bound, the integration is halted and only restarted if the input drives the integral away from the bounds.
Base class for Boolean signal sources
bloc k LimIntegrator "Int eg r at o r with l imited values of the outputs" parameter Real k.l "I nt eg ra t o r gains" ; parameter Real outMax _1 "Upper limits of outputs", parameter Real outMin- ·outMax "Lower limits of outputs" ; parameter Real yO-O "Start values of integrators";
partial block BooleanSlgnalSource
"Base class for Boolean sIgnal sources" extends BooleanBlockIcon ; output BooleanOUtput y -ccenecece of Boolean output signal·; end BooleanSlgnalSource ;
Modelica.Blocks.lnterfaces.MI2BooleanMOs 2 Multiple InpullBooleanMultiple Output block with same signal lengths ~·····_ ·····1 Block has two Boolean input vectors uI and u2 and one .i Boolean output vector y. All vectors have the same L .... _._.•.' numberof elements.
r
parti al block HI2BooleanMOs "2 Multiple Input I Boolean Multiple Output block with SArt1(! signal lengths" extends Boo l e anBl oc k Jco n; parameter Integer 0.1
-meene i on of input and. output vectors ."; input Real Input ul (nJ "Connector 1 of Boolean input signals" ; input Reallnput u2 (n) "Connector 2 ot Boolean input sIgnals", output BooleanOUtput y (oj "Connector o f Boolean output signals" ; end M12BooleanMOs ;
extends Interfaces.SlS0(y(start_yO») j equ ation der(y ) _ if Y < outHin and u < 0 or y > outHax and u > o th en 0 else k.u I end Limlntegrator ;
Modellca.Blocks.Continuous.Derlvatlve
. {J I\.-..
Approximatedderivativeblock This block defines the transfer function between the
~ . '::-:: " input u and the output y element-wise as approximated derivative: y = «(k • s) I (T. s +
I» • u
If you would like to be able to change easily between different transfer functions(FirstOrder,SecondOrder, ... ) by changing parameters, use the general block TransferFunctioninstead and model a derivative block with parametersb =[k.O}, a = IT. II. blo ck Deri vat ive "Approx i mat ed derivative block" parameter Real k.l ·Ga ins· , par ameter Stuni ts . Time T (min=Mod e l ica . Constants . SHALL)
Modelica.Blocks.lnterfaces.lntegerlnput Connector with input signals of type integer connector JntegerInput • input IntegerSlgnal "Connec t o r wi th input signals of type Integer· ;
Modelica.Blocks.lnterfaces.lntegerOutput Connector with output signals of type integer connector IntegerOUtput • output IntegerSignal "Connector with output signals of type Integer" ;
0 .01 "Ti me constants ('['>0 required ; T-O is ideal derivative block)" j extends Interfaces . S IS0 ; output Real x "St a t e of block" , equ ation der (x) _ if noEvent (abs (k) > - Hodel ica . Constants . IPS ) then (u . x} IT else 0 ; y • it: noEvent (abs (k) ,.. Modelica . Constants. BPS) then (kIT)· Iu - x} else 0 j end Derivative ;
Modelica.Blocks.Contlnuous.FirstOrder
Modelica.Blocks.Continuous
0'.'. / i2a 0= {J L @ e Inlegra10r
Urrl nlegralor
DerivaUw
FlrslOde
O requi red) " J extends Interfaces . S I SO; output Real x "Sta t e of block" I equation der(x ) • u/T : y • k* (x ... u) 1 end PI I
Modelica.Blocks.Contlnuous.PID
,'L;
PID controller in additive description form
~ This is the text-book versionof a PID-controller. For a
. ...I~~'~
more practically useful PID-controller. use block UmPlD.
block PID "PID ~con troller
i n additive descr i pt ion f o rm" ex tends rneee reces . S IS O;
parameter Real k - l " Ga i n" ; parame t er S tun i ts . Time Ti (mi n ..Model ica . Co nstants . SMALL ) 0.5 "T i me Con s tant of Integra tor " ; parameter Siunits . Time Td (min- OJ _ 0 .1 "Time Constant of Derivative block " ; parameter Real Nd(min-Modelica . Constant s . SMALL) _ 10 " The higher Nd, the more ideal the d e ri vat ive bl ock " ; Bl ocks .Math .Gain P " Propo r t i o na l part o f PI C controller" ; meeae . Co n t i n uou s. Integrator I (k -l /T i ) " I n t eg r a l part o f PIn c o n t rol l er" ; Bl ocks . Continuo us .Derivati ve 0 (k _Td , T_ma x ( (Td /Nd , lOO-Modelica . Co n s t a nt s . EPSJ ) ) "Derivative part of PID controller " J Blocks .Math .Gain Gain(k.. k) "Gain o t PI D c o nt r o l l e r "; Blocks .Hath.Add) Add ; equation connect (P .y, A.dd.ul); connect (1 . y , Add.u2 ) ; connect (D.y , Add .u3) ; connect (A.dd.y, Gain .u) ; connect (y , Ga i n .y) ; connect (U, I .u) I ecnnee e tu, P . u) ; connect (u , D.u ) ; end PIO ,
Modellca.Blocks.Contlnuou8.L1mPID PID controller with limited output, anti-windupcompensation and setpoint weighting
~ 1/
r. . PI?
.........~
This is a PID controller incorporatingseveral practical aspects. II is designed according to Chapter 3 of the book by K. Astroem and T. Haegglund: PlD Controllers: Theory, Design, and Tuning. 2nd edition, 1995.
Besides the additive proportional. integral, and derivative part of this controller, the foUowing practical aspects are included: •
The output of this controller is limited. If the controUer is in its limits. antiwindup compensationis activated to drive the integrator stale to zero.
The high-frequencygain of the derivative part is limited to avoid excessive amplification of measurementnoise. Setpoint weighting is present. which allows weighting the setpoint in the proportionaland the derivative part independentlyfrom the measurement. The controller will respond 10 load disturbances and measurement noise independently of this setting (parameters wp, wd). However, setpoint changes will depend on this setting. For example. it is useful to set the setpoint weight wd for the derivative part to zero. if steps may occur in the setpoinl signal. block LimPID " PI O c o n troller with limi ted output , ant i windup c ompe ns ation and setpoint .....eighting · extends Interfaces .SVcontrol ; parameter Real k (min.O) • 1 "Ga i n of PIO bl ock" ; parame ter SIunit s . Time Ti fmin_Modelica . Cons tants. SMALL) 0 .5 "T ime con s t a n t of Integrator block " ; parame ter s runt ee . Time Td (min-O) - 0 .1 "Time c o n s t a nt of Derivative block" ; parameter Real yMax-1 "Upper limit of outpnt " , parameter Real yMin_ -yMax "Lo.....er limit of output " ; parame ter Real wp(min-O) - 1 "Set -poi:lt weight f or Proportion"l bl ock ( 0 • . 1)·; parameter Real wd (min -a) "' 0 "S et~ po i n t weight for Derivative block (0 • • U .. ; parameter Real Ni (min_lOO-Madellca .Constants . BPS ) • 0 .9 "Ni -Ti is time constant of anti-windup compensation " ; parameter Real Nd Cm in-lOO-Modelica . Co n s t a n t s . IPSl - 10 "Th e h i gher Nd, the more ideal the derivat.i ve bl ock " ; Blocks . Nonl inear . Lim i ter 1 imiter (uMax_yHax , uMin-yMin ) ; Bl o cks .Hat h .Add addP(kl .wp, k2. -ll; Blocks . Ha t h . Ad d addDtkl_wd , k2".-1) ; Bl ock s .Mat h . Gain P , Blocks .Continuous . Integra tor I (k-l /Ti) ; Bl ocks . Con t inuous . De r i v a t i v e 0 (k_Td . T_max « ITd /N d , 1. e - 14 ) II :
Bl ocks . Ha t h . Ga i n gainPIO !k_k); Bl ocks .Math.A.dd3 addPID ; Bl ocks .Hath .Add) addI (k2 . -l) ; Bl ocks .Ma th .Ad d addSat(k2 . -l) ; Bl ocks . Ma t h . Ga i n gal nTrack (k_ l / (k-H!) ) ; equati o n a s s e r t( yMax >_ yMin . " P I O: Limits must be c or.s istent " I ; connecu Iu B . addP .ul ) ; connec t (u-m. lJ.d d P .u2) ; conn ec t (u- e , addD . u l ) ; connect (u-m, addD .u2 ) ; connec t Iu- B . add I . ul ) ; c onnectCu-m. addI.u2) ; conn ec t (gainTr a c k . y, addI . u J ) ; c onnect (a d d P .y, P . U) ; connec t (addD .y, D. u ) ; conne c t (addI.y, I . u ); c onnec t (P .y, addPIO.ull , c onnect (D.y , addPID .u2) ; c o nn e ct (I . y , a dd PI O. u 3 1; connec t (a ddPID .y, gainPID .u) I con ne c t (gainPID .y , addSat.u2) ; connect (addSat .y. gainTracJt .u) I connect (gainPID.y, limiter .u) ; connect (I imi ter . y, y) 1 c o nn ec t (llmiter .y, addSat .ul) ; end LimPID;
Modellca.Blocks.Contlnuous.TransferFunctlon Linear transfer function S)
~ a(( 5) _ _ _
This block defines the transfer function between the input u and the output y as (nb =dimension of b. na = dimension of a):
b[l)*s"[nb·l) + b(2)*s"[nb-2] + ... + b[nb) yes) =
* u(s)
a[I)*s"lna·l) + a(2)"s"[na·2) + ...+ a[na) State variables x are defined according to controllercanonical form. Initial valuesof the states can be set as start values of x. block TraJ1sferFunctlon "Linear transfer function" extends Interfaces . S I SO; parameter Reel b ( d • (1 J "Numerator coetficients of transfer f unct ion . " ; para""'ter Re al a ( d • (I, 1 J "De nomi na t o r c oefficients of transfer f Wlction . " ; output Real x(size(a , U - 1) ·State of transfer function fr om c ontroller cano n ica l torm ";
766 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica protected parameter Integer naee t ae Ie , 1) ·Size of Denominator of tranBfer fWletion . "1 parameter Integer nb(max_na) • size{b , 1) · s ! ze of Numerator of tran8fer function ." , parameter Integer nx _size(a, 1) - I; Real xldot "Der i v at i ve of first state of TransferFen" ; Real xn "Highest order state of TransferFeD" ,
parameter Rea! uM in (max-uMax) • ·uMax "Lower limits of dead zones-; extends Interfaces . SISO ; equation y • if u > uHax then u . uMax else if u < uMln then u uMin else 0 ; end Dead Zone ;
equat ion
Modelica.Blocks.Math
(der (x ) ; xnl '" {xldot; xl ; lui s transpose ( Ie l ). (xldot : xl ; [yl '" c renepose Haeros Ina - 00. 1) ; bJ)·[xldot, xJ ; end TransterFunction;
Modellca.Blocks.Contlnuous.StateSpace Linearstate space system
B ... C •D
~
The State Spaceblock defines th . e relationbetweenthe input u and the output y in state space form: denx) =A • x + B • u, Y =C • x + D • u
The input is a vectorof length nu, the outputis a vectorof length ny, and nx is the numberof slates. Accordingly, A has the dimension: A(nx,nx), B has the dimension: B(nx,nu), C has the dimension: C(ny,nx), D has the dimension: D(ny,nu)
block StateSpace "Linear state space system" parameter Real A( l, 8ize(A, 1»)·11, 0, 0 , 1] "Ma.trix A of state space model· ; parameter Real B [size (A. 1). :J- [1; 1) ItMatrix 8 of state space model It i parameter Real Ch, size(A . 1))-11. 1) ItMatrix C of state space model" ; parameter Real D[sizetC, 1), size (8 . 2)) _zeros (size(C . II. size{B . 2») "Matrix 0 of state space model" , extends Interfaces.MIMO(final oin-size(S, 2), final nout-she(C, 1 ) ; output Real x(size(A . 1)) "State vector" , equat ion der(x) • A·x + B·u ; y - C·x + D·Ui end scaeespece ,
Modelica.Blocks.Nonlinear
ill ill Urriter
DeadZone
This packagecontainsdiscontinuous and nondifferentiable algebraic input/output blocks. In particular,the following blocksare provided: Limiter Limit the rangeof a signal. DeadZone Providea regionof zero output. Modellca.Blocks.Nonlinear.L1mlter
1/'
Limit the range of a signal
~ The Limiterblock passes its input signalas output .. •.... ,. signal as long as the input is withinthe specifiedupper and lowerlimits. If this is not the case, the corresponding limitsare passedas output.
block Limiter "Limit the range of a signal" parameter Real uMax-1 ·Upper limits of input signals "; parameter Real uMin{maxcuMax) - ·uMax "Lower limits of input signals It t extends Interfaces . S I SO, equation y _ if u ,. uMax then uMax else if u < uMin then uMin else U ; end Li mi ter i
{>
@
Gain
Ma~
~ ~n Feeack
~
~
:t!J:t!Jtrr\D~Gt {SD~~WG~
W~ W Wle e This packagecontains basic mathematical operations, such as summation and multiplication, and basic mathematical functions, such as sqrt and sin, as input/output blocks. All blocksof this librarycan be connectedeither with continuous blocksor with sampled-data blocks. In particular,the following operations and functions are provided: Twolnputs Changecausalityof input signals TwoOutputs Changecausalityof outputsignals Gain Outputthe input multiplied by a scalar gain MatrixGain Outputthe productof a gain matrixwith the input Sum Outputthe sum of the elementsof the input vector Feedback Outputdifferencebetween commandedand feedback input Add Outputthe sumof the two inputs Add3 Outputthe sum of the threeinputs Product Outputproductof the two inputs Division Outputfirst inputdividedby second input Abs Outputthe absolutevalueof the input Sign Outputthe signof the input Sqrt Outputthe squareroot of the input Sin Outputthe sine of the input Cos Outputthe cosineof the input Tan Outputthe tangentof the input Asin Output the arc sine of the input Acos Outputthe arc cosineof the input Atan Outputthe arc tangentof the input Atan2 Outputatan(uI/u2) of the inputsul and u2 Sinh Outputthe hyperbolic sine of the input Cosh Outputthe hyperbolic cosineof the input Tanh Outputthe hyperbolic tangentof the input Exp Outputthe exponential (basee) of the input Log Outputthe naniral(basee) logarithmof the input LoglO Outputthe base 10 logarithm of the input Modellca.Blocks.Math.Galn Outputthe productof a gain withthe input signal ~ This blockscomputes ~ wi th the input u : y =
outputy as product of gain k k • u,
Modelica.Blocks.Nonllnear.DeadZone
' 0
Providea region of zero output The DeadZoneblock definesa regionof zero output. If ;./ .• the inputis within uMin •.. uMax. the output is zero. Outsideof this zone, the output is a linear function of the input with a slope of I.
r .
block DeadZone ·Provide a region of zero output· parameter Real uHax_l ·Upper limits of d.ead. zone.";
block Gain "OUtput the product of & ga in with the input signalparameter Real k.l ItGain vector multiplied element -wise with input vector" ; public input Interfaces .RealInput u -Input signal connector- j output Interfaces .RealOutput y ItOUtput signal connector - ; equation y • k·u I
Appendix D-Modelica Standard Library Modelica.Blocks.Math 767 end Gain;
Modellc8.Blocks.M8th.M8trlxG8in
B
Outputthe product of a gain matrixwith the inputsignal vector
K
This blockscomputesoutput vectory as productof the gain matrixK with the input signal vectoru: y • K * U;
blOCk MatrixGain "Output the product of a gain matrix with thO! input signal vector" parameter Real K( , . d=[1 , 0; 0 , 1) "Gain matrix which is multiplied with the input" j extends Interfaces.MIMO(final nin-sizeCK, 2) , final nout_sizeO 0 required)
Appendix D-Modelica Standard Library Modelica.Blocks.Sources 769 ~ .~ ~ This blocks computesthe output y (element-wise)as the base 10 logarithm of the Inputu: y = 10g10(u) ;
tc:
An error occurs if the elementsof the input u are zero or negative. block LoglO "Out put the baae 10 logar ithm o f the input (input:> 0 required)" extends Interfaces . 5 150; equation
y. Modelica .Math.loglO(u ) , end LoglO ,
Modelica.Blocks.Math.Twolnputs Changecausalityof input signals(e.g.• for inversemodels) This block is used to enableassignment of valuesto variables preliminarily defined as outputs (e.g.•useful for inverse model generation). model Twolnputs "Change c aus a l i t y of input signal s (e . g . tor inverse models)" e xtends Blocks . Interfaces . mcckrcom input Blocks . I nterfaces . Real Input u 1 ; input Bl oc ks . Interf aces . Rea], Inp ut u2 ; equation u1 .. u2; end Twolnputs ;
Modellca.Blocks.MBth.TwoOutputs Change causalityof outputsignals (e.g.• for inversemodels) This block is used to enablecalculation of valuespreliminarily definedas inputs. (e.g.•useful for inversemodelgeneration). model TwoOutputs "Change causality of output signals (e .g. for inverse models)" extends Blocks . Interfaces . Bl oc k I c on ; output Blocks . Interfaces . RealOUtput y2 ; output Blocks . Interfaces . RealOUtput yl; equation yl • y2 , end TwoOutputs ;
All sourcesare vectorized. This meansthat the output is a vector of signals. The numberof outputs is in correspondence to the lengthof the parametervectorsdefining the signals.Examples: II out put ILl = 2·sin(2*pi*2.1) ; II output Iz l = 3*sin(2*pi·2 .3) ; Mode1ica.B1ocks .Sources.Sine sl(amp1itude={2.3) . freqH z={2.1,2 .2j) ; I I output [1] = 3·sin(2·pi*2 .1) ; II out.put Iz l = 3·sin(2·pi·2 .3); Mode1ica .B1ocks .Sources .Sine s2(amp1itude={3} . freqHz={2 .1,2 .3j) ; The first instancesl consistsof two sinusoidal outputsignals with the given amplitudes and frequencies. The second instance s2 consists also of twosinusoidal outputsignals. Since the amplitudes are the same for all output signalsof s2. this value has to be providedonlyonce. This approachis used for all parameters of signal sources: Wheneveronly a scalar value is providedfor one parameter. then this value is used for all output signals. All Real sourcesignals (with the exception of the Constant source)have at least the following two parameters: Offset Value which is added to aU signal values. StartTime Start timeof signal. For time < starff'ime, the output is set to offset. The offset parameteris especiallyuseful in order to shift the corresponding source, such that at initial time the systemis stationary. To determine the corresponding valueof offset usuallyrequires a trimmingcalculation. ModelicB.Blocks.Sources.Clock
Modelica.Blocks.Sources
f0lE}[B0 [§} ~Sine ~ ~ Constant
Step
Rarrp
Sine
K1 8ill ~ ~ Kin~P fIT2 [jJ E1 Boo~ep [[l [00 Sa~ger ruD
~~IS TimeTeble
Pulse
BooleanConstant
SawTooth
Trapezoid
BooleanPulse
This packagecontains sourcecomponents. i.e., blockswhich have only output signals. These blocksare usedas signal generators. The following .wurcesare providedto generate Real signals: Clock Generate actual time. Constant Generateconstantsignals. Step Generatestep signals. RampGenerateramp signals. Sine Generatesine signals. ExpSine Generateexponentially dampedsine signals. Exponentials Generatea rising and fallingexponential signal. Pulse Generatepulse signals. SawTooth Generatesawtoothsignals. Trapezoid Generatetrapezoidal signals. KinematicPTP Generatean acceleration signal to moveas fast as possiblealong a distancewithin givenkinematicconstraints. TimeTabte Generatea (possiblydiscontinuous) signal by linear interpolation in a table. The following sourcesare providedto generate Boolean signals: BooleanConstant Generateconstant signals. BooleanStep Generatestep signals. BooleanPulse Generatepulsesignals. SampleTrigge r Generatesample triggers.
block Clock "Generate actual time signals" parameter Real offset.O "Offsets of output s ignals "; parameter SIunits . Time startTime.O "OUt put • offset for time < startTime" ; extends Interfaces .SO : equet Ion y .. e-ffset ... (if time < startTime then 0 else time - startTime): end Clock ,
J
ModelicB.Blocks.Sources.Constant
I'.. .
Generateconstantsignalsof type Real
block Constant "Generate constant signals of type Real " parameter Real k.t "Constant output. values ", extends Interfaces . SO ; equation
v
»
k,
end Constant ;
Modellca.Blocks.Sources.Step
m
bCr
Generatestep signalsof type Real
block Step "Generate step signals of type Real " parameter Real height.l "Heights of steps "; parameter Real offset.O "Offsets of output signals "; parameter SIunits . Time startTime.O "OUtput • offset for time c startTime "; extends Interfaces .SO; equation y • offset + (if time < .t.rtTi~... then 0 e1.e height) ; end Step ;
770 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica Modelica.Blocks.Sources.Ramp
r-;:=l
lLr
Generate ramp signals
block Ramp "Generate ramp slgn81s" parameter Real height_1 "Heights of ramps"; parameter Real duration (min ..Model ica .Constants . SMALL) • "Durations of ramps" ; parameter Real offset _O "Offsets of output sIgnals· I
parameter SIunits . Time startTime.O "OUtput., offset for time < startTime" i extends Interfaces. SO; equation y = offset + (if time < BtartTlme then 0 else if time < (startTlme + duration) then (time - startTime) ·helght/duratlon else height)
Modellca.Blocks.Soufces.Pulse I
end Ramp;
IV
Modelica.Blocks.Soufces.Slne
I
~
Generatesine signals
block SIne "Generate sine signals" parameter Real amplitude-1 "Amplitudes of sine waves", parameter SIunits . Frequency freqHz_l "Frequencies of sine waves" ; parameter SIunits . Angle phase=O "Phases of sine waves·, parameter Real offset.O "Offsets of output signals"; parameter SIunits . Time startTime·O "Output .. offset for time < startTirne"; extends Interf3ces . SO; protected constant Real pi -Modelica. Constants. PI ; equation y = offset .. (if time < startTime then 0 else amplitude·Modelica . Ma t h . sin (2pi-freqHz- (time - startTime) + phase));
\
end Sine ;
Modellca.Blocks.Sources.ExpSlne
~l
Generate exponentially dampedsine signals
block ExpSine "Generate exponentially damped sine signals" parameter Real amplitude-1 "Amplitudes of sine waves" ; parameter s tunt ee . Frequency freqHz_2 "Frequencies of sine waves"; parameter Slunits . Ang l e phase..O "Phases of sine waves"; parameter Slunits . Damping damping .. ! "Damping coefficients of sine waves" ; parameter Real offset_O "Offsets of output signals"; parameter Stunits . Time startTime_O "Out pu t _ offset for time < startTime"; extends Interfaces . SO, protected constant Real pi -Model ica . Con s t a n t s. PI ; equation y _ offset .. (if time < startTime then 0 else amplitude*Modelica.Math.exp(- (time startTime) *damping) -Modelica .Math . sin (2*pi -freqHz* (t i me - startTime) + phase)); end ExpSine,
f\.J
Modellca.Blocks.Sources.Exponentlals
I
Generatea risingand falling exponential signal
model Exponentials "Generate a rising and falling exponential signal" parameter Real outM a x _l " He i gh t of output for infinite riseTime" 1 parameter Stunits .Time riseTime(min"'O) • 0 .5 "Rise time" ; parameter Slunits .Time riseTimeConst (min ..Modelica . Constants •SMALL) • 0 .1 "Rise time constant" , parameter SIunits. Time fall TimeConst (min-Modelica . Constants . SMALL) • riseTimeConst "Fall time constant",
parameter Real offset-O "Offsets of output signals" j parameter SIunits . Time startTime-O "OUtput = offset for time < startTime" 1 extends Interfaces . 50 ; protected Real y_riseTime; equation y_riseTime • outMax- (1 - Modelica .Math .exp(rieeTime/riseTimeConst) ; y '" offset .. (if (time < startTime) then 0 else if (time < (startTime .. r i s eT! me) ) then outMax- (l - exp I- (time startTime ) IriseT!meConst» else y _riseTime*Modelica .Ma t h . exp t - (time - startTime riseTime) I f a l l Ti meCon s t ) ), end Exponentials ;
~
l1lli
Generate pulsesignalsof type Real
block Pulse "Generate pulse signals of type Real" parameter Real amplitude_1 "Amplitudes of pulses" ; parameter Real width( final min=Model Ica . Constants . SMALL, t inal max.IOO I or 50 "Widths of pulses in t of periods" ; parameter SIunits . Time period (final min"'Modelica . Constants . SMALL) _ I "Times for one period" ; parameter Real offset.O ·Offsets of output signals" 1 parameter SIuni ts. Time startTime=O "OUtput", offset for time < startTime"; extends Interfaces . SO; protected SIunits . Time TOCfinal start=startTime) "Start time of current period"; equation when sample (s t a r t Ti me , period) then TO - t i me ; end when ; y .. offset .. (if time < startTime or time >_ TO .. width then 0 ef ee amplitude); end Pulse ;
Modelica.Blocks.Sources.SawTooth
~ Generate saw toothsignals
l:MJ
block SawTooth "Generate saw tooth signals" parameter Real amplitude"'l "Amplitudes of saw tooths" , parameter SIunits . Time period (final mln:eModelica . Co ns t a nt s . SMALL) • 1 "Times for one pe riod " ; parameter Real offset-O "Offsets of output signals"; parameter SIunits . Time startTime-O "Output - offset for time < startTime" ; extends Interfaces. SO; protected SIunits . Time TO(final start.startTime) "Start time of current period " ; equation when sample (startTime , period) then TO - time, end when ; y • offset .. (if time e startTime then 0 else Camplitude/period), Ctime - TO» , end SawTooth;
Modellca.Blocks.Sources.Trapezold
1l!lL~ Generate trapezoidal signalsof type Real block Trapezoid "Generate trapezoidal signals ot: type Real" parameter Real amplitude_! - Ampl i t u de s of trapezoids"; parameter Slunits . Time rising (final min-OJ • 0 "Rising durations of trapezoids· ; parameter SIunits . Time width(final min _O) - 0 .5 "tfidth durations of trapezoids · 1 parameter Slunits . Time falling (final min:eO) • 0 "Falling durations of trapezoids", parameter SIunits. Time period (final min-Model iea . Constants . small) - 1 "Time for one period" ;
Appendix D-Modelica Standard Library Modelica.Blocks.Sources 771 parameter Integer nperiod.. -l "Number of periods « 0 means infinite number of periods) "; parameter Real offset.O "Offsets of output signals"; parameter SIunits. Time startTime=O "Output e offset for time c startTime"; extends Interf aces. SOi protected parameter SIunits. Time T_rising=rising "End time of rising phase within one period"; parameter SIunits. Time T_widthIlT_rising ... width "End time of width phase within one period"; parameter SIunits. Time T_falling=T_width + falling "End time of falling phase within one period" i SIuni ts. Time TO(f inal start-startTime) "Start time of current period" i Integer counter (start..nperiod) "Period counter"; Integer counter2 (start:rnperiod) ; equation when pre (counter2) 0 and sample (startTime, period) then TO .. time; counter2 :: pre (counter) ; counter:: pre (counter l - (if pre (counter) > 0 then 1 else 0); end when; y = offset + (if (time < startTime or counter2 == 0 or time >- TO + T falling) then 0 else if (time -; TO ... T_rising) then (time TO)*amplitude/T rising else if (time _ table Inext, 1) loop next :- next + 1 . end while, II Deline next time event , if last table entry not II reached if next < nrow then next Event : . BtartTime + table (next. 1) j end it ; II neeeredne interpolation coefficients nextO :_ next - I ; dt : - table (next , 1) - tablelnextO , 1) , if dt _ pre(nextEvent),initial()} then (a,b.nextEvent,last) : _ getlnterpolationCoefficlents (table, offset , startTime, time, last. 100·Modelica .Constants .EPS), end when, equation y • a·time + b ; end TimeTable;
Modelica.Blocks.Sources.BooleanConstant
[,-·-····--··1 I:
Generate constant signals of type Boolean
r
L:~:_:..-.:.:..::J
block BooleanConstant "Generate constant signals of type Booleanparameter Boolean k_true ·Constant output values-, extends Interfaces . Boo l e a n Si gna l So u r c e ; equation y • 1 level) then 1 else Roff) ; n1.i .. sl·(if (control.v > level) t h e n Gon else l); p .v - n2.v ,. s2·( lf (control.v , level) then Roff else 1), 02 . i " 82· (if (control. v > level) then 1 eloe Gon) I end ControlledldealCommut i ngSwitch ,
Modellca.Electrlcal.Analog.ldeal.ldeaIOpArnp Idealopamp(norator-nullator pair) The idealOpArnp is a two-port. The left port is fixedto + vr = 0 and i l = 0 (nullator). At the rightport bothany voltagevz and any current I 2 are possible (norator).
1[-
model IdealOpAmp Itl d ea l opamp (norator-nullator pair)" SI . Voltage vi " Vo l t ag e drop over the left port" J SI . Voltage v2 "Voltage drop over the right port", S I.CUrrent 11 "Cur r e nt flowi ng from pce • to neg . pin of the left port" , 51 .CUrrent i2 "Cur rent; flowing from pos. to neg . pin of the r ight port" ; Modelica . Electrical .Analog . Interfaces . PositivePin pI "Pos Lt Ive pin of the left port II j Modelica . Electrical .Analog . Interfaces . Nega t i v e Pi n nl ItNegative pin of the left port " ; Modelica . Electr i cal .Analog . Interfaces . PooitivePin p2 "Positive pin of the right port lt , Model ica . Electrical . Analog . Interfaces . Negat i vePin 02 "Nega ti ve pin of the r ight port It; equat ion vi " pl. v - n l . v ; v2 _ p2.v - n2.v j o - pl. i + nr . i ; o " p2 .i + n2 .i , 11 • pl.i; i2 • p2 .i ;
vr -
0,
11 • 0, end IdealOpAmp ,
Modellca.Electrlcal.Analog.ldeal.ldeaIOpAmp3Pln Idealopamp(norator-nullatorpair),but 3 pins The idealOpArnp with three pinsis of exactlythe same behavioras the idealOpAmpwith fourpins.Only the negativeoutputpin is left out, Boththe input voltage and currentare fixedto zero(nullator). At the outputpin bothany voltage vz and any current i2 are possible. model Idea1OpAmp3Pin ItIdeal opamp (norator·nullator pair ) , but 3 pins" Modelica . Electrical .Analog . Interfaces . PositivePin i n-» '"Positive pin of the input port"; Model ica . Electrical .Analog • Interfaces . Nega t i ve Pl n in_" "Negative pin of the input port" , Modeli ca . Electrical .Analog . Interfaces . Positi vePin out "OUtput pin" , equation in-p .v • in_n .v, iny .i • 0 , Inn .i-O , end IdealOpAmp3Pin ;
Modellca.ElectrlcaI.Analog.ldeal.JdeaIDlode Idealelectrical diode ~ Idealeleclrical diode. This is an idealswitchwhichis open, whenit is reversed biased(voltagedrop < 0), and whichis closed.whenit is conducting (current> 0). In order to preventsingularities duringswitching, the openeddiodehas a high resistance and the closeddiodehas a low resistance. If the actual circuithas an appropriate structure. the limitingcase is also allowed, i.e., the resistance of the closeddiodecouldbe exactly zeroand the conductance of the opendiode couldbe also exactly zero(i.e., the resistanceis infinity). Note. there are circuitswherea description with zero/infinity resistances is not possible. model IdealDiode "Ideal electrical diode" extends Madellea. Electrical .Analog . Interfaces .One Po r t , parameter 51 .Resistance Roft (final min-O) • 1 .1-5 ·Closed diode resistance lt , parameter 51.Conductance. Gon (final min_OJ • I .E -5 "Opened diode conductance" , Boolean off (start _true) "Switching state of diode" 1 protected Real s "Aux il i a r y va r iab l e " ;
Appendix D-Modelica Standard Library Modelica.ElectricaI.Analog.Sensors 777 equation
end PotentialSensor ;
oft. 8 < 0 ; V • 8· (if off then 1 else Roft) ; i • o' (if off then Gon eloe 1) , end IdealDiode ;
Modellca.Electrlcal.Analog.Sensors.VoltageSensor
Modellca.Electrlcal.Analog.ldeal.ldeaITransformer
~ Sensor to measurethe voltagebetween two pins
Idealelectricaltransformer
JC
The ideal transformer is an ideal two-portresistive circuit ele~ent which is characterized by the following twoequations:
vi = n· v2 12 = -n • i1
model Vol tageSensor IISensor t o measure the voltage between two pins" extends Interfaces . RelativeSenBor ; Modelica . Blocks . Interfaces. RealOUtput v "Voltage between pin p and n ( .. p . v - n . v)" ; equa tion p. i • 0 ,
n . i .. 0 ;
where n is a real numbercalled the turnsratio. model IdealTransformer "Ideal elec trical t r an s fo rme r" extends Modelica . Electrical.Analog. Interfaces . TwoPort ; parameter Real 0.1 "Turns ratio " ; equation vr .. n*v2 ; 12 • - o *il ;
v .. p . v - n .v; end Vo l t ag eSe n s o r;
Modellca.Electrlcal.Analog.Sensors.CurrentSensor ~
Sensorto measurethe currentin a branch
end IdealTranaformer ;
Modellca.Electrlcal.Analog.ldeal.ldeaIGyrator
Idealgyrator
rrJ 'Lo
A gyratoris an ideal two-portelementdefinedby the following equations:
il = G· v2 i 2 = -G "" '11
where the constant G is called the gyrationconductance. model IdealGyrator "Ideal gyrator" extends Modelica . Electrical .Analog . Interfaces . TwoPo rt ; parameter 51 .Conductance G.l ttGyra t ion conductance"; equation i1 • G· v 2 , 1 :2 • -G*v} ;
model CurrentSensor "Sensor to measure the current in a branch " ex tends Interfaces . Re l a t i v eSe n s o r ; Modelica . Blocks . Interfaces . RealOUtput i "current in the branch from p to n " ; equat ion p .v .. n . v ; p.i = i ; n. i • -I , end CurrentSeneor ;
Modelica.Electrical.Analog.Sources
.&
+
SignalVottage ConslanlVohag& SlepVoftage RarnpVoftage SlneVollage
end IdealGyrator I
ExpSlneVoitage
Modellca.Electrlcal.Analog.ldeal.ldle
-G
ExponenIlalsVoftage
Idle branch The model Idle is a simple idle runningbranch
model Idle .. Idl e branch" extends Model ica . Electrical .Analog . Interfaces .One Po r t ; equation i = 0, end Idle l
Modellca.Electrlcal.Analog.ldesI.Short
tt
The modelShort is a simple shortcut branch
model Short "Short cut branch" extends Model i ca . Electrical .Analog . Interfaces . One Po r t 1 equa tion
v. 0;
end Short ;
Modelica.Electrical.Analog.Sensors
PotenllalSensor
{f}
VonageSensor
~
CurrenlSensor
This packagecontainspotential,voltage, and current sensors. Modellca.Electrlcal,Analog.Sensors.PotentiaISensor ~
S8wTool:hVotlage TrapezoldVoJlage
TableVoilage
ConstantCurrent SlepCtJ'Tent RampCurrent SlneCurrenl ExpSineCurreni
ExponentialsCune n!
PulseCUlTeni
sawToolhCurrenl
TrapezoldCurrent
TableCunent
This packagecontainslime-dependent and controlledvoltageand currentsources. Modellca.Electrical.Analog.Sources.SlgnaIVoltage
Short cut branch
{J}
~
SlgnalCurrem
PulseVotlage
Sensor to measurethe potential
~
-v-o
Generic voltage source using the inputsignal as source voltage
model SignalVoltage "Gene ri c voltage source using the input signal as source voltage" extends Interfaces .One Po r t ; Mode:' i ca . mecks . Interfaces . Real Input voltage ; equation voltage,. "0; end SignalVoltage ;
Modellca.Electrical.Analog.Sources.ConstantVoltage
--1f---o Sourcefor constantvoltage model ConstantVol tage "Sou r c e tor const6.nt vo ltage " parameter $1 . Voltage V_I "Value of constant voltage" ; extends Model iea . Electrical . Analog . Interfaces . One Port ; equation v _ V;
end ConstantVoltage ;
model PotentialSensor "Sensor to measure the potent ial " extends Interfaces . AbsoluteSensor ; Modelica . Blocks . Interfaces . RealOutput ph i "Abs o l u t e voltage potential"; equation p .i • 0 , ph i . p .v ,
Modelica.Electrlcal.Analog.Sources.StepVoltage
--&
Step voltagesource
model StepVoltage "Ste p vo l t ag e s ource "
778 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica parameter 81 . Voltage V=l "Heig ht of s t e p"; ex tends Model ica. Elec t rical.Analog . Interfaces . VoltageSource (rede c l a re Hodel lea . Blocks . Sources . Step s i gnalSource (height- (VIII; en d StepVol tage ;
Modellca.ElectrlcaI.Analog.Sources.RampVoltage
--e-o
Ramp voltagesource
model RampVolt age
"Ramp volta"ge source "
parame ter 51 . Voltage V-I "He i ght of ramp"; parameter 51 . Time du rat Jon (min=Hodel i ca .Constants .SMALL) • :2
-nurae t on of ramp"; e xtends Mod elica . Electrical .Analog . Interfaces. VoltageSource (redeclare Mode l lea . Blocks . Sources . Ramp s lgnalSource
(final height_IV) . final duration_(duration)ll ; end RampVol tage ;
Modellca.ElectrlcaI.Analog.Sources.SlneVoltage ~ Sine voltagesource model SineVoltage -s.tne voltage source· parameter 51 . Voltage V.l "Amplitude of sine wave" I paramet er SI .Angle phase -O "Phase of sine wave II ; parameter SI . Frequency freqHz.l II Fre que nc y of sine wave II ; extends Hodel i ca. Electrical.Analog . Interfaces . VoltageSource ( r e de c l a re Model lea . Blocks . Sources . Si ne signalSource (
ampli t ud e - IV) • freqHz _ (freqHz). ph a se- (pha se}ll ; e nd SineVoltag e ;
Modellca.Electrical.Analog.Sources.ExpSlneVoltage _~
Exponentially dampedsine voltagesource
model Exp5 ine Voltage "Exponentially damped s ine voltage s ource II par ameter 5I .Voltage V..l "Ampli t ude of s ine wave II ; parameter 5I .Frequency freqHz-2 "Freque ncy of sine wave"; parameter 51 .Angle phase.O "Pha s e of sine wave" ; parameter 51 .Damping damping_l "Damping coeff icient of sine 'lave"; extends Modeliea . El e c t r i c a l. Ana l og . Interfaces . VoltageSource {redeclare Modeliea . Blocks . Sources . Exp5lne signalSource ( a mp li t ude- IV) . f reqHz - (freqHz). phaBe_(phase}. d amping- (damping))) ; end ExpSineVoltage ;
Modellca.Electrlcal.Analog.Sources.ExponentlalsVoltage
_-&
Rising and fallingexponential voltagesource
end Exponent ialsVoltage ;
Modellca.EJectrlcal.Analog.Sources.PulseVoltage
--6-0
Pulse voltage source
model PulseVoltage llPul s e voltage source parameter 51 . Vo l t age V. I ~ Amp l i t ude of pulse ll; parameter Real width ( f inal min _Model ica . Con s t ant s . SMALL . final max.IOO ) • 50 · Wi dt h of pulse in " of per iod ": parame t er 51 . Time period (final min ..Model ica . Co ns t ant s . SHALL) • I II Ti me f o r o ne period II ; extends Hodel ica . Electrical . Analog. Interfaces. VoltageSource (red eclare Hodelice . Block.s . Sources . Pulse signalSource ( amplitude -IV). width- (width ) . period -(period)I ) , end Pul seVoltage ;
Modellca.Electrlcaf.Analog.Sources.SawToothVoltage
--&
Sawtooth voltagesource
model SaW'ToothVolt age II Saw tooth voltage source II parameter 51. Vo l t age V.I "Amplitude of saw tooth ll : parameter SI. Time period .! · Ti me for one period "; extends Hodellca. Blectrical .Analog . Interfaces . VoltageSource (redeelare Model lea . Blocks . Sources . SawToOth BignalSource (amplitude.(V). period_lperiod) I I , end SawToothVoltage :
Modellca.Electrlcal.Analog.Sources.Trap8zoldVoltage
--9-0
Trapezoidal voltage source
model Trap ezoidVoltage -Trape zo i dal voltage source II parame ter 51 . Vo ltage V-I II Amp l i t ude of trapezo id ·; par amet e r 5 1 .Ti me r is ing Cfinal mln ..,O) • 0 IIR is ing dur a tion o f trape zo id ll ; parameter 51 .T ime width{final min_OJ - 0.5 · Wi dt h dura t ion of trapezoid ": parameter 5 1 . Time f alling (final min-a) _ 0 · Fa ll i ng duration ot: trapezoid·, par ameter 5 1 . Time period Uinal min ,.Modelica . Cons t ant s. small) • 1 IITime for one peri od" ; parameter Integer nperiod.-l "Number of periods « 0 means inf inite number of periods) II ; extends Modelica . Electrical .Analog . Interfaces . VoltageSource (redeclare Model ica . Bl o c ks . Sources . Trapezoid signalSource ( amplitude -IV) • rising- (rising) . width. (width} • falling_ {falling}. period- (period). nperiod-{nperiod}J I I end TrapezoidVoltage,
Modellca.Electrlcal.Analog.Sources.TableVoltage
_to
Voltagesourceby linearinterpolation in a table model ExponentialsVoltage IIRisi ng and falling exponential voltage source parameter Real vMax_1 "upper bound for rising edge II , parameter 51. Time riseTime (min-O) - 0 .5 ·Rise time II , parameter SI . Time riseTlmeConst (min -Model ica . Cons tants . SHALL) • 0.1 ·Rise t ime constant· , parameter 51 . Time f allTimeCon st (min ..Hodelica . Co ns t ant s . SHALL ) • r iseTimeConst "Fa l l time cons tant- , e xtends Hodel lea . Electrical .Analog . Interfaces . VoltageSource Cre declare Hodel ica . Blocks . Sources . Exponentiat"s s ignalSource ( ou t Hax- (vMax) . riseTime -{riseTime} , r iseTlmeConst - {riseTimeconst) . f aI I TJrnP.Con s t. (fallTimeConst})) ,
This blockgenerates a voltagesource by linear interpolation in a table. The time points and voltage valuesare storedin a matrix table[i.j]. wherethe first columntablel..I] containsthe time pointsand the secondcolumncontainsthe voltageto be interpolated. The table interpolation has the following properties: The time points need to be monotonically increasing. Discontinuities are allowed, by providingthe same time point twicein the table. • Values outside of the table range. are computedby extrapolation throughthe last or first two pointsof the table.
, .: . .
0
Appendix D-Modelica Standard Library Modelica.ElectricaI.Analog.Sources 779 •
• •
If the table has only one row, no interpolation is performed and the voltagevalue is just returned independently of the actual time instant, i.e., this is a constant voltagesource. Via parametersstattTime and offset the curve definedby the table can be shifted both in time and in the voltage. The table is implemented in a numerically sound way by generatingtimeevents at intervalboundaries, in order to not integrateover a discontinuous or nondifferentiable points.
Example: table = [0 0 1 0 1 1 2 4 3 9 416]
If, e.g., time (afterevent)
= 1 . 0,
the voltagev
e.g., time
1 .5,
the voltagev
2 .5.
e.g., time
2.0,
the voltagev
4.0 ,
e.g., t ime
5 . o, the voltagev
0 .0
(beforeevent), 1.0
23 . 0
(i.e.. extrapolation).
extend.s Model ica . Electrical . Analog . Interfaces . Vo l t a.g e Sou r c e (redeclare Modeli ca . Blocks . So urces . TimeTable signalSource (table-table» j end TableVol tage ;
Modellca.Electrlcal.Analog.Sources.SlgnaICurrent ~
Genericcurrentsource using the inputsignal as source current
model SignalCurrent "Gen e r i c current source using the input signal as sou rce cu rrent" extetlds Interfaces . One Po r t ; Modelica . Blocks. Interfaces. Reallnput cur r ent r equation i - c u r r e nt : end 5ignalCurrent ;
Modelica.Electrlcal.Analog.Sources.ConstantCurrent
-W
Modellca.Electrlcal.Analog.Sources.SlneCurrent ~
Sine currentsource
model S ineCUrrent "Sine current source" parameter SI .CUrrent I-I "Amplitude of si ne wave" ; parameter SI .Angle phase-O "Phase of e Ine wave" ; parameter 51 .FreQUency freqHz .. l "Frequency of sine wave" ; extends Modelica . Electrical .Analog. Interfaeee . Cu r r e nt So u r c e (redeclare aoeet Ice . Blocks . Sources . S i ne signalSour ce ( amplitude _II) . freqHz- {freqH% I. phaaee (phase)l ) I end SineCUrrent:
Modellca.Electrlcal.Analog.Sources.ExpSlneC:Jmmt
model TableVoltage "Voltage source by linear interpolation in a tabl e" parame ter Real t.abke l r , : ) - (0 , 0 ; 1 . 1 ; 2, 4} "Table matrix (time .. first column. voltage . second column)" i
~
parameter 51. Time duration (min_Hodeliea . Constants . SMALL) • 2 "Duration of ramp"; extends Madellca . Electrical .Analog . Interfaces . cur ee nes e a r c e (redeclare Modelica . Blocks .s cueee e . Ramp signalSourcp. lfinal height - {I}. fina l duration- (duration)) ) ; end RampCurrent ;
Source forconstant current
model ConstantCurrent "Source for constant c urrent " parameter SI .Current I-I " Va l ue o f constant current"; extends Hodel ica . Electrical . Analog. Interfaces. One Po rt 1 equation i . II end ConstantCUrrent ;
Modelica.Electrlcal.Analog.Sources.StepCurrent ~ Step currenlsource model StepCurrent "Step current aource" paramete"t' 51 .Current I_I "Height of step" ; extends Madeliea . Electrical .Analog . Interfaces . CUr r e n t Sou r c e (redeclare Model i c a . Slacks . Sources . Step signa1Souree lheight_\ I)) ) I end 5tepCUrrent;
Modellca.Electrlcal.Analog.Sources.RampCurrent ~ Rampcurrentsource model RampCurrent "Ramp c u r r e n t s ource" parameter 5I .Current I-I "Height of ramp" 1
.~ Exponentially dampedsine currentsource model ExpSineCurrent "Exponentially damped sine current source tt parameter Real I_I "Amplitude of sine wave "; parameter 51 . Frequency freqHz_2 "Frequency of sine wave " ; parameter 51 . Angle phase~O "Phase of sine wave " ; parameter SI .Damping damping .. 1 ttDa mpi ng coeff icient at sine wave" ; extends Modelica . Electrical .Analog. Interfaces . CUrrentSource (redeclare Madel lca . Block.s . Sources . ExpSine signalSource ( amplitUde_ {I} , freqHz-{ freqHz l. phase_ (phase). damping- (damping)l ) : end ExpSlneCUrrent ;
Modellca.Electrlcal.Analog.Sources.ExponentlalsCurrent
4
Risingand falling exponential currentsource
model ExponentialsCUrrent "Rising and falling exponential current ecureeparameter Real iMax- l f1 Uppe r bound for rising edge " ; parameter SI . Time riseTime (min -O) ~ 0 .5 "Rise time" j parameter 51 . Time riseTimeConst (min ..Modeli ca .Constants . SMALL) .. 0 .1 "Rise time constant" ; parameter 51 . Time fall TimeCcnst (min_Modelica. Constants .SM1\LL) - riseTimeConst "Fall time constant " ; extends Madellea. Electrical .Analog . Interfaces . CUrrentSource (redeclare Madelica. Blocks . Sources . Exponentials s ignalSource ( outMax- {iMax) I riseTime_{riseTirne) , riseTimeConst -{ riseT imeconst}, fallTime Conat-(fallTimeConst}I ) I end RxponentialsCurrent ;
Modellca.ElectrlcaI.Analog.Sources.PulaeCurrent
~ Pulsecurrentsource model PulseCUrrent "Pulse current source" parameter SI .Current 1.1 "Amplitude of pulse" ; parameter Real width ( final min-Modelica. Constants. SMALL, final max-lOO) - SO ·Width of pulse in , of period" l parame ter: SI . TiMe period{final min cMode l i ca .Con s t a n t s . SMALL) • 1 "T ime f or one period" ;
780 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica extends Mod el i c a . El e c t r i ca l . Ana l og. Interfaces . CurrentSource (redec l ar e Modellca . Blocks . Sources . Pulse s !gnalSource ( a mpli tude - I I) , widt h. I width). per Iod e (per i od))) , e nd Put s e Current ;
Modelica.Electrical.Analog.Sources.SawToothCurrent
...- EMax, the exp(x) function Is linearized": protected Real vbc s Real vbe ; Real qbk ; Real 100; Real t be ; Real cbc r Real cbe r Real ExMin; Real ExMax; Real Capcje ; Real Capcjc ;
function pow ·Just a helper function for x"'y" i npu t Rea l X ; input Real y ; o u t pu t Real z ; algorithm z : _ x"'y; end pow :
functi on pow "Just a helper function for x"'y· input Real x ; input Real Y i output Real z ; algorithm z : _ x "'y ; end pow ;
public Model ica . Electrical .Analog . Interfaces . Pin C "Collector" , Modelica . Electrical .Analog . Interfaces . Pin B "Sase"; Modelica . Electrical .Analog . Interfaces . Pi n E ·Emitter" ; equation ExMin • exp(EMinl ; ExMax =- exp (!Max) ; vbc = B.v - C.v: vbe = B.v - E.v; qbk - 1 - vbc*Vak; Ibc • if (vbc/Vt < EMinl then Is' (ExMin' (vbc/Vt EMin ... 1) ~ 1) .. vbc·Gbc else if (vbc/Vt > EMax) then Is" (ExMax· (vbc/Vt - EMax ... 1) - 1) .. vbc·Gbc else Is· (exp(vbclVt) - 1) ... vbc*Gbc; Ibe • if (vbe/Vt < EMin) then Is' IExHi n' (vbe/Vt EMin ... 1) - 1) .. vbe·Gbe else if (vbe/Vt > !Max ) then Is· (ExMax* (vhe/Vt - !Max ... 1) - 1) ... vbe*Gbe elae Is· texp(vbe/Vt) - 1) ... vbe·Gbe , Capcjc • if (vbc/Phic > 0) then Cjc'll , Mc'vbc/Phicl else Cj c'powll - vbc/Phic. -Mc) , Capcje - i f (vbe/Phie > 01 then Cje'll + Me'vbe/Phiel else Cje·powU - vbe/Phie, ~ M e ) 1 cbc .. if (vbc/Vt < lMin) then Taur·Is/Vt*ExMin· (vbc/Vt EMin + 1) + Capcjc else if lvbc/Vt > EMaxl then Taur·Js/Vt*ExMax* (vbc/Vt - BMax ... 1) .. Capcjc else Ta ur*Is/Vt·exp(vbc/Vt) ... eapejc ; cbe .. if (vbe/Vt < EMin) then Tauf*ls!Vt·ExHl n* (vbe/Vt EMin ... 1) ... Capcje else if (we/Vt > EMaxJ then Taut.Is!Vt*ExMax.(vbe/Vt - EMax ... 1)+ Capcje else Ta uf*ls /Vt·exp(vbe!Vt) ... Capeje : C . i .. (ibe - ibe) ·qbk - lbe/Dr - cbc*der (vbc) ... Ccs·der (C. v) 1 8.1 • the/Sf ... ibc/Br ... cbc·der(vbc) ... cbe*der(vbe} I E .1 .. -B .l ~ C.! ... Ccs*der(C .v) : end NPN;
public Modelica . Electrical .Analog . Interfaces . Pin C "Collector" ; Hodelica. Electrical.Analog . Interfaces . Pin 9 "Base" ; Modellca . Blectrical .Analog. Interfaces . Pin B "Emitter" ; equation ExM in • exp(EMin) ; ExMax • exp (EMax) ; vbc = C.v - a .v, vbe • E. v - B.V ; qbk = 1 • vbc*Vak j ibc • if (vbc/Vt < EMinl then Is' IExMin' (vbc/Vt EMin .. 1) - 1) + vbc*Gbc elee it (vbc/Vt > EMax) then Is· (ExMax* (vbc/Vt • EMax .. 1) - 1) .. vbc *Gbc else Is* (exp (vbc/Vt) - 1) .. vbc*Gbc, ibe • if (vbe/Vt < EMln) then Is' (ExMin' (vbe/Vt EMin .. 1) ~ 1) .. vbe*Gbe else it (vbe!Vt > &Max) then Is* (ExMax+ (vbe/Vt ~ EMax: + 1) • 1) + vbe*Gbe else Is'lexplvbe/Vt) - 11 + vbe'Gbe ; Cspcjc • it (vbc/Phic > 0) then Cjc' II + MC'vbc/Phic) else Cjc'powll - vbc/Phic . -Me); Capcje • it (vbe/Phie >- 0) then Cje. (1 + Me·vbe/Phie) else Cje'powll - vbe / Ph i e . - Me ); cbc • if (vbc/Vt < EMin) then Taur*ls/Vt*ExMin* (vbc/Vt EMin .. 1) .. Capcjc else i f (vbc/Vt > EMax) then Taur*ls / Vt*ExMax· (vbc/Vt - EMax .. 1) + Capcjc else Taur*ls/Vt·exp(vbc/Vt} + Capcjc ; cbe • if (vbe/Vt < EMin} then Tauf*ls/Vt*ExHin* (vbe/Vt EMin + 1) + Cap cje else if (vbe/Vt > £Max) then Tauf*Is!Vt*ExMax* (vbe/Vt - EMax .. 1) .. Capcje else Tauf· Is/Vt*exp (vbe/Vt) + Capcje; C . i • - « ibe - ibcl 'qbk - ibc/Br - cbc'der (vbc) Ccs*c1er(C .v) ) ; D. i • - (ibe /Df .. tbc/Dr .. cbe*der (vbe) + cbc*d.er (vbc») ; E.i • -9 .i - C.i .. Ccs*der(C .v) ; end PNP;
__r
parameter 51 .CUrrent Is...1 .e -16
"Transport saturat ion current " ; parameter SI . InversePotential Vak=O. 02 "Early voltage (inverse) I l/Volt ll ; parameter SI.Time T8Uf -O .12e -9 '·Ideal forward transit time" ; parameter SI. Time Taur...Se -9 "Ideal reverse t ransit time" ;
parameter 51 .Capacitance Ccs-le-12
Modellca.Electrlcal.Analog.Semlconductors.PNP
Appendix D-Modelica Standard Library Modelica.ElectricaI.Analog.Examples 783
Modelica.Electrical.Analog.Examples
...:.J
, ".·1~ ·
;,.
CauerFUler
ChuaCircuit
~~
. >iI)
DifferenceAmplilier NandGale
This packagecontains examplesfor the analog electricalpackages. • Chua's circuil Cauer filter • NAND gate Modellce.Electrlcel.Anelog.Exemples.CeuerFllter Cauer switchedcapacitor filter The exampleCauer filteris a low-pass filter of the fifth order. It is realizedusinga switched-capacitor network. The voltagesource V is the input voltage, and the CpS . p2 . v
is the filter output voltage. The pulse response is calculated. The simulationend time should be 2e5. Pleaseplot the output voltage OpS . p2 . v ,
model CauerFil ter "CAUER. Switched Ca paci tor Filt e r" import Modelica . Electri cal .Analog . Examples . Util i t ies; Modelica . Electrical .Analog . Sources . TrapezoidVolt5ge V( V.I , II!ltartTime_499. ris ing.!, wi d th.l S0 0. falling -I , period. 50000. nperiod.1) , Modelica . Electrical .Analog . Sources . Tr a pezoidVoltage elk i V-5, rlsing _s, width-s OO, fallin g _5, pe r I od e ro oo j , Model lca .Electri cal .Analog .Ba s l c . Cap ac itor c r rc-n . Modeli ca . El e c t r i c a l. Ana l og . BlIs i c . Ca p a c i t o r C2 {e . }. 55 ) ; Modell ca . El e c t r i c a l. Ana l og . Basic . Ca paci tor C3 IC-l . 521) ; Madel l e a . Bl e c t r i c a l. Analog . Basic . Ca pa c i t o r C4 (C-l) ; Madel lea . Elect ri cal .Analog. Bas i c . Ca p a c i t o r CS IC-l) ; Hodelica.. Electri cal .Analog . a a e f c . Ca pa c i t o r C6 (C- l . 0 18) ; Model ica.. Electr i c a l .Analog . Ba ste . Capa.c i t o r C7 (C- l) ; Modeliea . El e c t ric a l . Ana l og . Bas ic . Ca pa c i t o r C8 (C- l . 64 4) ; Modeliea .Elee tr i cal .Analog .Bas i c . Cap a c i t o r C9( C.2 ) ; Model l e a . Electr i cal .Analog . Bas i c . Ca p a c i t o r ctO (C. l ) ; Modeli ca. Elfllc t r i c al . Ana l og . 'Bas i c . Ca p a c i t o r Ci l ' C_ 2) ; Hode l ica . Electri cal .Analog. Bas i c . Ca pa c i t o r C12 (e -l) ; Modelica . Elec tr i c al .Analog . Bas i c . Cap a c i t o r C13 (C.9 . 862 ) ; Madeliea. . Electrical .Analog . Basic .Capa c i t o r C14 (C..7 . 23 ) ; Model lea . Electr ical .Analog . Basic . Capaci t o r CIS (C-I 0 . 06) Model ica . Elec tr ic al .Analog . Ba s i c . Cap aci t o r C16 (C. I 0 .:B ) Modeli ca . Ele c t rica l .Analog . Basic . Cap aci t o r C1 7 (C . 12 . 76 ) Hodel i ca . El e ct r i c al .Analog . Bas i c . Cap acitor C1 8 (C. 8 . 67 6 ) Utilit ies . Re a I S" i t c h 81 ; Utilities.Rea1Sw!tch 52, Utilities . Rea1 5witch 53, Utilit ies.ReaIS"itch 84 ; UtiUties .Rea15witch 5 5 ; Utilities .Rea15w!tch 56, Utilities .Re al5wl t ch S7 ; Utilities . Rea 15 wl t c h 58 ; Utilltles .RealSwitch S9; Utilities . RealSwltch S ID; Utilities .RealSwitch 511 ; Utilities .RealSwitch 812 ; Utili t ies . RealSwitch 513 ; Utilities . RealSwitch $14 ; Utilities .Rea15witch SIS ; Utilit ies . RealSw itch S16 ; Ut ilities . Real5witch S1 1 Ut ilities . Re a 15wi t c h 518 ; Hodelica.. Electri cal .Analog . Basic . VCV Op l (gain-30000) : Madeliea . El ectrical .Analog . Basi c . VCV Op2 (gain-300 00 ) ; Model ica . Elet:trical .Analog . a e s te . VCV Op3 (ga in _30000 ) , Madelica . Electrical .Analog . Basic . v ev Opt (gain-30000) , Madeli ca . Electrical .Analog .aeefe . VCV Op5 1941n=300 00) ; Madel i ca. Electrical .Analog . Ba s i c . Ground G: Modelica . Electrical .Analog . Basic . Ground H, equation connect (S l . nl, V. p ) ; connect IC8 . p , ct 8 . n} ; connect IC8 . p , S I1 . n l ); connect (C8 .p, 517 .nl ) ; conn e c t ICS . p , Ops . p 2 1 , connectlC1 .p , Cll . pl ; connec t{C2 .p , CI6 . n ); connect (C2 . p , 57 .nl } ; c onne ctlC2 . p , 5 13 .n1 ) ; connect IC2 . P . Op3 . p 2 ) , c onnec t (C6 . p , C14 . n ) , connect (e 6 . p , SI .n2); connect lC6 .p , 55 .nl ) ; connect (C6 . p , Opl . p 2) conn ect (C15 .n, S9.n 2 ) connect IClS ." , 53 . " 1) co nnect (CIS ." , Op2 . p2
connec t (C14 .p , C2 .nl : co nne c t IC14 . p , 5 2 . n 2) ; c onnect IC14 . p , 54 ."1) i c onnectlC14 . p , Opl. n ll ; c onn e c t (C1S . p , S 6 . n 2 ) , conn e c t (CI S. p, 58 .02 ) ; c onnect (C15 .p , Op2 .nl ) ; c o nne c t fe 16 . p , C6. n J ; conne c tlC16 . p , Ce . n) ; co nne ctIC16. p, StO .n2 ) : c onnect (C16 . p , OpJ . n l) ; c on nec tlC l ' . p , S12 .n l) ; connec t (CI1 . p , 5 14 . 01) : c onnectf C17 . p , Op4 . n U : c onnec t fC18 .p, CI l .n); connec t (C1 8 . p , 5 16 .nl ); c o nne ct (C18 . p , S1 8. nl l ; connec t fC18 . p , CpS . n U; co nnect(Cll . n , 51 5 . n 2 ) ; c onn e c t (Cl ' . n, S17 .n2 ) ; co nne c tfC11 . n , ssm i , co nn ec t (CI 7 .n , Op 4 . p 2 1 ; c on nec t (Cl .n , S2 .p ) ; co nn ec t (C3 .p , 53 .p ) ; conn ec t CC3 .n , 54 .p) ; c OllJlec t (C4. p , S5.p) ; connect lC4 . n , 5 6 . p); co nnect (CS . p, 5 7 . p ) ; c onne ct IC5 . n , s a . p ); c onnect IC7 . p, 5 9 . p) I c oanece tc 'r . n , s r u . p r , c onnect (C9 .p , Sll .p) ; c onne c tC C9.n , 5 12 . p l ; c onnect (Cl O.p , 5ll .pl ; co nn ec e tcm . n . S l4 . p l j co nne c t(Cl1 .p , 5 1S .p l ; c onnec tC Cl1 .n , SlG .pl ; c on ne:ct( C12 . p , S17 . p) ; connect( C12 . n, S I 8 .pl ; c onnect (Cl .p , S l . p ) ; connect (Sl . c ont r ol, Cl k . p l; co nnec tC S2 .cont r o l. Cl k . p) ; c onne c t Lsav c ont r or , Clk .p) ; conne ct t s e ccnt r ot , Cl k . p J : c onne ct (S S . c o nt r o l, Clk .p) ; c cnnec t (5 ' .c o nt r o l , Clk . p ) ; conne ct (S7 . cont r o l , Cl k . p ); c onnect (5 8 .cont rol , Cl k.p ) ; c onnec t (S9 . c on t r ol , Clk . p ) ; c onnec t (SI O. c ontrol , Cl k .p) c onnec t (Sll . e on t r o l, Cl k.p) cc nn ecc ts r z. e on e eer , Clk .p) co nn ect (5 13 . c ont r o l, Cl k . p) conne ct j s i ei coet r o j , Cl k . p) co nnect (S I S . c on cro l, Clk . p j conn ect (S 16 .cont ro l , Clk.p) c onnect (S 17 .control , Clk.p) c onnect (51 3 .cont r o l , Clk . p l c
c cnnec r tu . p , V . n) ;
connect (G .p , 5 3 . n2 ) ; connec t (G. p , 5 4 .n2 ) ; c onnec t (G.p , 5S . n2 ) I co nnect (G.p, S1 . n2) ; conne c tW . p . Sll.n2) ; c onnect (G.p , 512 . n 2 ) ; c o nne ct (G .p, 5 13 . n 2 ); c onnect (G.p , 5 14 . 0 2 1 ; c onnect (G.p , s r s . n 2 1 i c onn e c t (G . p, 518 . 02) ; c onn e c t( G. p , 52 . nl ) ; connec t lG . p , 56 .nl ) ; c onne ct (G.p , 58 .nl) , conn e c t (G.p , 5l0.r.l) ; c onnectCG .p , SIS .nl1 ; c onnect (M. p , Op l. p l) ; c onnectIM .p, Op2 . p l ) j connec t IM.p , Op3 . p l ) ; c onn ec t (H .p , Op4 . p 1 ) , connec t CM. p , CpS . p l ) I co nne ct (M. p, Op1. n 2 ): connect (M.p , Op2 . n 2 ) ; c onnect (M. p , Op3 . n 2 ) ; c onne ctlH .p , Op4 .n2) , connect (M.p , Op5 . n2 ) j connect (M. p , Cl k . o l ; e nd Caue r Fllte r ;
784 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Modellca.Electrical.Analog.Examples.ChuaClrcuit
Chua's circuit, ns, V, A ~.~1jfl
~:2S:m!::,J \~~;j
Chua's circuit is the simplest nonlinear circuitwhich sho.ws chaotic behavi?r. The c~reuit consists of linear basic elements(capacitors, resistor, conductor,
inductor), and one nonlinearelement,which is called Chua's diode. The chaotic behavior is simulated. The simulation end timeshould be set to 5e4. To get the chaotic behaviorpleaseplot ci , v. Choose C2. v as the independent variable. model ChuaCircuit "Chua's circuit , ne, V, Aft Modeli c a . Electrical .Analog . Basic . Inductor L(L =18); Model ica . Electrical .Analog . Basic . Re s i s t o r Ro (R.12 . se - 3) ; Modelica . Elect rical .Analog . Basic . Conductor GWaO . 565) ; Modelica . Eiect rical .Analog. Basic . Ca p a ci t o r Cl (C_IO, v ( s t a r t ",4 » ;
Modelica . Elect rical . Analog . Basic . Ca p a c i t o r C2 (e-lOO) : Model lea . Electr leal . Analog . Examples . Ut i l ities . Non linearRe sistor Nr ( Ga (min - -1) • -0 . 757576, Gblmin. -l) = -0 .409091,
Modelica.Electrical.Analog.Examples.DifferenceAmplifler
1
Modellca.Electrlcal.Analog.Examples,NandGate
CMOS NANDGate(see Tietze/Schenk, page 157) The nand gate is a basic CMOS buildingblock. It ~ consistsof four CMOS transistors. The output voltage Nand. y . v is low if and only if the two input voltagesat Nand. xl . v and Nand. x2 . v are both high. In this way the nand functionalityis realized. The simulationend time should be set to le-7. Pleaseplot the input voltagesNand.xl.v , d Nand.x2 .v, and the output voltage Nand. y. v. model NandGate
Ve.l) ;
Modelica. Electrical .Analog . Bas ic . Ground Gnd; e qu a t i o n connect (L .p , G.p), c onne c t (c .n, Nr .p) , c onnect (Nr .n, Gnd. p ), c o nnec t (C1. p, G . n ), connect (L .n , Ro .p) , connect (G.p, C2 .pl ; connect tcr . n, Gnd . p) ; connec t (C2 . n, Gnd .p) ; connect (Ro .n , Gnd .p) ; end ChuaCircuit ;
;i)W~:Jl\l.j
It is a simpleNPN transistoramplifiercireuit.The
""""-, ;~'9~::5iJ
voltagedifferencebetweenRl . p and R3 . n is amplified. The output signal is the voltage betweenR2 .nand
· l ,~.,. '..;NI 'J
c onne c t (Transistorl .b , CI.p); connect(Transistorl .c , C2 .p) ; connect (R2 . n , Transistorl . c) ; connect (Trans istorl .e , Il .p) ; connect (Transistor2 . b , R3 . p ) ; connect (Transistor2 . b , C3 . p) ; connect (C4 . n , Transistor2 .c l , connect (R4 .n, Transistor2 . c ) ; c o nn e c t (CS .p , Translstor2 .e) , end Differenc eAmplifier ;
R4 . n. In this examplethe voltageat Vl is amplifiedbecause R3 . n is grounded. The simulationend timeshould be set to le- 8. Please plot the input voltageVl .v, and the output voltages R2 .n . v, and R4 .n .v . mode l DifferenceAmplifier Modelica . Electrical .Analog . Sources . ExpSineVoltage VI ( V=O. 2, freqHz=O .2e9, damping-a .leB) ; Modelica . Electrical.Analog . Sources . Ra rnpVo l t a ge V2 (V-IS , duration=le-9) , Mode lica . Electrical.Analog . Sou r c e s . RampCurrent 11 (1 ..0 .16 , duration_le-9) , Modelica . Electrical .Analog . Basic . Re s i s t o r Rl (R-O . 000 1 ) ; Modelica . Electrical .Analog. Bas ic . Re s i s t o r R2 (R-IOO) ; Modelica . Electrical .Analog . Basic. Resistor R3 (R~O . 0001) ; Modelica . Electrical .Analog .Bas ic . Resistor R4 (R-I00); Modelica . Electrical .Analog . Ba s i c .Ca pa c i t o r CI (Cc le·lO) ; Model ica. Electrical .Analog . Basic . Ca pa c i t o r C4 (e. le-IO) ; Model i ca . Electrical .Analog . Basic . Capacitor CS (C.le-IO) ; Modelica . Electrical .Analog . Ba s i c . Ca p a c i t o r C2 (C.le-lO) ; Modelica . Electrical .Analog . Ba s i c . Ca pa ci t o r C3 (C-Ie ·l0) ; Modelica . Electrical .Analog . Ba s i c .Ground Gndl ; Modelica . Electrical .Analog . a e a f c . Ground Gnd9; Modelica . Electrical .Analog .Basic .Ground Gnd3; Modelica . Electrical .Analog . Basic . Gr ou nd Gnd2 ; Modelica . Electrical.Analog . Basic . Ground Gnd6 ; Modelica . Electrical .Analog . Ba s i c .Gr ound Gnd7 1 Modelica . Electrical .Analog . Ba s i c .Ground GodS ; Modeli ca . Electrical .Analog . Ba s i c .Ground GndS , Modelica . Electrical .Analog . Basic . Ground Gnd4 1 Modelica . Electrical .Analog . Examples . Ut i l i t i e s .Transistor Transistorl ; Modelica . Electrical .Analog . Examples . Utilities . Transistor Transistor2 ; equation connect(Vt .n , Gnd t . p ) , connect (CI .n, Gnd2 . p ); connect(l1.n, Gnd7 .p) ; connect (CS .n, GndS .p) ; connect (C3 . n , GndS . p ); connect (R) .n, Gnd4 .p), connect (C2 . n , Gnd3 .p) ; connect (C4 . p , Gnd6 . p ) ; connectU1.p, CS .p) , connect (Rt .p , VI .p) ; connect (R2 .p, V2 .p); connect (R4 .p , V2 . p ); connect{V2 .n, Gnd9 .p), c onne ct(R! .n , Transistor1.b) I
"CMOS NAND Gate (see Tietze/Schenk , page 157)"
Modeli ca . Electrical .Analog . Sources . TrapezoidVoltage VINI ( Vos3 .5, startTime_20e -9, ' rising-le-9 , w!dth-1ge-9 , falling osl .e~9 ,
period=40e ~9) ;
Modelica . Electrical .Analog. Sources . TrapezoidVoltage VIN2 ( V-3 . 5 , startTime=10e ~9. rising-le-9 , width-1ge~9, falling.l .e-9, period-40e -9) ; Model ica . Electrical. Analog . Sources . Ra rnpVo l t a ge VDD (V_5, duration=le-9) ; Modelica . Electrical .Analog . Basic . Ground Gndl ; Model i ca . Electrical .Analog . Sa s i c .Ground Gnd4 , Model ica . Electrical .Analog . neafc •Ground Gnd5 ; Modelica . Electrical .Analog . Examples . Utilities . Nand Nand ; equation connect (VDD .n, Gndl .p); connect (VIN1.n, Gnd4 .p) ; connect (VIN2 . n , GndS . p) ; connect (Na nd . Vdd, VDD .p) ; connect(VINI .p, Nand .xl}; ccnnecc tvma .p , Nand .x2) ; end NandGate ;
Modelica.Electrical.Analog.Examples. Utilities
:tNand
o
NonlinearReslstor RealSwitch
Transistor
This packagecontainsutilities. Modelica.Electrlcal.Analog.Examples.Utllitles.Nand
CMOS NAND Gate (see Tietze/Schenk, page 157) The nand gate is a basicCMOS buildingblock. It ~ \}J consistsof four CMOStransistors. ~~' ~ (~ t,:l-
. •
model Nand "CMOS NAND Gate (see Tietze/Schenk, page 157)" Modelica . Electrical .Analog . Semiconductors . PMOS TPl(W.. 6 .5e~6, L_3 .1e -6, Beta-1.0Se-5, ve --r, X2...0 .41, K5.0 .8385 , dW. -2.5e-6, dL.-2 .1e-6) ; Model lea . Electrical . Analog . Semiconductors . PMOS TP2(W_6 .Se ~6, L-3 .le -6, 8eta.1.0Se~S, Vt.~l , 1(2_0 .41 , K5.0 .8385 , dW.-2 .5e -6, dL. -2.1e-6) ; Modellca. Electrical .Analog . Se mi c onduc t o r s •NMOS TN1(W.6 .5e ·6, L"3 .le -6 , Beta-4 .le-5, Vt.O .8, 10 _1.144, K5.0.7 3ll, dIl. -2 .5e-6, dL.-l .5e -6) I Modelica. Electrical .Analog . Semiconductors . NMOS TN2(W..6 .Se ·6, L..3 .1e ·6, Seta-4 .le -S, Vt ..O.8 , K2.1 .144, XS.O .7311, dW.-2 . 5e - 6 , dL=·1 .5e~6) ; Modelica . El e c t r i c a l . Ana l og . a e a t c . Capacitor C4 (C-O . 4 e ~ 1 3 ) ; Modelica . Electrical .Analog . Basic . Ca pa c i t o r C7 (C_O. 4e-13) ; Modelica. Electrical .Analog . Ba s i c •Ground God ; Model lea . Electrical .Analog . Ba s l c . Ground Gnd2 ; Modellca. Electrical .Analog . Ba s l c . Ground Gnd3; Modellca . Electrical .Analog. Basic .Ground Gnd6 ; Modellca . Electrical :Analog . Basic . Ground Gnd? ; Modelled . El e c t r i c a l. Ana l og. Basic •Ground GndS ; Modelicd . El e c t r i c a l . Ana l og . Interfaces . Pin xl; Modelicd . Electrical .Analog . Interfaces . Pin x2 ; Modelica . Electrical.Analog . Interfaces . Pin Vdd ; Model ica. Electrical .Analog . Interlaces. Pin y ; equation
Appendix D-Modelica Standard Library Modelica.ElectricaI.Analog.Examples. Utilities 785 connectlnn.s, TN2.D ) , conn ec t lTN2. B, Gnd .p) , connect(TN2.0 , C7 .p) j c o n n ec t ( TN2. S, Gnd.p ) ;
connectlTPl.S, TNl .D) , c onne c t (TPl .G , TNt .G) ; connect (C4 . n , Gnd2 . p) j ecnnece t c 't . n. Gnd3 .p) :
connectITP2 .B. Gnd 6 .p l,
connect (TNt .B , Gnd7 . p r , connect(TP1 .B, Gnd8 .p)
~
connect (TP2 . 0, xl) ;
connect (TP2 .G, TN2 . G) ; connect (TNt .G, x2) ; connectCTP2 .S , rsi . o i . connect ('ml. 0 , C4 . p) ; connect tvdd , TPl.D) ; connect (TP2 .D, Vdd) ,
connect (C4 . p ,
y) ;
end Nand ;
Modelica.Electrical.Analog.Examples.Utllltles.Nonlinear· Resistor Chua's resistor model NonlinearResistor "Chua ' B resistor" extends Model ica . Electrical . Analog . I n t e r f aces . One Port ; parameter SI. Conductance Ga ; parameter 51 .Conductance Gbj parameter $1 . Voltage Ve l equation i ... if Iv < -ve) then Gb· (v + Vel • Ga· Ve else it (v ,. Vel then Gb' (v Ve l .. Ga'Ve else Ga'v ; end NonlinearResistor; ¥
Mode!lca.Electrlcal.Analog.Examples.Utllitles,RealSwltch
o
m odel RealSwitch Modelica . Electrical .Analog . Ideal . ControlledldealCOImlUtingSwitch S (level .2 . 5) ; odelica. Electrical .Analog . Ba s i c . Re s i s t o r R (R.O . 01) ; xcdet tea . Electrical .Analog . Interfaces . Pin p ; Modelica .l:lectrical .Analog . Interfaces . Pin nl ; Madeli ca . Electrical .Analog . Interfaces. Pin n2 ; rotodelica . Electrical .Analog . Interfaces . Pin co nt r o l ; equation connect (p, R .p); connect (R .n . S .p) ; connect (nl, S . nl) t connect (n2. 8 .n2); connect (control . S .con trol) ; end R.ealSwltch ;
Modellca .Electrlcal.Analog.Examples.Utilities.Translstor
model Transistor Model Ice , Electrical .Analog . Basic . Resistor rtb (:t.o . as) ; Modelica . Electrical.Analog. Basic . Resistor rtc (R=O . 1 ) ; Modelica .Electrlcal .Analog. Basic . Ca p a c i t o r ct (C.le~ 10) ; Modelica . Electrical.Analog •Semiconductors . NPN Tr (8t .SO . Dr-O .l , I8.1e ~16 . Vak.O.02 , Tauf.O .12e·9, Taur.Se-9. Ccs-le-12 , Cje.O .4e ~12, Cjc.O.5e ~12 , Phie".O .8, Me.O .C, Phic-O .8 , Mc.O .l33, Gbc.le-lS, Gbe.le~lS, Vt .. O.02S8S) ~ Madeliea . Electrical .Analog. BaBic . Ground Groundl; Modeliea . El e c t r i c a l . Ana l og. Interfaces . Pin c Mod.elica. Electrical .Analog . Interfaces . Pin b Modelica . Electrical .Analog . Interfaces . Pin e equation connect (rtb .n, Tr .B) ; connect (rtb .n, ct .p) ; connect (ct .n , Groundl .p) ; connect (Tr . C, rtc .p) ; connect (rtc .n , c ~ ; connect (b , rtb.p) ; connect {Tr .E, e) ;
786 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica directed out of the flange. A flange is describedby a Modeliea connector containing the following variables:
Modelica.Mechanics This packagecontains components to model mechanicalsystems. Currently the following subpackages are available: Rotational
I-dimensional rotational mechanicalcomponents.
Translational l-dimensional translational mech. components, Mullibody 3-dimensional mechanicalcomponents. The most up-to-date version of Ihis library with documentationis available at www.modelica.org. Copyright (C) 1999-2003, Modelica Association and DLR. Thi s Modelica package is free software; it can be redistributed
and/or modifiedunder the terms of the Modelica license, see the license conditions reproducedat the front pages of this book. Main Author: Martin Otter Deutsches Zentrum filr Luft und Raumfahrte.V. (DLR) Institut filr Robotik und Mechatronik Postfach 1\16 D-82230 Wessling Geooany email:
[email protected] Modelica.Mechanics.Translational This package contains components to model J-dimensional translational mechan ical systems. · ·a · ·~
SIidl~8SS
ElastoGlip
"b9x' Sk;
Position
R;j
Accele rate
~"
-cr-
s~
Dampe,
FIXed
-+, , Foree
®.
SpttngDamper
--$'-< AelaUveStates
The filled and non-filled green squares at the left and right side of a component represent mechanical flanges. Drawing a line between such squares means that the corresponding flanges are rigidly attached to each other. The componentsof this library can be usually connected together in an arbitrary way. E.g. it is possible to connect two springs or two sliding masses with inertiadirectly together. The only connection restriction is that the Coulomb friction elements (Stop) should be only connected together provided a compliant element, such as a spring, is in between. The reason is that otherwise the frictional force is not uniquelydefined if the elements are stuck at the same time instant (i.e., there does not exist a unique solution) and some simulationsystems may not be able to handle this situation, since this leads to a singularityduring simulation. It can only be resolved in a "clean way" by combining the two connected friction elements into one componentand resolving the ambiguity of the friclional force in the stuck mode. Another restriction arises if the hard stops in model Stop are used, i. e. the movementof the mass is limitedby a stop at smax or srnin. This requires the stales Stop.s and Stop.v . If these states are eliminated during the index reduction the model will not work. To avoid this any inertias should be connected via springs to the Stop element, other sliding masses, dampers or hydraulicchambers must be avoided. In the icon of every component an arrow is displayed in grey color. This arrow characterizes the coordinatesystem in which the vectors of the component are resolved. It is directed into the positive translational direction (in the mathematicalsense). In the flanges of a component, a coordinate system is rigidly attached to the flange. It is called flange frame and is directed in parallel 10 the component coordinate system. As a result, e.g., the positivecutforce of a "left" flange (flange_a) is directed into the flange, whereas the positive cut-force of a "right" flange (flange_b) is
SIunits .Poslt ion 8
"abs o l ut e posit i on of flange-;
flow Force f
"cut- f o rc e i n the flange ",
This packagecontains the followingmodel components: Interfaces Sublibrarycontaining interface definitions. Examples Examples of library usage. SlidingMass Translational component with inertia. Stop Sliding mass with Coulomb friction and hard stops. Rod Massless rod. Spring Linear spring. Damper Linear damper. SpringDamper Linearspring and linear damper in parallel connection. EIastoGap Linear spring and linear damper that can lift off. Position Drive a flange with a reference position given as input signal. Accelerate Drive a flange with an acceleration given as input signal. Move Drive a flange with a reference position, velocity and accelerationgiven as input signal. Fixed Fixed flange at a predefinedposition. Force External force defined as input signal. ForceSensor Ideal sensor to measure the force in a flange. PositionSensor Ideal sensor to measure absolute position of a flange. SpeedSensor Ideal sensor to measure absolute velocityof a flange. AccSensor Ideal sensor to measure absolute acceleration of a flange. This library is designed in a fully object oriented way in order that componentscan be connected together in every meaningful combination (e.g. direct connection of two springs or two shafts with inertia). As a consequence, most models lead 10 a system of differential-algebraic equations of index 3 (= constraint equations have to be differentiatedtwice in order to arrive at a slate space representation) and the Modelica translatoror the simulator has to cope with this system representation. According to our present knowledge, this requires that the Modelica translator is able to symbolically differentiate equations (otherwise it is e.g. not possible to provide consistent initial conditions; even if consistent initial conditions are present, most numerical DAE integrators can cope at most with index 2 DAEs). Main Author: Peter Beater UniversitatPaderborn, AbteilungSoest FachbereichMaschinenbaulAutomatisierungstechnik LilbeekerRing 2 D 59494 Soest Gennany email:
[email protected] Modellca.Mechanlcs.Translatlonal.lnterfaces
II --D'
Interfaces for ID translationalmechanicalcomponents
rwof_
f'-'-"-'-"-"l
L_.__..j
D Rigd
D
Com"'' ' '
Aange _b
ow-
~--;s.."
R "'£
D
Frk:tlonSu e
Modellca.Mechanlcs.Translatlonal.lnterfaces.Flange_a ID translationalflange (flange axis directed INTO cut plane, e.g., from left to right)
Appendix D-Modelica Standard Library Modelica.Mechanics.Translational 787 This is a flange for ID translational mechanical systems. In the cut planeof the flangea unit vectorn, called flangeaxis, is defined whichis directed INTOthe cut
•
plane, i.e., fromleft to right. All vectors in the cut planeare resolved with respectto this unit vector; e.g.• forcef characterizes a vectorwhichis directedin the direction of n with valueequal to f . Whenthis flange is connected to other I D translational flanges, this means that the axes vectors of the connected flanges are identical. The following variables are transported through thisconnector: 8: Absolute positionof the flangein [m]. A positivetranslation meansthat the flange is translated along the flange axis. f:
Cut-forcein direction of the flange axis in [N) .
connector Flange_a" (lett) lLl translational flange (flange axis directed INTO cut plane, e . g . from left to right)" 51 . Position s "absolute position of flange " ; flow 51 . Force t "cut force directed into flange "; end Flange_a;
Modelica.Mechanics.Translational.lnterfaces.Flange_b
D
This is a flange for ID translational mechanical systems. In the cUI planeof the flange a unit veelor n, called flangeaxis, is definedwhichis directed OUTOF the cut plane. All vectorsin the cut planeare resolved with respectto this unit vector. E.g. forcef characterizes a vectorwhichis directed in the directionof n with valueequalto f. Whenthis flangeis connectedto other ID translational flanges. this meansthat the axes vectors of the connected flanges are identical. The following variables are transported throughthisconnector: s: Absolute position of the flange in [m]. A posilivetranslation meansthat the flangeis translated along the flangeaxis. f: Cut-forcein direction of the flangeaxis in [N) . connector Flange b "10 rotational flange (non- filled square icon)" SI.Angle phi "Absolute rotation angle of flange" flow 51. Torque tau "CUt torque in the flange": end Flange_b ;
i
Modelica.Mechanics.Translational.lnterfaces.Rigld
Rigidconnection of two translational 1D flanges This is a ID translational component with two rigidly ,connected flanges. The distancebetween the leftand the right flangeis alwaysconstant, i.e.• L. The forces at the
O
right and left flangecan be different. It is used. e.g.• to built up sliding masses. t'artial model Rigid
"Rigid connection of two translational 10 flanges" 51 . Position s "abSOlute position ot center of component {s • flange_a.s + L/2 • flange_b ,B - L/2) " .: parameter 51 . Length L.O "length of component. from lett flange to right flange (. flange b .B - flange &.s)" ; Translational. Interfaces .F l a nge a flange a "(left) driving flange (flange axis d irected INTO cut plane, i. e . from left to right)"; TranslatIonal . Interlaces . Flange_b flange_b "(right) driven flange (flange axis directerJ Otrr OF cut plane , 1. e . from l'ight to left)" ;
equecIon flange_a .s • e flange_b .8 • S end Rigid ;
+
L/2 ; L/2 :
Modellca.Mechanlcs.Translatlonal.lnterfaces.Compllant
Compliant connection of two translational I D flanges
O
This is a 10 translational component with a compliant 'connection of two translational ID flanges whereinertial effectsbetweenthe two flanges are not included. The
absolutevalueof the forceat the left and the right flangeis the same, It is usedto build up springs, dampers etc. partial model Compliant "Compliant connection of two translational ::'0 flanges" Flange a flange a II (left) driving flange (flange axis directed INTO cut plane , e . g . from left to right) · , Flange b flange b "(right) dr iven flange (flange axis directed OUT OF cut plane ) " , 51 .Distance s r e j, "relati ve dIstance (. flange_b . 8 ~ flange_a . e)" , flow Sl.Force f "forcee between flanges (positive in direction at flange axis R,)" ; equation s reI .. flange b .s - flange_a.s ; flange b . f • f ;nange-a .f = - f ; end Comp! iant ;
Modellca.Mechanics.Tranalatlonal.lnterfaces.TwoFlanges
Component with two translational ID flanges ThiSis a ID translational component with two flanges. It " is used.e.g., to built up parts of a drive trainconsisting of severalbase components.
D
partial model TwoFlanges "Component with two translational 10 flanges n Translational .Interfaces . Flange_a flange_a "(left) dri Ving flange (flange axie directed Itfro cut plane . e . g. from lett to right) "; Translational . Interfaces . Flange_b tlange_b "(right) driven flange (flange axis directed OUT OF cut plane)" ; end TwoFlanges ;
Modellca .Mechanlcs.Translational.lnterfaces.AbsoluteSensor
Device to measure a singleabsoluteflange variable ~ This is the superclass of a ID translational component withone flangeand one outputsignal in order to measure an absolute kinematic quantityin the flangeand to provide the measured signal as outputsignal for furtherprocessing with the Modelica.Blocksblocks. partial model Absolute5ensor "Device to measure a single eeeotuee flange VAriable" extends Model ica . Icons . TranslationalSensor ; Flange 8 flange a "(left) flange to be m288ured (flange axis directed INTO cut plane, e. g . trom lett to right)"; end AbBol uteSensor ;
Modelica.Mechanlca.Translational.lnterfaces.RelativeSensor
Deviceto measure a singlerelativevariablebetween two flanges ~:)Th is is a superclass for 1D translational components with two rigidlyconnected flanges and one outputsignalin order to measurerelativekinematic quantities between the two flanges or the cut-forcein the flangeand to providethe measured signal as outputsignalfor furtherprocessing with the Modelica.Blocksblocks.
wr
partial model RelativeSensor "De v i c e to measure a single relative var iable between two flanges" extends Modelica. Icons . TranslationalSensorl Flange_a flange_a "(left) driving flange (flange axis directed INTO cut plane, e . g . from left to right)" ; Flange_b flange_b "(right) driven flange (flange ax is directed our OF cut plane) I I ; end RelativeSensor ;
788 Peter Fritzson Principles of Object-Oriented Modeling andSimulation with Modelica
D
Modellca.Mechanlcs.Translational.lnterfaces.FrlctlonBase
or s tartBackward) and v relfric < 0 and B > (omin + L/2) then Backward else Stuck) ; end FrictionBaoe ;
Base class of Coulomb friction elements. Modellca.Mechanlcs.TranslatlonaJ.SlldlngMass
part i al model Fr ictionBaae "Ba se cl ass of Coulomb fri ction elements" extends Interfaces . Ri g i d; parameter 51. Pos ition smax.2S "right Btop for (right end of) sliding mass" , parameter 51. Position smin.. -25 "left stop for Cleft end of) sliding mass" ; parameter 51 . Velocity v small.le-) " Re l a t ive ve locity near to zero (see model info text)" ;
I I Equ ati ons to defi.ne the f ollowIng va riables have 1/ to be defined in subclasses 51 . Velocity v_relIrle "Relative velocity between frict ional surfaces" ; SI .Acceleration a relfrle " Re l a t i v e acceleration between frictional surfaces· ; 51. Force f "'Friction force (positive. if directed in opposite direction of v reI)·; SI . Force fO "Friction force for v _O and forward 01 iding"; SI. Force fO max "Maximum friction force tor v -o and locked"; Boolean free "true, if frictional element is not active"; II Equations to detine the following variables are given II in this class Real 88 "Path parameter of friction characteristic t • f (4 relfric)" ; Boolean startForward "true, if v rel -O and start ot forward sliding or y reI > v smal1" ; Boolean etartBackward "t.r'ue , if y_rel -O and start of backward sliding or v reI < .y 8mall" ; Boolean locked- -true, it v rel .O and not Iliding" ; constant Integer Unknown_)-Value of mode is not known·, c o ns t a nt Integer Free.2 ·Element is not active · ; constant Integer Forward·! e v rei > 0 (forward eliding)· ; constant Integer StUCK,O "v rei. 0 (forward sliding, locked or backward sliding)", constant Integer Backward. ·l "v reI < 0 (backward sliding) " ; In teger mode ( final min_Backward , f inal max_Unknown, s t a r t . Unknown) , equation I- Friction c h a r a c t e r i s t i c (locked is introduced to help the Modelica translator determining the different structural contlgurations, if for each configuration special code shall be generated) -I s tartForward = pre (mode) •• Stuck and (sa" fO max and 8 < (smax • L/2) or pre (startForwardl and sa > to and 8 < (smu ~ L/2» or pre (mode) •• Backward and v relfric > v small or initialO and (v relfric >-0) ; BtartBackward ,. pre (mode) •• Stuck and (S8 < -t:O_max and s " (smin + L/2) or pre (startBackward) and sa < -to and s "
{smf n + L/2»
or pre (mode) •• Forward and v_relfric < .v_srnall or initial () and (v relfric < 0) I locked • not free and-not (pre (mode) •• Forward or startFoOiard or pre (mode) •• Backward or startBackward) ; a relfric • if locked then 0 "et ee if free then sa et se if startForward then sa • to elBe if startBackward then S8 + fO else if pre (mode) • • Forward then sa • fO else sa + fO ; I- Friction torque has to be defined in a subclass . Example for a clutch : f • it locked then sa else it tree then 0 else egeo·!n(it startForward then Hath .tempIntezpoll ( w_reltric, mueJOs, 2J else i t startBackward then .Hath . templnterpoll (.w_relfrie,mueJ'Os , 2) else it pre (mode) _. Forward then Hath . tempInterpoll (w reltrlc, mueJ'Os, 2J else ·Math . tempInterpoll (-",_reJtric, mueyos, 2J);
«t II finite s tate machine to determine configuration mode • if tree then Free elBe (if (pre (mode) •• Forward or pre (mode) Free or startForward) and v relfric " 0 and 8 < (smax - L/2) then Forward else it (pre (mode) •• Backward or pre(tI'lOde) • • Free
Sliding mass with inertia -" Sliding mass with inertia. withoutfriction and two rigidly connected flanges. The sliding mass has the length L; the position coordinate s is in the middle. Sign convention: A positive force at flange flange_a moves the sliding mass in the positive direction. A negative force at flange flange_a moves the sliding mass to the negative direction. model SlidingMa88 "Sliding mass with inertia" extends Interfaces . Rigid ; parameter SI .Mass m-t -mass of the sliding mass" ; SI . Velocity v "abs o l u t e ve l oc i t y of component"; SI .Acceleration a -ebecruee acceleration of component" ; equation v.der(s), a • der(v) ; m-a • flange B.f + flange_b .t ; end SlidingMass;
Modellca.Mechanlcs.Translatlonal.Stop Sliding mass with hard stop and Stribeck friction
-fa i n This element describes the Stribeckfriction _
characteristicsof a sliding mass, i.e., the frictionalforce
acting between the sliding mass and the support. Includedis a hard SlOP for the position. The surface is fixed and there is friction between sliding mass and surface. The frictional force f is given for positive velocity v by:
f= F_Coulomb + F-prop • v + F_Stribeck· exp ({exp • v) The distance between the left and the right connector is given by parameter L . The position of the center of gravity. coordinate s , is in the middle between the two flanges. There are hard stops at smax and srnin, i.e., if jlangca.s >= smin and jlange_b.s rop·v - F_Coulomb F_Stribeck·exp(- fexp*abs (v») ; 1/ Define events for hard stops and re initil iaze the 1/ state variables velocity v and posi tion e algorithm when (initial (» then a.ssert (8 )0 smin .. L/'Z o r s )0'" smin + L /2 and v >- 0, "Error in initialization of hard stop . (s - L /2) must be >- smin ") I alsert (s < smax ~ L/2 or a --Os. 2) else -Hoth .tempInterpoll (-wJelfrlc, mueJ'Os. 2) I
'/ // f lnite state machine to determine conUguration mode • it free then Free else (if (pre (mode) •• Forward or pre(mode) •• Free or startForward) and w relfrie )0 a then Forward else if (pre (mode) ••-Backward or pre (mode) • • Free or startBackward) and w reltr!c < 0 then Backward else Stuck) ; end FrictionBase ;
Modelica.Mechanlcs.Rotational.lnterfaces.AbsoluteSensor
Base class to measurea single absolute flangevariable _ ~~ This is the base class of a I D rotationalcomponentwith ~ one flangeand one output signal in order to measurean absolute kinematicquantity in the flangeand to providethe measuredsignal as output signal for furtherprocessingwith the blocks of package Modelica. Blocks . part ial model AbsoluteSensor "Base class to measure a single absolute flange variable" extends Modelica . Icons .no t.a t Ione t seneor i Flange_a flllnge_a "(left) flange to be measured (flange axis directed INTO cut plane)" , end Absol uteSensor ;
Modellca.Mechanics.Rotational.lnterfaces.RelatlveSensor
Base class to measurea single relative variablebetweentwo flanges This is a base class for ID rotationalcomponentswith two rigidlyconnected flangesand one output signal in order to measurerelativekinematicquantitiesbetween the two flanges or the cut-torquein the flangeand to provide the measured signal as output signal for funher processingwith the blocks of package Modelica . Blocks.
~
model RelativeSensor "Base class to measure a .lngle relative variable between two flanges" extends Madel lea . Icons . Ro t a t i ona ISe ns o r, Flange lJ flange a "'left) driving flange (flange axis directed IIn"O cut plane)" ; Flange_b tlange_b .. (right) driven flange (flange axis d irected OtTI' OF cut plane) "; end RelativeSensor;
Modellca.Mechanlcs.Rotatlonal.lnertla
ID-rotationalcomponentwith inertia • Rotational componentwith inertia and two rigidly connectedflanges.
~
model Inertia " l D~ rota t i on a l component with inertia" extends Interfaces. Rigid ; parameter 51. Inertia oJ.l "Moment of inert ia" ; SI .AngularVelocity w "Absolute angular velocity of component" , 5I.AngularAcceleration a "Absolute angular acceleration of component" , equation w . der lphl) , a • der (w) 1 J·a so flange_a . tau + flange_b . tau; end Inertia ;
Modellca.Mechanics.Rotational.ldeaIGear
Ideal gear without inertia This elementcharacterizes any type of gearbox which is fixed in the groundand which has one driving shaft and one driven shaft. The gear is ideal, i.e., it does not have inertia,elasticity,damping. or backlash. If these effects have to be considered,the gear has to be connected to other elements in an appropriateway.
4
model IdealGear "Ideal gear without inertia" extends Interfaces . TwoFlanges; parameter Real ratio.} "Transmission ratio lflange a.phi/flange b .phU equation - flange_a.phi .. ratio*flange_b .phi ; o • ratio· flange a .tau + flange b .tau; end IdealGear , -
"I
Modellca.Mechanlcs.Rotational.ldeaIPlanetary
Ideat planelarygear box ~~The IdealPlanelary gearbox is an ideal gear without
-==
inertia. elasticity.damping.or backlash consistingof an inner sun wheel,an outer ring wheel and a planet wheel locatedbetweensun and ring wheel. The bearing of the planet wheelshaft is fixedin the planet carrier. The componentcan be connectedto otherelementsat the sun. ring, and/or carrier flanges. It is not possibleto connectto the planet wheel. If inertia shall not be neglected. the sun. ring. and carrier inertias can be easily added by attachinginertias (= model Inertia) to the corresponding connectors. The inertiasof the planet wheelsare always neglected. The icon of the planetarygear signals that the sun and carrier flanges are on the left side and the ring flange is on the right side of the gearbox. However.this componentis generic and is valid independently of how the flangesare actually placed (e.g., sun wheel may be placed on the right side insteadof the left side in reality). The ideal planetarygearboxis uniquelydefined by the ratio of the number of ring teeth zr with respectto the number of sun teeth zs . For example,if there are 100ring teeth and 50 sun teeth, then ratio = zr/zs = 2. The numberof planet teeth zp has to fulfill the following relationship: zp := lzr - zs) / 2 Therefore, in the aboveexample zp = 25 is required. According 10 the overallconvention,the positivedirectionof all vectors.especiallythe absoluteangularvelocitiesand cut-torquesin the flanges,are along the axis vectordisptayed in the icon. model Ideal Planetary "Ideal planetary gear box· parameter Real rat io-laO/SO "numbe r of r ing teeth/sun teeth (e.g . ratio·lOO /50 ) "z 1/ kinematic relat10nshi p Interfaces . Flange a sun "sun flange (flange axis directed INTO cut plane)"; Interfaces . Flange_a carrier "carrier tlange (flange axis directed INTO cut plane)"; Interfaces . Flange bring "ring flange (flange axis directed Otrr OF cut plane) "; equation
Appendix D-Modelica Standard Library Modelica.Mechanics.Rotational 799 (l ..
ratio) ·ca rr ier .phi .. sun .phi .. rat i o-ring .ph i ; / / torque balance (no inertias ) ring .tau • ra tio·Bun .tau : c ar r i e r . tau • - 11 .. ratio) -sun. tau ; end IdealPlane tary ;
· Re l at i ve angular velocity be tween flange_b and flange_a l ' ; equation w r eI .. der (phi re I) ; tau . c· (phi_reI ~ phi_reIO ) + d·w_rel ; end Spr ingDamper;
Modelica.Mechanlcs.Rotatlonal.ldeaIGearR2T
Modelica.Mechanlcs.RotatlonaI.ElastoBacklash
Gearbox transfonning rotational into translational motion
Backlash connected in series to linear spring and damper (backlash is modeled with elasticity)
.,(;)
:';' This is an ideal mass- and inertialess gearbox which ~ transfonns a ID-rotational into a ID-translational motion. If elasticity, damping. or backlash has to be
considered. this ideal gearbox has to be connected with correspondingelements. model IdealGearR2T
·Gearbox transformi ng rotational int o t ra ns l at i o na l mot i on " parameter Real ratlott!nal unit. "rad /m") • 1 "traoBmIllston ratio (flange_a . ph i/flange_b . s ) "; Interfaces . Flange_a flange_a ; Model lea . Mechanics . Translationa) . Interfac es . Flange b flange b l equation flange_ll .phi .. rat io·flange_b .B ; o _ ratio·flange_8.tau ... flange _b .f ; end IdealGellrR2Tj
Modelica.Mechanlcs.Rotatlonal.Sprlng linear ID rotational spring ~ A linear ID rotational spring. The component can be
connected either between two inertias/gears to describe the shaft elasticity, or between an inertia/gear and the housing (component Fixed), to describe a coupling of the element with the housing via a spring. model Spring "Li ne a r 10 rota tional spr i ng " extends Interfaces . Compf l a nt ; parameter Real c (fi nal unit. ION . m/ r ad lO • ti na l min.O ) "Spring c ons t an t ", paramete r 51 .Angle ph i_relO ..O
.r!'h-. This element consists of a backlash element connected in -lffiJ ill" series to a spring and damperelement which are connected in parallel. The spring constant shall be nonzero, otherwise the component cannot be used. In combination with components IdealGear, the ElastoBacklash model can be used 10 model a gearbox with backlash, elasticity, and damping. model Elas t oBacklash '" Bac kl a s h c onnected in series t o 1 i ne &r spring and damper (backlash is modeled with elasticit y)" extends Interfaces.Compliant ; parame ter SI. Ang l e b (final min .. O) • 0 "To t a l bac klash"; parameter Real c ( final unit -"N .m/ r ad " , final min _Model I ee . Constants . SMALL) .. 1 . es "Spring co nstant (c > 0 required)" : pa rameter 51 .Angle phi relO .. O "Unstretched spring angle lt ; parameter Real d ( fina l uni t _"N.m. s / rad" , final min _O) • 0 ItDarnping constant "; SI .AngularVel oc ity w re I "Re l at ive angu la r velocity between flange_b and flange_a " ; pro tected S I. Ang l e b2.b/2 ,
I I A min imum backlash is defined i n order to avoid an II i nfi n i te number of state events i t backlash b i s set II t o ze ro . constan t 51 .Angle b mi n-l.e ·l0 "min I mum backlash "; equ at i on ",_ re I _ der (phI_rel) ; tau - if b2 > b_min then ( if phi_re I > b2 then c · (phi _re I • phi_rfl,I O
~
b:2)
of.
c1*",_rel
else (if phi reI < - b2 then c- (ph i reI - ph i rel O ... b 2 ) ... d· w ee r else OJ ) el se c· (phi rel- - phi reID) of. d ·w re I ; en d Elast oBack lash ; -
- ua eeeeeebee spring angle "; equa tion tau .. c- (ph i reI - ph i reIO ); end Spring ; -
Modelica.Mechanlcs.Rotational.BearlngFrlctlon
Modellca.Mechanics.RotationaI.Damper linear ID rotational damper
--m:-o linear. velocity-dependent damper element. It can be connected either between an inertia or gear and the
housing (component Fixed), or between two inertia/gear elements. model Pamper "Li ne a r 10 r otational damper " extends Interfaces . Compliant l parameter Rea l d (
e
Coulomb friction in bearings This element describes Coulomb friction in bearings, i.e., a frictional torque acting between a flange and the housing. The positive sliding friction torque "tau" has to be defined by table "tau_pos" as functionof the absolute angular velocity " w .
inertias/gears to describe the shaft elasticity and damping, or between an inertia/gear and the housing (component Fixed) to describe a coupling of the element with the housing via /I spring/damper.
Currently. only linear interpolationin the table is supported. Outside of the table, extrapolationthrough the last two table entries is used. It is assumed that the negative sliding friction force has the same characteristic with negative values. Friction is modeled in the following way: When the absolute angular velocity "w" is not zero, the friction torque is a function of w and of a constant normal force. This dependency is defmed via table tauJ'os and can be detennined by measurements,e.g. by driving the gear with constant velocity and measuring the needed motor torque (= friction torque). When the absolute angular velocitybecomes zero, the elements connected by the friction element become stuck, i.e., the absolute angle remains constant. In this phase the friction torque is calculated from a torque balance due to the requirement, that the absolute accelerationshall be zero. The elements begin to slide when the friction torqueexceeds a threshold value, called the maximum static frictiontorque, computed via:
model Spr i ngOamper
maxi mum s t atic fric ti on •
tinal unit ."N .m.s!rad ", tinal min.O) .. 0 '"Damping constant"; 51.AngularVelocity ",,_reI "Relativ6 angular v e l oc i t y between flange b and flange an : equation w r e I .. der (phi reI ) ;
tau.
d*w reI ; end Damper; -
Modellca.Mechanlcs.Rotational.SprlngDamper Linear ID rotational spring and damper in parallel
.r/Vl., A spring and damper element connected in parallel. The
Lm:J
component can be connected either between two
'"Linear 10 rotational spring and da mper I n parallel '" extend. I nterfaces . Compl i an t; paramet'!r Real c(linal unit. . m/rad tin al min-OJ ·Spring constant ": IIN
parameter 51 .Ang le phi relO.O ·Unstretched spring angl e II ;
paraaneter Real d ( final unit."N .m.s /rad". final min.O) .. 0 "Damping con stant ..; 5 1 . Angu l arVe l oc i t y ""_reI
ll
,
(peak , : 1 )
-
p~ak
• sliding fr i cti on ("'_0) -
This procedure is implementedin a "clean" way by state events and leads to continuous/discretesystems of equations if friction elements are dynamicallycoupled which have to be solved by appropriate numerical methods. The method is described in:
800 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica Otter, M., H. Elrnqvist, and S.E Maltsson (1999); HybridModeling in Modelica baud on the Synchronous DataFlowPrinciple, CACS0'99. Aug. 22-26, Hawaii. Moreprecise frictionmodelstake into accountthe elasticityof the materialwhen the twoelementsare "stuck". as well as other effects. like hysteresis. This has the advantagethat the friction elementcan be completelydescribedby a differential equation withoutevents. The drawbackis that the systembecomesstiff (about 10--20 timesslowersimulation)and that morematerial constants have to be supplied.whichrequires moresophisticated identification. For moredetails. see the following references, especially(Armstrongand Canudasde Wit 1996): Armstrong. B. (1991); Controlof Machines with Friction. Kluwer AcademicPress. BostonMA. Armstrong, B.. and C. Canudasde Wit (1996); Friction Modeling and Compensation. The ControlHandbook. editedby W.S. Levine. CRC Press.pp. 1369-1382. Canudasde Wit, c.. H. Olsson, K. J. Astroem, and P. Uschinsky (1995);A New Modelfor Controlof Systemswith Friction. IEEE Transactions on AutomaticControl. Vol.40, No.3, pp. 419-425. model BearingFriction "Coulomb friction in bearings ,. extends Interfaces . Rigid. ; parameter Real tau.J>OB l e • :).10, 1) If (w. tau) Positive slid ing friction characteristIc (w> .. O) II ; parameter Real peak(final min.. !) • 1 ·peak*t auJ>Os(1 ,2) .. Maximum friction torque for "'• • 0" , extends Interfaces . FrictionBase; 81 .AngularVeloclty w "Absolute angular velocity of flange_a and flange_b ll ; SI.AngularAcceleration a "Abs o l ut e angular accel erat ion ot tlange a and flange b-, equ ation II Constant auxiliary variables tauO • Math .tempInterpoll (0, tauJ>Os . 2): tauO max - peak·tauOi free-. talse ; I I A.ngul ar ve loc ity and angular Ac ce leration of f langes w • der {ph i) i a • der (w) i w relfric • Wi a-reUric • 11 : /7 Equilibrium of torques o • flange a .tau ... flange b .tau . tau , I I Fr icti on torque tau. if l ocked then Ba else Cit BtartFontard t hen Math.tempInterpoll (w. tau...,POs. 2) efee if startBackward then - Mat h. t empI nt e rpo l l{- w. tauJ>08 , 2) ease if pre{model •• Forward then Hath .tempInterpoll(w. t au'-poB, 2) etee - Math .tempInterpoll( -w , tauJ>Os, 2» ; end BearingFriction ,
Modellca.Mechanlcs.Rotatlonal.Clutch Clutch based on Coulombfriction This componentmodelsa clutch. i.e.• a component with ~ two flanges where frictionis presentbetweenthe two -, flangesand these flanges are pressedtogethervia a normal force.The normalforce fn has to be providedas input signal u in a normalized form. fn = fn_maxou. where fn_maxhas to be providedas parameter. Frictionin the clutchis modeled in the following way: When the relativeangularvelocityis not zero. the frictiontorqueis a function of the velocity-dependent friction coefficient mue(w_rel). of the normalforce "fn", and of a geometry constant "cgeo" which takes into accountthe geometryof the deviceand the assumptionson the frictiondistributions: frictional_torque = cgeo 0 mue(w_rel) 0 fn Typical values of coefficients of friction: dry operat ion mue = 0.2 " 0.4 operating in oil : mue = 0 .05 .. 0.1 When plates are pressed together. where r i is the inner radius. ro is the outer radius.and N is the numberof frictioninterfaces. the geometryconstantis calculatedin the following way under the assumption of a uniformrate of wear at the interfaces: cgeo = N°(rO + ri)/2
$
The positive part of the friction characteristic mue (w_rel). wJel >= 0, is defined via tablemueyos (first column = w_rel. second column = mue) . Currently. onlylinear interpolation in the tableis supported. Whenthe relativeangularvelocitybecomeszero. the elements connectedby the frictionelementbecomestuck, i.e.•the relative angle remainsconstant.In this phasethe frictiontorque is calculatedfroma torquebalancedue to the requirement that the relativeacceleration shall be zero.The elementsbegin to slide when the friction torqueexceedsa thresholdvalue.called the maximum static friction torque, computedvia: frictional t orque = peak 0 cgeo • mue(w rel=O) 0 fn (peak >= 1) This procedure is implemented in a "clean" way by state events and leads to continuous/discretesystemsof equations if friction elementsare dynamically coupled. The methodis describedin: Oller. M., H. Elmqvist, and S.E. Mattsson(1999); HybridModtling in Modelica basedon the Synchronous DataFlow Principle. CACSO'99. Aug. 22-26. Hawaii. Moreprecisefriction modelstake into accountthe elasticityof the material when the twoelementsare "stuck", as well as other effects. like hysteresis. This has the advantagethat the friction elementcan be completely describedby a differential equation withoutevents.The drawbackis that the systembecomesstiff (about 10--20 timesslowersimulation)and that morematerial constantshave to besupplied,which requiresmoresophisticated identification. For moredetails.see the following references. especially(Armstrong and Canudasde Wit 1996): Armstrong, B. (1991 ); Controlof Machines with Friction. Kluwer Academic Press,Boston.MA. Armstrong B., and C. Canudasde Wit (1996); Friction Modeling and Compensation, The Control Handbook. editedby W.S. Levine. CRC Press. pp. 1369-1382. Canudasde Wit. C; H. Olsson. KJ . Astroem, and P. Uschinsky (1995);A New Modelfor Controlof Systemswith Friction. IEEE Transactionson AutomaticControl. Vol.40. No.3. pp. 419-425. model Clutch -Clutch based on Coulomb fric tion extends Interfaces . Compl i ant , par ameter Rea l mue,J>Os ( : , : } . ( O. 0 .5] -(...,.mue) posit i ve slid ing friction coeffi c ient (w_reh·.O I - , parameter Real pealt(final min",l) • 1 -peak*mue-P08 (1 , 2] • maximum value of mue for w_rel •• O- , parameter Real cgeo (tinal min.O) ,. I -Geome t ry constant containing friction distribution assumption-, parameter 5 1. Force fn_ma.xUlnal min .O} • 1 "Maximum normal force- ; extends Interfaces . FrictlonBase; 5I .AngularVel ocity ",,_reI -Relative angular velocity (flange_b.w - flange_a .w)-, 8I .AngularAccel eratlon a_reI -Relative angular acceleration (flange b .a -flange a .al - , Real mueO - "Friction coefficient for ...,,,,0 and forward sliding", 5I .Force fo "Nannal force (tn-to max-f normalized)" 1 Modelica . Blocks . Interfaces .RealInput f:normalized "No rma l i zed force signal {. normal_force/tn_max ; clutch Is engaged if > Ol - ; equat ion II Constant auxiliary variable mueO • Modellca.Math .tempInterpoll (0 , mU8JXlB, 2) , // Relative quantities w reI • der (phi rel) , a-reI. der {w reI) ; v- relfric • w-reI , a-relfric • a-reI , 17 Normal torce and frict ion torque tor w_rel_O
tn • fn max·f normalized:
free. tn c. OJ tauO • mueO*cgeo·fn , tauO max • pe ak·t auOj II f rict ion torque tau • i f l oc ked then Sa else if free then 0 el se cgeo*fn· (if startForward then Model ica .Hath . tempInterpoll (v_ re l , mueJ>Os , 2) else if startBackward then ~Mode l i ca . Hath . t empI n t e rpol l { - w_re l r mue"'po8, 2J else if pre (mode) • • Forward then Hodelica .Math. tempInterpoll (v_rel , mue..,POs, 2) eree - Mode l ica . Mat h . t empl nt e rpo l l (-v_reI, mue"'po8, 21) end Clutch ,
J
Appendix D-Modelica Standard Library Modelica.Mechanics.Rotational 801 Modttllca.Mechanlcs.Rotatlonal.OneWayClutch
Seriesconnectionof freewheel and clutch ThiScomponent modelsa one-way clutch. i.e., a componentwith two flanges where frictionis present between the two flanges and these flanges are pressed togethervia a normal force. These flanges maybesliding with respect to each other, Parallel connectionof ClutchCombi and of FreeWheel. The element is introduced to resolvethe ambiguityof the constrainttorquesof the elements. A one-way-c1utch is an element wherea clutch is connectedin parallelto a free wheel. This specialelement is provided, because such a parallelconnectionintroduces an ambiguity into the model (the constrainttorquesare not uniquely definedwhen both elements are stuck)and this element resolves it by introducing one constraint torqueand not two. Note, initial valueshave to be chosen for the model, such that the relativespeed of the one -way-clutch >= o. Otherwise, the configuration is physicallynot possibleand an error occurs. The normal force fn has to be providedas inputsignal u in a normalized form, fn = fn max-u, where fn max has to be providedas parameter. Frictionin the clutch is modeled in the following way: When the relativeangularvelocityis positive, the frictiontorque is a functionof the velocity-dependentfriction coefficient mue(w_rel), of the normal force "fn", and of a geometryconstant "cgeo" which takesinto account the geometryof the device and the assumptions on the friction distributions: frictional_torque = cgeo * mue(w_rel ) + fn Typical valuesof coefficients of friction: dry operat i on mue 0 .2 . . 0 . 4
$
operating in o i l:
mue . 0.05 . . 0 . 1
When plates are pressed together, where r i is the inner radius, ro is the outer radius,and N is the numberof frictioninterfaces,the geometryconstantis calculated in the following wayunder the assumptionof a uniformrate of wear at the interfaces: cgeo = N* (rO + ri)/2 The positivepart of the frictioncharact erist ic mue(w rel) , w_rel >= 0, i's defined via table mue_pos (fir s t co l u';n w_rel, se cond column = mue). Currently, only Iin(;8J' interpolation in the tableis supported. When the relative angular velocity becomeszero. the elements connectedby the friction elementbecomestuck, i.e., the relative angle remainsconstant. In this phase the frictiontorqueis calculatedfrom a torquebalancedue to the requirement that the relativeacceleration shall be zero.The elementsbegin to slide when the frictiontorqueexceedsa threshold value,called the maximumstatic frictiontorque, computedvia: frictional_torque = peak + cgeo * mue(w_rel =OI * fn (peak >= 1) This procedureis implemented in a "clean" way by stale events and leads to continuous/discrete systemsof equations if friction elements are dynamically coupled. The methodis describedill: Otter, M., H. Elmqvist,and S.E. Mattsson (1999); HybridModeling in Modelica basedon theSynchronous DataFlowPrinciple, CACSD'99, Aug. 22-26, Hawaii. model OneWayCl utch ·Ser ies c onne c t ion o f freewheel and clutch" extends Interfaces . Compliant ; parameter Real mueyosl :. : ). (0 . 0 .51 "(w ,muel pos itive sliding friction coet:ficient (w rel>.O)" ; parameter Real peak (fInal min -1) :; 1 "peak.mueJ>Os U, 2) • maximum value ot: mue for w rel - -O" ; parameter Real cgeoCtinal min :O) • 1 "Geometry c onstant containing friction distribution assumpt i on" ; parameter SI .Force fo max(!lnal min.O) ., 1 "Max i mum normal force" : parameter 51 .AngularVelocity v_small (mi n . Model ica . Constants . e p s ) " I "Re l a tive a ngular ve loci ty ne a r t o zero (s ee model i n f o text)" ; 51 .Angul arVel oci t y w_ reI
"Relati ve angular ve l oc ity ( f l a nge b . w - flange a . w) " ; 5 1 . Angu l a r Ac c e l e r a ti o n a_reI " Re l a t I ve angular a c c e l e r a t i on (flange b .a - fla nge a .a ) " : 51. Fo rce fn " Norma l t orce (fn-tn f normal i zed) " : Boolean eta rtForward " t ru e , if ;; rel_O a nd start ot f orw ard sliding o r 101 ret > w em;ll " : Bool ean l ocked " t rue , If w rel:O and not sl id ing" ; Boolean stuck(final e ta rt ",fa l s e) · 101 rel _O (forward sliding o r l ocked)" 1 protected SI .Torque eeuo " Fr i c t i o n torque for w-o and slIding" ; 51 .Torque tauO_max "Maximum friction torque for w-O and l ocked" : Real mueO "Frict i on coe f f i c i e nt for W.. O and sl id ing ": Boolean f ree " t ru e, i f frictional element Is not act ive " ; Re al sa · p a t ~ pat:'ameter of tau f (a r el) Frict i on c ha r ac t eri s t i c ": co n s t a nt Real eps O_ l .Oe_4 "Re l a t i ve hysteresis epsil on " ; SI . To rque tauO max l ow " Lcwea t; va l u e l or tauO max" ; pa rameter Real- peak 2_max t Ipeek , 1 + epe c l j , publi c Hod el ica . Bl ocks . Interfa ces . Re a l Input t normalized " no nna l i ze d f orce input sIgnal (0 . . 1) " I equation " Co ns tant aux iliary variable mueO • Modelica .Math .tempInterpoll (0 , mue-.p09 , 2 ): tauO max l ow . epsOtmueO.cgeo'to max: I I Re l a tIve quantities -
max.
'C
",_reI . der(phl_rell;
a ret • der (101 ret) ; 17 Normal force a nd fri ction t orque for w_rel -0 free " f normalized < . 0 1 tn • it free then 0 else tn max" normalized ; tauO • mueO'cgeo' fn: t a uO_ma x " if free then tauO_max_low else peak2'ta uO; , . Frict i o n c ha r a cte ri s t i c (locke d i s introduced to help the Hodelica translat-::>r determining the different s truc t u ral configura tions , if for each con fi gu r ation spec i al code shall be g e ne r a t ed )
. /
star tForward • pre ( stuc k ) and (S!I > tauO max or pre (sta r t Fo rwa ro) and sa > tauO o r 101 reI ~ w small) o r initial () and (w_rel > 0) ; locked • pre (stuck) -and not startFoniard : / I ac ce lerat i on and fri c tion t orque a reI • 1 f locked then 0 else Boll ~ tauO ; t au .. it loc ked. then sa else (if free then 0 else cgeo'fn t Modelica . Ma t h . templnterpoll (w_rel , mueJ>0s, 2}) : I I Oetennine configuration s tuck • locked or w reI = 0, is defined via tablemueyos (first column =w, secondcolumn = mue). Currently, only linear interpolation in the table is supported. When the absoluteangular velocity becomeszero, the elements connectedby the frictionelementbecomestuck, i.e., the absolute angle remainsconstant. In this phasethe frictiontorque is
802 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica calculatedfrom a torque balancedue to the requirement that the absoluteaccelerationshall be zero. The elementsbegin to slide when the friction torqueexceeds a thresholdvalue. called the maximumstatic friction torque. computedvia: frictional_torque = peak' cgeo • mue(w=O) • fn (peak >= 1) This procedureis implementedin a "clean" way by state events and leads 10 continuous/discrete systems of equationsif friction elementsare dynamicallycoupled. The methodis describedin: Otter. M., H. Elmqvist,and S.E. Mattsson(1999); HybridModeling in Modelicabasedon the Synchronous Data FlowPrinciple, CACSD'99,Aug. 22-26. Hawaii. More precise friction models lake into account the elasticityof the materialwhen the two elements are "stuck". as well as other effects. like hysteresis. This has the advantagethat the friction element can be completelydescribedby a differentialequation withoutevents. The drawbackis that the system becomesstiff (about 10-20 times slower simulation)and that more material constants have to be supplied, which requiresmoresophisticated identification. For more details, see the followingreferences. especially (Armstrong and Canudasde Wit 1996): Armstrong, B. (1991); Controlof Machines with Friction. K1uwer Academic Press, Boston. MA. Armstrong, B.•and C. Canudasde Wit (1996); Friction Modeling and Compensation, The Control Handbook. edited by W.S.Levine. CRC Press, pp. 1369-1382. Canudas de Wit, C.• H. Olsson. KJ . Astroem,and P. Lischinsky (1995); A new modelfor controlof systemswithfriction. IEEE Transactions on AutomaticControl. Vol. 40. No.3. pp. 419-425. roodel Brake ·Brake based on COulomb friction • extends In terfaces. Rigid ; parameter Real mueJ>Os{: , :) -(0. 0.5) "(w,mueJ positive elid ing friction coefficient (w rel >_O) ",
parameter Real peakCtinal min.I) ;- 1 "pe ak· mue,J>Os [l , 2 ) 2 maxinnJm value of mue for w_rel.-O"; parameter Real cgeo(final min.O) • 1 "Geometry constant containing friction distribution assumption" , parameter 51.Force fn max(final min.O) • 1 "Maximum normal force· , ex tend s Interfaces . FrictionBase; SI .Angul arVelocity W "Absolute angular velocity of flange a and flange b"; SI .AngularAcceleration a "Absolute angular acceleration of flange a and flange b"; Real rnueO "Friction coefficient for "'.0 and forward slid ing" ; 51 . Force fn "Normal force (.tn max-r: normalized)"; // Constant auxiliary variable Modelica . Blocks. Interfaces . Re al l nput r: normalized It Normal i ze d force signal (. normal force/tn max, brake is active if " D)" , - equation mueO • Hodelica .Math .tempInterpoll (0, mueJ>Os, 2); // Angular velocity and angular acceleration of flanges II flange_a and flange_b w • der(phi) , a • der(w); w relfric • W; a-relfric " a; /7 Torque equilibrium, normal force and friction torque II for w re1-0 o • flange a.tau + flange b .tau - tau ; fn • tn rna;·f normalized; t auD ... roeO*cgeo*fn ; tauO max • peak*tauO; free-. fn Os, 2) else if startBackward then -Hodelica .Hath . templnterpollC -w, rrrueJ>Os, 2) else if pre (mode) 'C: Forward t he n Model ica .Math .templnterpoll (w, mueJX>s, 2) else · Hode li c a . Hat h. t e mpI nt e rpo l l (-w, mueJ>OB, 2}) I end Brake,
Modelica.Mechanlcs.Rotatlonal.GearEfficlency Efficiencyof a gearbox
~J This componentconsistsof two rigidlyconnected flanges
Tl
flange_a and flange_b withoutinertia wherean efficency coefficienteta reducesthe driven torqueas function of the driving torque dependingon the directionof the energy now. i.e.• energy is always lost. This can be seen as a simple modelof the Coulombfrictionacting between the teeth of a gearbox. Note that most gearbox manufacturers provide tables of the efficiencyof a gearboxas function of the angular velocity (efficiencybecomeszero, if the angular velocityis zero). However. such a table is practicallyuseless for simulationpurposes.because in gearboxes alwaystwo types of friction are present: (I) friction in the bearings and (2) frictionbetween the teeth of the gear. (1) leads to a velocity-dependent, additiveloss-torque,whereas (2) leads to a torque-dependent reductionof the driving torque. The gearbox manufacturers measureboth effects togetherand determine the gear efficiencyfrom it. althoughfor simulationpurposes the two effects need to be separated. Assume.for example. that only constant bearing friction, i.e.• bearingTorque=const .• is present.l.e.• (I) loadTorque = motorTorque sign(w)'bearingTorque Gearboxmanufacturers use the loss-formula
(2) loadTorque = eta'motorTorque Comparing(I) and (2) gives a formula for the efficiencyeta: eta • U . sign (w) ·bearingTorque/motorTorque)
When the motorTorque becomes smaller than the bearing'Iorque, (2) is useless. because the efficiencyis zero. To summarize. be
careful to determinethe gear efficiency of this element from tables of the gear manufacturers. model GearEfficlency "Ef fi c i e ncy of a gearbox· extends Interfaces .Rigid , parameter Real e t a ( mi n=Mode l1 c a . COns t ant s . 5MALL, max.I) • 1 "Efficiency" I 51 . Power power_a "Ene rgy flowing into flange_, (. power) ", Boolean driving_a "Tru e, if energy is flowing nrro And not out of flange flAnge a" ; equation power a - flange 4 . tau*der(phi}: driving a • po we; a ,.. 0 : flange ii .tau ., ·Clf driVing_a then eta·flange_a.tau else flange_4 . tau/eta) , end GearEfficiency;
Modellca.Mechanlcs.RotatlonBI.Gear Realistic modelof a gearbox ~ This componentmodels the essentialeffects of a gearbox. in particulargear efficiencydue to friction betweenthe teeth. bearingfriction. gear elasticity, and damping, backlash. The inertiaof the gear wheels is not modeled. If necessary. inertia has to be taken into account by connecting componentsof model Inertia to the left and/or the right flange.
JII[
model Gear "Realistic model of a gearbox" extends Interf aces. TwoFlanges; parameter Real ratio.! "transmission ratio (flange_a .phi/flange_b .phi) It , parameter Real eta ( min =Model tce . Constants . SMALL, max.I) • 1 "Gear efficiency" ; parameter Real frictionJ>Os[ : , :1-(0, 1) "(w, tau) positive sliding friction Characteristic (",,..0)" ; parameter Real peak. (final min..l) _ 1 "pe ak*f r i c t i o nJ>Os (I, I ) • maximum friction torque at zero velocity" ; parameter Real c ( final unit-"N.m/rad", tinal min ..Modelica . Cons t ant s . SMALL) • 1. e5 "Gear elasticity (spring constant) "; parameter Real d ( final unit -"N .m.s/rad", final alin.O) • 0 "( r e l at i v e ) gear damping" I parameter SI .Angle b(final min_OJ • 0 "Total backlash" ; Madelic! . Mechanics . Ro t at i o na l. IdealGear gearRatio(final ratio.ratio) ; Modelic4 .Me c hani c s. Rotational .GearEfficiency gearEtficiency(f inal eta"eta) I Hodelica .Me c han i c s . Rotational . BearingFriction
Appendix D-Modelica Standard Library Modelica.Mechanics.Rotational 803 bearingFriction (final tau,JlO•• frictionJlo., final
peekepeakj r
Modelica .Me chani c s. Rotational. ElastoBacklash elastoBacklash (
final b.b ,
Modellca.Mechanlcs.Rotatlonal.Accelerate Forcedmovement of a flangeaccordingto an acceleration signal ...
final c-c ,
..L
.-
final phi retuen . final dod): equation connect {gearRatio. flange_b, gearEt! iciency. flange_b.} ;
connect (gearEft iciency. flange_b , bearingFriction.flange a) ; connect (bearingFriceion . flange b , elastoBacklash . flange a); connect(elastoBacklash .flange b , flange bl r connect(gearRatio .tlange a, flange a) i end Gear ; - -
Modellca.Mechanlcs.Rotatlonal.Posltlon Forced movementof a flangeaccordingto a referenceangle signal ,The input signal angle defines the reference angle phi_ref (t) in [rad]. Range flange_b isforced to moveaccordingto this reference motion. Accordingto parameterexact(default =false), this is done in the followingway: 1, exactetrue The referenceangle is treated exactly. This is possibleonly, if the input signal is definedby an analytical function, whichcan he differentiated at least twice. If this prerequisite is fulfilled, the Modelicatranslatorwill differentiate the inputsignal twice in order to compute the referenceacceleration of the flange. ...
..L
.-
2. exactefalse
The referenceangle is filtered and the secondderivative of the filteredcurve is used to computethe referenceacceleration of the flange. This secondderivativeis not computedby numerical differentiation but by an appropriaterealization of the filter. For filtering, a second-orderBesselfilteris used. The critical frequency (also called cut-off frequency) of the filter is defined via parameter Lcrit in [Hz) . This valueshould be selectedin such a way that it is higher than the essential low frequencies in the signal. The input signal can be providedfromone of the signal-generator blocks of the block libraryModelica . Blocks .Sources . model Position "Forced movement of a flange according to a reference angle signal " parameter Boolean exact -false "true/false exact treatment/liltering the input sIgnal" # parameter SI . Frequency f_erit _SO "if exact-talse , critical frequency of filter to filter input signal"; output 81 . .Angle phi ref "reference angle defined with the input signal"; output 81 .Angle phi "abSOlute rotation angle of flange flange b ", output 81.AngularVelocity w "absolute angular velocity of flange flange_b" ; output 81 .AngularAcceieration a "absolute angUlar acceleration of flange flange_hI!; protected parameter Real W c1;it_2-Modelica . Cons t ant s . pi· f erit "critical freqUency in (1/s) "; constant Real at-t .361 7 "s coetficient of Bessel tilter"; ccnetene Real br.O . 6180 "OlioS coefficient of Bessel filter ";
public
Interfaces . Flange b flange b , Modelica . Block.s. Interfaces-:-Reallnput angle "Flange angle as input sIgnal I' ; equation phi ref - angle ;
phi-. flange_b.phi: w • dsr (phi) : a • der(w) j 1 f exact then
phi • phi_ref :
else
I I Filter. a • phiJet/ll + (af/w_crit)+. + /I (bt/w crit'2)+.'2) a • I(phlJef - phi) +w_crit at+w)+(w_crit/bf) :
end if; initIa l equation if not exact then
phi • phi ref:
end if;
end Position ;
-
.The inputsignal accelerat ion definesan angular acceleration a in [radls2]. Range flange_.b is forced to move with this acceleration. The angular
velocitywand the rotationangle phi of the flangeare automatically determined by integrationof the acceleration. The input signal can be providedfromone of the signalgeneratorblocks of the block libraryModel ica . Blocks .Sources. model Accelerate "Forced movement of a flange according to an acceleration signal" parameter 51 .Angle phi start .. O "Start angle": parameter SI.AngularVelocity w_start ...O "Start angular velocity"; 51 .Angle phi (final start-phi start, tina I fixed -true) "absolute rotation angle of flange flange_b"; 51 .AngularVelocity \II (final start.w_start . tinal fixed -true) "absolute angular velocity of flange flange_b" ; SI .AngularAcceleration a "absolute angUlar acceleration of flange flange_b" ; Interfaces . Flange b flange b, Modelica . Bl o c ks. Interfaces-:-RealInput eccet erae Ion "Angular acceleration as input signal" : equation
phi. nange_b.phi: der 19hi) :
w •
a .. der(w) ; a • acceleration ; end Accelerate :
Modellca.Mechanlcs.Rotatlonal.Move Forced movement of a flangeaccording to an angle, speed, and angularacceleration signal ~Range I
flang,,_b isforced to movewith a predefined motionaccordingto the input signals:
u (11: angle of flange u [2) : angular velocityof flange u [3) : angularacceleration of flange The user has to guarantee that the inputsignals are consistentwith each other, i.e., that u [2 J is the derivativeof u [1} and that u (3 J is the derivativeof u 12) . There are. however, also applications where on purposetheseconditions do not hold. For example,if only the position-dependent termsof a mechanical systemshall be calculated.one may provideangle = angle(t)and set the angular velocityand the angularacceleration to zero. The input signalscan be providedfromone of the signal-generator blocks of the block libraryModelica . Blocks .Sources. Note, this modelutilizesthe nonstandard function constrain(..) and assumesthat this function is supportedby the Modelicatranslator: Real rId, rd l r l , rddld : r
rd c . . . rdd • . . . constrain t r , rd . rdd) ,
where r, rd and rdd are variables whichneed to be computed somewhereelse. A simple implementation of const rain () is: r = 0;
However, this implementation requires that r (t ) is given as analytical, smoothfunctionin order that it can be differentiated and it does not allow applications such as the one sketched above. Functionconstrain () is used to explicitlyinformthe Modelica translatorthat rd is the derivativeof rand rdd is the derivativeof rd and that all derivatives need to be identicalto zero.The Modelicatranslatorcan utilizethis information to use rd and rdd wheneverthe Pantelides algorithmrequiresto compute the derivativesof r (and takes rd and rdd insteadof actually differentiating r) . model Move "Forced movement of a flange according to an angle, speed and angular acceleration signal" SI .Angle phi "absolute rotation angle of flange flange_b": sr .AngularVelocity w "absolute angular velocity ot flange flange_b ll ;
804 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica SI .AngularAcceleration a "absolute angular acceleration of flange flange_b" ; Interfaces . Fl ange_b flange_bi Modelica . Blocks . Interfaces . Real Input u (31 ; protected Real constraintResldue ;
Re al constralntResidue d; Real constraintRes idue- dd; equation phi . flange_b .phi ; .. . der(phi) I a = der(w) ; constraintResldue • u(l) - phi l constralntResidue d ~ u(2) - W; constraintResldue-dd .. u(3} . a ; constrain (constraIntResidue, constralntResldue d, c onstralntResidue_dd) ; end Move;
Modelica.Mechanlcs.Rotatlonal.Flxed
Flangefixedin housingat a given angle ~ The flange of a ID rotational mechanical systemis fixed at an anglephiO in the housing. Maybe used to connecta compliant element. such as a springor a damper, between an inertiaor gearboxcomponent and the housing; to fix a rigidelement,such as an inertia, witha specificangleto the housing. model Fixed -Flange fixed in housing at a given angle" parameter SI .Angle phiO-O "Fixed offset angle of housing" ; Interfaces . Flange_b flangf!_b _ (right) flange fixed in hous ing" ; equat ion flange b .phi • phiO , end Fixed;
Modellca.Mechanlcs.Rotatlonal.Torque
Inputsignal acting as externaltorqueon a flange ~ ~ The input signal torque defines an external torquetau tau in [Nm) whichacts (withnegative sign)at a flange connector, i.e., the component connected to this flange is drivenby torque tau. The inputsignalcan be provided fromone of the signal-generator blocksof Modelica .Blocks. Sources. model Torque "Input signal acting as external torque on a
flange-
w ret = der (phi reI) : a-rei .. der (w reI); flange a .tau -; 0 : flange-b . t au • 0; end Relat"tveStates ;
Model1ca.Mechanlcs.Rotatlonal.Sensors
1\7
TorqueSensor
~.
ReIAn~~;or
~
AngleSensor
SpeedSensor
AccSensor
~ ReIAc:fe'';;;~r
Model1ca.Mechanlcs.Rotatlonal.Sensors.TorqueSensor
Idealsensor to measure the torquebetweentwo flanges (= flange_a . tau) Measures the cut-torque between twoflanges in an ideal wayand provides the resultas outputsignaly = tau flange_a . tau (to be furtherprocessed withblocks of the Modelica . Blocks library).
~
model TorqueSensor
"Ideal sensor to measure the torque between two f l ang e s (. flange a .tau)" extends Modelica . Icons. RotationalSensor ; 81 . Torque tau "Torque in flange flange a and flange b ( .. flange a .tau • ~ f l ange ii .tau)" ; Interfaces.Flange a flange a i Interfaces . Flange-b flange -bi Modelica .Blocks . Interfaces-:-Re al OUt put Yi equation flange a .phi .. flange b .phi ; flange-a .tau ., tau ; flange:b.tau • -tau ; tau .. y ; end TorqueSensor;
Model1ca.Mechanlcs.Rotatlonal.Sensors.AngleSensor
Idealsensorto measure the absoluteflangeangle _ ~ _ Measures the absolute anglephi of a flangein an ideal ~ wayand provides the result as outputsignal y (to be furtherprocessed with blocksof Modelica. Blocks .
"'Torque (8 posi tive val ue accelerates the flange)" , Model Ice . Blocks . Inter faces. Real Input torque "Connector of input signal used as torque II ; Interfaces .Flange b flange b "(Right) flange" , equation tau .. torque : flange_b . tau '" - t au; end Torque;
model AngleSensor • Ideal sensor to measure the absolute flange angle" extends Interfaces .AbsoluteSensor ; Modelica . Blocks . Interfaces . RealOutput phi "Abs o l ut e angle of flange ll ; equation phi • flange a . phi ; o .. flange_a -:-tau : end AngleSensor;
Modellca.Mechanlcs.Rotational.RelativeStates
Modellca.Mechanlcs.Rotatlonal.Sensors.SpeedSensor
Definition of relativestate variables ~},-a Usually. the absoluteangleand the absoluteangular .r velocityof
Idealsensorto measure the absoluteflangeangularvelocity _~ _ Measures the absolute angular velocity w of a flangein ~ an idealwayand provides the resultas outputsignaly (to be furtherprocessed withblocksof the Modelica . Blocks library).
S I . Torque tau
Modelica .Mechanics . Rot at i onal . Inertia models are usedas state variables. In somecircumstances, relative quantities are better suited,e.g.•becauseit maybe easierto supplyinitial values. In such cases. model RelativeStates allows the definition of state variables in the following way: Connectan instanceof this modelbetween two flangeconnectors. The relative rotation angle and the relative angular velocity between the twoconnectors are used as statevariables. model Relative5tates "Definition of relative state variables" extends Modelica . Me c han i c s . Rotational . Interfaces . TwoFlanges, 51 .Angle phi_reI (fixed.true) "relative rotation angle used 8S state variable" ; SI .AngularVelocity w_rel (fixed_true) IIrelatl ve angular ve locity used a8 state variable"' , 5I .AngularAcceleration a_reI "relative angular acceleration'll ; equation ph i_reI . flange_b .phi - flange_a .phi;
model SpeedSensor • Ideal sensor to measure the absolute flange angular velocity· model SpeedSensor 'II Ideal sensor to measure the absolute flange angular velocity" ex tends Interfaces .Abs o l ut e Se ns o r: Model iea. Blocks . Interfaces . RealOutput w ·Absolute angular velocity of flange ": equation w - der(flange a .phi); o .. flange_a . tau; end SpeedSensor ;
Appendix D-Modelica Standard Library Modelica.Mechanics.Rotational 805 Modellca.Mechanlcs.Rotational.Sensors.AccSensor
Modelica.Mechanlcs.Rotatlonal.Examples
Ideal sensor to measure the absolute flange angular acceleration
This package contains example models First Friction CoupledClutches
--I5'f:>.. _ Measures the absolute angular acceleration a of a ~
flange in an ideal way and provides the result as output signal (to be further processed with blocks of the Modelica . Blocks library).
model AccSensor "I de a l ee neor to measure t he abeotu-e flange angular accelera t ion " extends Interfaces . AbsoluteSensor ; Madellea . Block.s . Interfaces . RealOUtput a "Absolute angular acceleration o f flange "; 8J . Angu l a rVe l oc i t y W "Abs o l ut e ang ula r velocity of flange "; equation w • derlflange a .phi) ,
a •
der(w)
o•
flange a .tau ;
i
-
end AccSensor;
Modellca.Mechanlcs.Rotatlonal.Sensors.ReIAngleSensor Ideal sensor to measure the relative angle between two flanges
~
Measures the relative angle phi_reI between two flanges in an ideal way and provides the result as output .... _ 0, "Connector frame_a of joInt ob ject is not as s e rt (c ord i na l i t y (f rame b) > 0 , "Cunnector frame b of joInt object is not end partialElementaryJolnt;
frames + is
connected") ; connecuedv j ,
Modelica.Mechanlcs.MultIBody.lnterlaces.PartleIForce
h All 3-dimensional forceand torqueelementsshouldbe It' basedon this superclass. This modeldefinesframe_a and frameb, computes the relativetranslation and rotationbetweenthe two frames and calculates the cut-force and cut-torque at frame_b by a forceand torque balancefrom the cut-forceand cut-torqueat frame_a. Asa result,in a subclass, only the relationship betweenthe cut-force and cut-torque at frame_a has to be definedas a function of the following relativequantities: r reI a(3) : Position vector from origin of frame a to origin of frame_b , resolved in frame_a Relative orientation object to from frame_b to frame_a par t ial model Part ialFor.ce "Superclasa of f orce elements " import SI "" Modellca .SlwlitB ;
808 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica Interfaces. Frame a frame a; Interfaces. Frame -b frame-b; 5I.Position r rel a(3) "Position vector from origin of frame_a to origin of frame b, resolved in frame a"; Frames .Orientation R reI "Relative orientation object to rotate from frame_b to frame_a" ; protected outer MultiBody. World world; equation assert (cardinality(frame a) > 0, "Connector frame a of force object is not connected"); assert (cardinality (frame_b) > 0, "Connector frame_b of force object is not connected"); /* Determine relative position and relative orientation between frame_a and frame_b
°-
*/
r reI a = Frames.resolve2 (frame a.R, frame b.r frame-a.r 0); -R_rel-.. Frames.relativeRotation(frame_b.R, frame_a.R);
/* Transform the forces and torques from frame_a to frame b */ [-
[frame b.f, frame b.t) • Frames.multipleResolve2(R reI,
-
-
-
frame a.f, -frame a.t + cross(r reI a, frame a.f»)); end partialForce; -
Modeliea.Mechanies.MultiBody.lnterfaees.PartlaILlneF oree
q
h All line forceelementsshouldbe basedon this base It' model.This modeldefines frame_a and frame_b, computesthe relativedistances and provides the
force and torquebalanceof the cut-forces and cut-torques at frame_a and frame_b, respectively. In sub-models, only the line force f, actingat frame_b on the line fromframe_a to frame_b, as a function of the relativedistances and its derivative der(s) has to be defined. partial model PartialLineForce "Base model of line force elements" import 51 = Modelica .5Iunits; parameter 51. position s_small-t. E-6 "IAdvancedll Prevent zero-division if relative distance
s-o" i Interfaces. Frame a frame ai Interfaces. Frame-b frame-b; 51. Force f "Line force acting on frame a and on frame_b (positive, if acting on frame_b and directed from frame a to frame b)"; 51. Position s "(Guarded) distance between the origin of frame_a and theorigin of frame b (>= s small»" i 51. Position e a (3) "Unit vector on the line connecting the origin of frame_a with the origin of frame_b resolved in frame_a (directed from frame a to frame b)"; Real r reI a (3) "positIon vector from origin of frame_a to origin of frame b, resolved in frame a"; protected outer MultiBody.World world; equation Connections .potentialRoot (frame_a.R, 100); Connections .potentialRoot (frame_b.R, 100); assert (cardinality (frame_a) > 0, "Connector frame a of line force object is not connected" ) ; assert (cardinality(frame~b) > 0, "Connector frame b of line force object is not connected" ) ; -
I / Determine distance sand n a r reI a .. Frames.resolve2(frame a.R, frame_b.r_O frame- a . r 0); s .. noEvent(max(Frames.length(r reI a), s small»; e_a = r_rel_a/s; -
/* Determine forces and torques at trame_a and frame_b
*I
frame a. f == - e a * f ; frame-b.f = - Frames. resolve2 (Frames . relat iveRotat ion (frame_a.R, frame_b.R), frame_a. f) ; / / Additional equations, if direct connections of line forces if isRoot (frame a.R) then frame a.R .. Frames.nullRotation(); else -
frame a. t = zeros (3) ; end if;if isRoot (frame b.R) then frame b. R == Frames. nullRotation () ; else frame b.t .. zeros(3) i end if;end PartialLineForce i
Modelica.Meehanlcs.MultIBody.lnterfaees.PartlalAbsol uteSensor This is the baseclass of a 3D mechanics component ... ~.... with one frameand one outputport in order to measure ~ an absolutequantityin the frameconnectorand to providethe measured signalas outputfor furtherprocessing with the blocksof packageModelica.Blocks. partial model PartialAbsoluteSensor "Base class to measure an absolute frame variable" extends Modelica. Icons. RotationalSensor; Frame a frame a "Frame from which data is to be measured" ; Model ica . Blocks. Interfaces. Out Port out Port "Measured data as signals"; protected outer MUltiBody. World world; equation assert (cardinality (frame_a) > 0, "Connector frame a of absolute sensor object is not connected") ; end PartialAbsoluteSensor;
Modeliea.Meehanlcs.MultIBody.lnterfaees.PartlaIRe'atl veSensor
~
This is a base class for 3D mechanical components with two frames and one outputport in order to measurerelativequantitiesbetween the two frames or the cut-forces/torques in the frameand to provide
the measured signalsas outputfor furtherprocessing with the blocksof packageModelica.Blocks. model PartialRelative5ensor "Base class to measure a relative variable between two frames" extends Modelica. Icons. Rotational5ensor; Frame a frame a i Frame -b frame -bi ModelIca. Blocks. Interfaces . OutPort outPort i protected outer MultiBody.World world, equation assert (cardinality(frame_a) > 0, "Connector frame a of relative sensor object is not connected") ; assert (cardinality(frame_b) > 0, "Connector frame b of relative sensor object is not connected") ; end PartialRelativeSensor;
Modeliea.Mechanies.MultiBody.lnterfaces.PartlaIVlsua IIzer
o
Base model of visualizers (has a frame_a on the left side
+ outerworld + assertto guarantee that the component is connected).
partial model PartialV!sualizer "Base model of visualizers (has a frame_a on the left side + outer world + assert to guarantee that the component is connected) " MultiBody. Interfaces. Frame_a frame_a; protected outer MultiBody. World world; equation assert (cardinality (frame_a) > 0, "Connector frame a of visualizer object is not connected") ; end PartialV!sualizer;
Modeliea.Mechanles.MultiBody.lnterfaees.PartlaITwoF rames
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBody.Frames 809 c1
=
This partial model provides two frame connectors,
R_rel relativeRotation(R I,R2); Return relative orientation object from two absolute orientation objects.
both frame connectors are connected.Therefore, inherit from this partial model if the two frame
R2 = absoluteRotation(R I,R_rel); Return absolute orientation object from another absolute
b access to the world object and an assert to check that
connectors are needed and if the two frame connectors should be connected for a correct model. partial model PartialTwoFrames "Base model for components providing two frame connectors + outer world -+ assert to guarantee that the component is connected" Interfaces. Frame a frame a; Interfaces. Frame -b frame-b; protected outer HultiBody. World world; equation assert (cardinality(frame a) :» 0, "Connector frame a of component is not connected"); assert (cardinality (frame_b) > 0, "Connector frame b of component is not connected"); end PartialTwoFrames i
and a relative orientation object. R =planarRotation(e,angle); Return orientation object of a planar rotation. angle =planarRotationAngle(e, vi, v2); Return angle of a planar rotation, given the rotation axis and the representationsof a vector in frame I and frame 2. R =axisRotation(i,angle); Return orientationobject R for rotation around axis i of frame I. R =axesRotations(sequence, angles); Return rotation object to rotate in sequence around 3 axes. Example: R = axesRotations({ 1,2,3},(90,45,-90}); angles = axesRotationsAngles(R, sequence); Return the 3 angles to rotate in sequence around 3 axes to construct the giyen orientationobject.
Modelica.Mechanics.MultiBody.Frames Functions to transform rotational frame quantities The package Frames contains type definitions and functions to transformrotational frame quantities. The basic idea is to hide the actual definition of an orientationin this package by providing essentially the type Orientat ion together with functions operating on instances of this type. If the underlying description of the orientation description is changed, then only changes in this package are necessary.
In the table below an example is given for every function definition. The used variables have the following declaration: Orientation R, Rl, R2, R reI, R inv; Real(3,3) T, T inv; Real (3] vl, ~2, WI, w2, n x, n_y, n_z, e, e_x, res_ori, phi7 Real[6] res equal; Real L, ingle;
Function/type Description Orientation R; New type defining an orientation object that describes the rotation of frame t into frame 2. der_Orientationder_R; New type defining the first time derivative of Frames.Orientation. res_oei = orientationConstraint(R); Return the constraints between the variablesof an orientation object (shall be zero). w2 = angularVelocity2(R, der_R); Return angular velocity resolved in frame 2 from orientation object R and its derivative der_R. vI =resolveI(R,v2); Transform vector v2 from frame 2 to frame l. v2 =resolve2(R,vl); Transform vector vl from frame I to frame 2. (vl,wl] = rnultiplekesolve ltk, [v2,w2]); Transform several vectors from frame 2 to frame 1. [v2,w2] = multipleResolve2(R, [vl,wl]); Transform several vectors from frame 1 to frame 2. DJ = resolveDyadel(R,D2); Transformsecond order tensor D2 from frame 2 to frame I. D2 =resolveDyade2(R,DI); Transform second order tensor Dl from frame I to frame 2.
=
R nullRotationO Return orientationobject R that does not rotate a frame. R_inv = inverseRotation(R);Return inverse orientation object.
phi =smaIlRotation(R); Return rotation angles phi valid for a small rotation. R = from_nxy(n_x, n_y); Return orientation object from n_x and n_y vectors. R = from_nxz(n_x, n_z); Return orientation object from n_x and n_z vectors. R = from_Tff); Return orientation object R from transformation matrix T. R = from_T_inv(T_inv); Return orientation object R from inverse transformationmatrix T_inv. R =from_Q(Q); Return orientation object R from quatemion orientationobject Q. T =to_T(R); Return transformationmatrix T from orientation object R. T_inv = to_T_inveR);Return inverse transformationmatrix T_inv from orientation object R. Q =to_Q(R);Returnquaternione orientationobject Q from orientationobject R.
exy =to_exy(R); Return (e_x, e_yJ matrix of an orientation object R, with e.,x and e_y vectorsof frame 2, resolvedin frame 1. L = length(n_x);Return length L of a vector n_x. e_x =normalize(n_x); Return normalized vector e_x of n_x such that length of e_x is one.
Typesand constants type Orientation "Orientationtype defining rotation from a frame 1 into a frame 2" extends Intemal.TransfonnationMatrix; encapsulated functionequalityConstraint"Return the constraint residues to express that two frames have the same orientation" import Modelica; import MultiBody.Frames; extends Modelica.Icons.Function; input Frames.OrientationRl "Orientationobject to rotate frame 0 into frame 1"; input Frames.Orientation R2 "Orientationobject to rotate frame 0 into frame 2"; output Real residue(3] "The rotation angles around X-, y-, and z-axis of frame I to rotate frame I into frame 2 for a small rotation (should be zero)"; algorithm residue := {cross(RI[l, :], RI[2, :])*R2[2, :],-cross(RI[l, :], RI[2, :D* R2(1, :],Rl[2, :J*R2[l, :]}; end equalityConstraint;end Orientation; type der_Orientation = Real[3, 3] (each unit="I/s") "New type defining the first time derivative of Frames.Orientation";
810 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica Modelica.Mechanlcs. MultiBody.Frames.orlentatlonConstralnt Returnresiduesof orientation constraints (shallbe zero) function orientationConstraint "Return residues of orientation constraints (shall be zero)" extends Modelica. Icons. Function; input Orientation R "Orientation object to rotate frame 1 into frame 2"; output Real res idue (6) "Residues of constraints between elements of orientation object (shall be zero)"; algorithm residue := (R[:, l)*R[:, 1) - 1,R[:, 2)*R[:, 2) 1,R{:, 3)*R[:, 3) - 1,R(:, l}"R[:, 2),R(:, l)*R[:, 3],R(:, 2)*R(:, 3J}; end orientationConstraint;
Modellca.Mechanics.MultIBody.Frames.angularVeloclt y2 Returnangularvelocity resolvedin frame2 fromorientation objectand its derivative. function angularVelocity2 "Return angular velocity resolved in frame 2 from orientation object and its derivative ll extends Model ica . Icons. Funct ion; input Orientation R 1I0rientation obj ect to rotate frame 1 into frame 2"; input der_Orientation der_R "Derivative of R"; output Modelica.Slunits.AngularVelocity w[3] "Angular velocity of frame 2 with respect to frame 1 resolved in frame 2"; algorithm /* The absolute angular velocity of frame_a, resolved in frame a, is defined as: w_a • vec (transpose (T) *der (T) ) ; where skew(w) •
Le.
*/
I I I
0 -w3
w3 -w2
w2
0 -wI
wI
0
I I I
and w=vec (skew(w»
:=
Modelica.Mechanlcs.MultIBody.Frames.multlpleResol ve2 Transform several vectors fromframe 1 to frame2 function multipleResolve2 "Transform several vectors from frame 1 to frame 2" extends Modelica. Icons. Function, input Orientation R "Orientation object to rotate frame 1 into frame 2"; input Real vI [3, :) "Vectors in frame 1"; output Real v2[3, size(v1, 2») "Vectors in frame 2": algorithm v2 := R*vl; end mUltipleResolve2;
Modellca.Mechanics.MultIBody.Frames.resolveDyade1 Transform secondorder tensorfrom frame2 to frame 1 function resol veDyadel "Transform second order tensor from frame 2 to frame 111 extends Modelica. Icons. Function; input Orientation R "Orientation object to rotate frame 1 into frame 2"; input Real D2 lJ, 3J "Second order tensor resolved in frame 2"; output Real D1 [3, 3 J "Second order tensor resolved in frame 1"; algorithm D1 : .. transpose (R) *D2*R; end resolveDyadel ;
Modellca.Mechanics.MultIBody.Frames.resolveDyade2 Transform secondorder tensorfrom frame 1 to frame2
W .. transpose (T) *der (T) w_a- (WO,2), -W(3,1), W(2,1>} Therefore, only 3 values of W need to be computed: I e_x' I W • I e_y' I * I der (e_x), der (e_y), der (e_z) I e_z' I I W(3,2) I I e_z'*der(e_y) w_a .. f -WO,l) I - I -e_z' *der(e_x) I W(2,1) I I e_y' *der(e_x)
(R[3, :J*der_R(2, d,-R(3, d*der_R(l, R [2, :) *der R {l, : J}; end angularVelocitY2; w
input Orientation R "Orientation object to rotate frame 1 into frame 2"; input Real v2 [3, : J "Vectors in frame 2"; output Real v1(3, size(v2, 2») "Vectors in frame 1"; algorithm vi : '" transpose (R) *v2; end multipleResolvel;
rl
.
Modelica.Mechanlcs.MultiBody.Frames.resolve1 Transform vectorfrom frame2 to frame 1 function resol vel "Transform vector from frame 2 to frame 1"
extends Modelica. Icons. Function; input Orientation R "Orientation object to rotate frame 1 into frame 2 II ; input Real v2 (3) IIVector in frame 2"; output Real vI(3) IIVector in frame 1 11; algorithm vI :. transpose (R) *v2, end resolve1;
Modelica.Mechanlcs.MultiBody.Frames.resolve2 Transform vectorfrom frame t to frame2 function resolve2 "Transform vector from frame 1 to frame 2"
extends Modelica. Icons. Function; input Orientation R "Orientation object to rotate frame 1 into frame 2"; input Real v1(3] "Vector in frame 1 11; output Real v2 [3] "Vector in frame 2", algorithm v2 :- R*v1; end resolve2 ;
Modelica.Mechanlcs.MultIBody.Frames.multlpleResol ve1 Transform severalvectorsfromframe2 to frame 1 function mul tipleResolvel "Transform several vectors from frame 2 to frame 111 extends Modelica. Icons. Function;
function resolveDyade2 "Transform second order tensor from frame 1 to frame 2" extends Modelica. Icons. Function; input Orientation R "Orientation object to rotate frame 1 into frame 2"; input Real D1 (3, 3) "Second order tensor resolved in frame 1"1 output Real 02 (3, 3) "Second order tensor resolved in frame 2"; algorithm D2 ::: R*Dl *transpose (R) : end resolveDyade2 ;
Modellca.Mechanfcs.MultiBody.Frames.nuIiRotation Returnorientation objectthat does not rotatea frame. function nullRotation "Return orientation object that does not rotate a frame" extends Modelica. Icons. Function; output Orientation R "Orientation object such that frame 1 and frame 2 are identical", algorithm R :- identity(3); . end nullRotation;
Modellca.Mechanics.MultiBody.Frames.lnverseRotatio n Returninverseorientation object function inverseRotation "Return inverse orientation object II extends Modelica. Icons. Function; input Orientation R 1I0rientation object to rotate frame 1 into frame 2"; output Orientation R_inv "Orientation object to rotate frame 2 into frame 1"; algorithm R inv :. transpose (R) ; end-inverseRotation,
Modelica.Mechanlcs.MultiBody.Frames.relatlveRotatio n Returnrelativeorientation object. function relativeRotation "Return relative orientation object" extends Modelica. Icons. Function;
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBody.Frames 811 input Orientation R1 tlOrientation object to rotate frame 0 into frame 1"; input Orientation R2 "Orientation object to rotate frame 0 into frame :2"; output Orientation R_rel "Orientation object to rotate frame 1 into frame :2"; algorithm R_rel :: R2*transpose (Rl) ; end relativeRotation;
Modellca.Mechanlcs.MultIBody.Frames.absoluteRotatl on Returnabsoluteorientation object from anotherabsoluteand a relativeorientation object. function absoluteRotation "Return absolute orientation object from another absolute and a relative orientation object" extends Modelica. Icons. Function; input Orientation R1 "Orientation object to rotate frame 0 into frame 1 tl; input Orientation R_rel "Orientation object to rotate frame 1 into frame 2"; output Orientation R2 "Orientation object to rotate frame 0 into frame 2"; algorithm R2 :.. R reI *Rl ; end absoluteRotation;
Modelica.Mechanics.MultIBody.Frames.planarRotatlon Returnorientationobjectof a planarrotation function planarRotation "Return orientation object of a planar rotation" import Modelica. Math; extends Modelica. Icons. Function; input Real e[3} "Normalized axis of rotation (must have length,.,1) "; input Modelica. Slunits .Angle angle tlRotation angle to rotate frame 1 into frame 2 along axis e"; output Orientation R "Orientation object to rotate frame 1 into frame 2"; algorithm R : = Ie l "transpose ( [e]) + (identity (3) [e}*transpose( [e]) )*Math.cos(angle) - skew(e) ·Math. sin (angle) ; end planarRotation;
Modetica.Mechanics.MultiBody.Frames.planarRotatlon Angle
i. e., vz .. resol ve2 (planarRotation fe, angle) , vI) II ; output Modelica.Slunits.Angle angle "Rotation angle to rotate frame 1 into frame 2 along axis e in the range: -pf definedby vectorn whichis perpendicular to the plane and by vectornx, whichpointsin the direction of the x-axisof the plane. frame_a and frame_b coincidewhen prismatic_a.s=O, prismatic_b=O and revolute.phi=O. Thisjoint has the following potential states: • the relativedistanceprismatic_x.s [m) along axis n_x, • the relativedistanceprismatic-y.s[m] alongaxis n_y = cross(n.n_x), • the relativeanglerevolute.phi [rad]aroundaxis n, • the relativevelocity prismatic_x.v [mls) (= der(prismatic_x.s)). • the relativevelocity prismatic_y.v [mls] (= der(prismatic_y.s)). • the relative angular velocity revolute.w [rad/s)(= denrevolute .phij)
The potential states are used as candidates for automatic selection of states fromthe tool. This may be enforced by setting "enforceStates=true" in the Advanced menu(this means that the Modelica attributes staleSelect=StateSelecl.always are set on these variables). The states are usuallyselectedautomatically. In certain situations, especially whenclosed kinematic loopsare present, it might be slightlymoreefficient,whenusingthe "enforceStates" setting. Thisjoint is visualized witha box alongaxis n_x,a boxalong axis n-y and a cylinderalongaxis n. model Planar "Planar joint (3 degrees-of -t reedom, 6 potential states) " import NonSI _ Modelica . S I. Co nv e r s i ons . NonSI un i t s ; extends MultiBody . Interfaces . PartialTwoFrames ; parameter Boolean anfmat.donet.r'ue "... true , if animation shall be enabled" ; parameter MultiBody .Types .Axis n..{O,O ,I) "Axis orthogonal to unconstrained plane, resolved in frame a ( to same as in frame b)" j parameter MUltiBody.Types .AXis n_x.{l ,O,O} "Vector in direction of x -axis ot plane, resolved i n frame a (n x shall be orthogonal to n) It ; parameter Boolean startValueaFixed..faise I Initializationl _ true, if all start values from below shall be used with fixed.ttue", parameter 51 . Position s_start_x.O "! Initializationl Initial value of x-distance (along It
~a:~;~ter 51 .Position
s_start_y.O ,,' Initializationl Initial value of v-distance (along cross(n,n x»)" j parameter-NonS I . Angle_deg phi_start .O "IInitializationl Initial value of rotation angle along n"; parameter SI . Velocity v_start_xeO "Ilnitializationi Initial value of derivative of xdistance" ; parameter 51 . Velocity v_start_y..O " I Initiali zation I Initial value of derivative uf vdist8nce" ; parameter M!JltiBody. Types . Angu l a r Ve l oc i t y_d eg s w start_O - " ' I n i t i a l i za t i on l Initial value of derivatiVE: of rotation angle " ; parameter SI .DiEltance cyl i nderLength-world. def aul tJoi ntLength "IAnimation I if animation • true 1 Length ot revolute cylinder" ; parameter 51 .Distance cyl inderDiameter.world . defaul tJointWidth "'Animationl!! animation e true I Diameter ot revolute cylinder" j pa remet.ez- tIIultiBody .Types . Color cylinderColor,.Types .Defaults .cc m ecct or "'Animationlif animation - true I Color ot revolute cylinder" ; parameter Real boxWidth,.O . 3·cylinderDiameter "IAnimationlif animation .. true I Width of prismatic joint boxes." ; paramp.ter Real boxHeight-boxWidth "IAnirr.a.tionJ it animation - true I Height of prismatic joint boxes " ; parameter MultiBody .Types . Co l o r boxcofore'rypea ,De!aults .,J'o i n t Co l o r "IAnimationli! animation. true I Color of prismatic joint boxes" 1 paramet~r Boolean enforceSta.tes.false "IAdvancedll - true, it generalized variables (s.phi.v.w) shall be used as states" ; Prismatic prismatic_x ( enforceStates_enforceStates, n. (cross (cross (n, n xl , n», startValuesFixed.startValuesFixed, animation.. false , s start-g start x , v- start.v- start-x) 1 Prismatic priematlc_y( enforceStates-en!orceStates, n- (croBs (n , n x l l , startValuesFixed_startValuesFixec1, animation-false, B sta':t-s start y, v=start_v=start=y) 1 Revolute revolute ( entorceStates_enforce5tates , n..n ,
818 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica startValuesFixed=startValuesFixed , animation-talse , phi start _phi start , ",_start.",_start) ; protected parameter Integer mUm- i f world . enableAnimat ion and animation then 1 else 0; parameter Real e (31 .Frames . normalize (0) I protected Visualiz ers .Advanced .Shape box x(ndim) ( each shapeType-"box" , -
each color -boxColor , each each each each
length-prismatic X .B, width",boxWidth, height.boxWidth , lengthOirection-prisntatic_x .e ,
each widthDirection- I0. 1. 0). each r -frame !I.r O. each R",frame-a .R); Visualizers .Advanced.Shape box y(ndim) ( each shapeType_"box", each coforvboxcofor , each length-prismatic y . 8, each width=boxWldth, each he ight.boxMidth, ea ch lengthDirection-priemat icy . e,
each widthDi rection. I1,0.0) • each r llpriematic y .frame 8 .r 0 , each RllprismaticJ . frame:a. R) ; Visualizers .Advanced .Shape cylinder(ndim) ( each shapeType-"cylinder", each color..cyl inderColor, each length..cylinderLength , each width..cylinderOiameter, each helght _cylinderDiameter, each lengthDirection.n ,
each widthDirection-1 0.1.0). each r shape. ·e· IcylinderLength/2) . each r;revolute .trame b .r 0 , each R.revolute .frame-b .RJ , equation c onn ec t (frame a, prismatic x . trame a) , connect (prismatic_x. frame_b, prismatic_yo frame_a) ; connect (prismatic-y. frame_b , revolute . frame_a) ; connect (revolute. frame b, frame b) ; end Planar ; -
Modellca.Mechanlcs.MultiBody.Jolnts.Spherlcal
r.....
Joint with 3 constraints that define that the origin of ~ frame_a and the origin of frame_b coincide. This joint does not have potential states. If this joint is used in a chain structure. a Modelica translator has to select orientation coordinates of a body as stales. If this joint is used in a loop structure, it is a cut-jointthat breaks the loop in independent kinematic pieces, hold together by the constraints of this joint. As a result, a Modelica translator will first try to select 3 generalized coordinates in the joints of the remaining parts of the loop and their first derivative as states and if this is not possible, e.g., because there are only spherical joints in the loop, will select coordinates from a body of the loop as states . model Spherical "Spherical joint (3 constraints, no potential states)" extends MultiBody . Interfaces . PartialTwoFrames ; parameter Boolean animation-true "~ true, if animation shall be enabled (show sphere)"; parameter SI.Distance sphereDiameter-world . defaul tJoi ntLength "I i t animation • true I Diameter of sphere representing
the
spherical joint·; parameter MultiBody.TypeB .Color sphereColor-Types .Oe f a u l ts. JointColor "I if animation - true I Color of sphere represent ing the
spherical jo int" I
Frames .Orientation R ret "Relative orientation object to rotate from frame_A to frame_b" ; protected parameter Integer ndim-if world .enableAnlmation and animation then 1 else 0 ; Visualizers .Advanced .Shape sphere (ndim) ( each shapeType.....sphere" , each color_sphereColor , each length_sphereDiameter, each width.sphereDiameter. each height_sphereDiameter, e ach lengthDirection-{l,O,O) ,
each widthDirection-IO.l. 0).
each r_sha.pe.( -0 . S. 0 , o} -sphereDlameter, each r ...t rame a . r 0 , each R.frame-a.R); equation / / Constraint equation frame_b .r_O .. frame_a.r_O:
II force balance R reI ... Frames .relativeRotation(trame a.R, frame b .R) , zeros (3) .. frame a .! + Frames .resolvel(R re t , frame b .t) ; / I (1' Alemberts principle + torque balance frame a .t .. zeros(3) ; frame-b.t _ eeroe ta l , end Spherical ;
Modellc8.Mechanics.MultiBody.Jolnts.FreeMotlon
...r"A io··.(;H
Joint which does not constrain the motion between frame_a and frame_b. Such a joint is only meaningful if the relative distance and orientation between frame_a and frame_b, and their derivatives, shall be used as states. Note, that bodies such as Parts . Body, Parts . BodyShape, have potential states describing the distance and orientation, and their derivatives, between the world frame and a body fixed frame. Therefore, if these potential state variables are suited, a FreeMotion joint is not needed. i;
model FreeMotion "Free moti on joint (6 degrees wof·freedom , 12 potential states ) .. import Model Lca . Math . - : import SI - Modelica .SIunits; import Cv .. Modelica .SI.Convers ions; extends MultiBody . Inte rfaces . PartialElementarYJoint ; parameter Boolean animation_true "- true , if an imation shal l be enabled (show arrow from frame a to frame b)"; parameter Boolean startValuesFixed..true .. , In itializationl • true, it: all start values below shall be used with f ixed_true" ;
parameter SI.Position r_rel_a_start(3)'10.0.0) "IInitializationl Initial values o f r rel a (vector from origin of frame_a to origin of frame_b resolved in frame_a ) ":
parameter
Cv .NonSI.
Angl e_deg phi_start (3)- I0, o, 0I
"IInitializationJ Ini t ial values of angle8 to rotate frame a around X- , y-, a- axis into frame b" ; parameter SI.Velocity v_rel_a_start(3)-(o:-O,O) "IInitializationl Initial values of velocity v rel a • der(r reI a)" ; parameter-MultiBody .Types .AngularVelocity_degs w
rel_a_start(3)'(O .0 .0)
"TInitializationl Initial values of angular velocity ot frame b with respect to frame a resolved in frame a" ; parameter SI . Length arrowDiameter..world . defaul tArrowDiameter "IAnimationlif animation. true I Diameter ot arrow from frame a to frame b" : para~ter MultiB~dy.Types .Color arrowColor..Types . Def a u l t s .Se n s o rCo l o r "IAnimationlif animation .. true I Color of arrow", parameter Boolean entcreeseaeese eeue "IAdvancedll • true . if generalized variables shall be used as states" ;
SI.Position r rel a(3) ( start.r reI-a start, fixed. flU liitartVa luesFixed . 3). stateSelect.if enforceStates then StateSelect.always else StateSelect. prefer) "Position vector from origin ot: frame_& to origin of frame b, resolved In frame a" ;
SI.Velocity v_rel_a(3) (
-
start_v reI a start , fixed.fIll (startValuesFixed, 3), stateSelect.i£ enforceStates then StateSelect . always else StateSelect . p r e f e r ) .... der (r rel a), i .e . , velocity ot origin of trame_b with respect-to orIgin of frame_a , resolved in frame_A" ;
SI .Angle phi (3) (
start.. Cv . from_deg(phi_start) , fixed. fill (startValuesFixed , 3), stateSelect ..if enforceStates then StateSelect . always else StateSelect . p r e f e r ) "Angles to rotate frame_& around x-", y ~, z-axis into frame_b" ;
SI.AngularVelocity w_rel_a(3] (
start_w rel a start-Modelica .constants .D2R , fi xed_tTll (start ValuesFixed, 3) ,
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBodyJoints 819 stateSelect~if
enforceStates then StateSelect .always
else StateSelect , prefer) "Angular velocity of frame b with respect t o frame a , resol ved in frame a : w reI-ali: vee ( der (T re I} " 6T ret
-
)" ,
-
-
-
-
protected constant Real c2 Bmall .l.e~6 "It cos Iphf Iz l -; c2_small, c2 _small is u s ed as guard against zero di vision " ; Real sl ". sln(phl ll) I" , Real s2 " . sln(ph I12))" ; Res! s3 I t . sin(ph i(3) "; keal e l " . eos(phillll" , Real ez cos(phi{2) " :
Import SI • Modeliea .Slunits , extends rneeet aces . PartialTwoFrames ; pa rameter Boolean enteee tcn-e rce ,,~ true , if animati on shall be enabled" ; parameter Boolean showMass.true "= true , if mass shall be shown (provfded anfmat. Lon '"' true
It.
a nd m > 0) " ;
Real c J ;" " . cos (phi l2}) with guard against zero " ; Real c3 "E cos(phi(3)" ;
protected parameter Integer ndim,.if world. enableAnimation and
animation then 1 else 0 ; Visualizers .AdvAnced .Arrow arrowfnd imJ ( each r heede r' reI a .
each dIameter:arrowDiameter f each corore ar-roecof or , each r .. frame a . r 0, each R_trame-a .R); Frames . Or i e nt a t i on 'R ret . Real T re113. 31; equationIii Determi ne sines and c o s i ne s of the Ca r da n angles • / sl • oin(phll1l) , s2 • sin (phi (2) I ; 03 • sin(phi (31) ; el " cos (pili (1)) ; c2 • cos (phi (2 ) I , c3 • eoa(phi(31) ;
Iii Below , an expression is di vided by cz . When phi (2)
..
90
deg , c2-0 snd a zero di vision occ u r s. To avoid this , c a is set to a small value around t h i s singular point with the hope that the simulat ion will st ill work even if there is a small jump in oz.
./
e2a .. noE vent
(if
cz
>
c2_small or cz
-c2_small then
e;
e2 else (if e2 >_ 0 then c2 _small else
~ e 2 _sma l l ) );
/. Relative transformati on matrix from frame_a to frame b - T_rel .. ( e3 , s3 , 0 ; ws 3, ca, 0 ; O. 0 , 1)"
.
tea ,
0, - 6 2; O. 1 . 0 ; 82, 0 , c2)' 11, O. 0;
/
T_rel .. (e2*e3 , el*s3
+ 81*s2·c) ,
O.
c1 , sl;
o•
- 01. e ll;
sl*s3 - e 1 · 8 2 *c 3;
e2*83, 01·c 3 - 81·82*8) . e1*e3 + Cl*s2*s3; 82, · 9 1 *c2, e 1 · c 2 ) ;
R_rel • Frames .from_T(T_rel) ;
/1 Kinematic differential equations for translational // motion der(r_rel_4l • v_reI _a ; 1/ Kinematic differential equations for rotational motion der(phil • (w rel a l I l • (sl'w rel a(2) c1."" reI a(3})·s2I c2a.cl·w reI aU) + sl*w reI a(3),(-81·W reI a(2) + cl'w_rel_aIJ))/C2a) I -// Kinematic r elationships frame b .R - Frame8 .absoluteRotation(frame s .R, R ret) ; frame-b .r 0 • frame a .r 0 + Frames.resolvel(frame a .R , r rel-a) ; -
II cue -rcrces and cut -torques are zero frame a .t ... zeros( ) ;
trame-a . t . zeros(J ) ; trame-b.f • zeros()); frame-b .t zeros()) ; end Free:.lotion ; &
Modellca.Mechanlcs.MultIBody.Jolnts.SphericaISpherl cal ,, ~
model 5phericalSpherieal "Spherical - spherical j o i n t aggregation (l constra int , no potent ial states) with an optional point mass in the middle"
Joint that has a spherical joint on each of its two ends. The rod connecting the twosphericaljoints is approximated by a pointmass that is locatedin the middleof the rod.
parameter Boolean comput egodbenqt h e f a Lae " = true . if rodLength shall be computed duri ng ini t ializat ion (see info) " ; parameter S I . Length rodLength ( min =Modelica. Constants. eps , f f xedenot; cornputeRodLength) = 1 "Distance between the origins of frame_a and frame _b (if computeRodLength=true , guess value)"; paramete!: 51 .Mass m_O "Mass of rod (lIE point mas s l ocated in middle of rod) ·; parameter Real sphereDiameter.world . de t a u l t J o i nt Le ng t h "IAnimationlif animation ... truel Diameter of spheres respresenting the spherical joints"; parameter MultiBody . Types .co r c r sphereColor..Multisody .Types .Defaults .J o i nt Co l o r "IAnimaticn I if animation = true I Color of spheres respresenting the spher i cal j oints" ; parameter Real rodDiameter=sphereDiame ter /Mult iBody . Types . De f a u l t s. Jot ntRodniameterFract ion "I1'.nimationlif animation ", true I Diameter of rod connecting the two spherical j o i n t "; parameter MultiBody . 'rypes . Color rodColor =Mult iBody .Types .Def au l t a . RodColor "IAnimationllf animation. t rue] Color of rod connecting the two sphe rical joints" ; parameter Real massDiameter_sphereDiameter "IAnimationl if animation ,. true and showMass • true and m > 0 I Diameter of sphere represent ing the mass poi nt" ; parameter Multi80dy. Types . Co l o r mas sColor.Mul t iBody . Types . Oefaul ts . BodyColor "IAnimationli! anima.tion • true and showMass .. true and m > 0 I Co l o r of sphere representing the mass poi nt " ; parameter Boolean kinematicConstr"int ..true " IAdvan c e d l l '" false, i f no c onstraint Ahall be defined. due to analyti cally sol ving a kinemat ic loop" ; parameter Boolean checkTotalPc'lwer",false " IAdv a nc ed l l • t.rue , it total power flowing into this component shall be determined (must be zero)" ; Frames . Or i e nt a t i on R. reI " Re la t i v e orientation object to rotate from frame_8 to trame_b" ; 51 . Force f rod
"Constraint force in dt rece Icn of t he rod (pos iti ve on frame a , when directed from frame a to frame b) " i 51. Position rRod 0131 "Position vector-from frame_a to frame_b resolved in world frame" ; SI . Position rRod a (3) " Po s i t i on vector-from frame a to frame b resolved In frame a" ; - 51 . Position eRod a (3) "Unit v ec t o r in direction from frame a to frame b, resolved in frame a"; - S1. Position r CM 0(31 "Dummy if m...O, or poaf t Ion vector from world frame to mid-point of rod , resolved i n world trame" ; 51 .Veloc ity v_CM_O(J) "Pirst derivative of r _CM_O "; 51. Force f CM a 131 "Dummy if m ...O, or inertial force acting at mid·point of rod due to mass oi nt acceleration , resolved in frame a " ; 51 .Foree t CM eDI "Durrmy if ;- .0, or pro jection of f _CM_a onto eRod_a, resolved in frame a" ; S1. Force f balD) " Fo rce actIng at frame b , but without force in rod , resolved in frame a" ; 51 . Power total Power "Total power flow ing i nto this element . if checkTotalPower-true (otherwise dummy)" ; protected p arameter Integer ndim.. if world . enableAnin:ation and
820 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica an imation then 1 else 0; parameter Integer ndim2.i f world . enableAnimation and an ima t ion and showHaS8 and m > 0 then 1 else 0 ; Vi s u a l i ze r s .Adva nc ed . Sha pe shape rod [n cUm) ( each sh apeType _"cylinder". each c o lor.. rodColor. eac h leng th .rodLength . each wl d t h . r odD i a me t e r . each he i g ht. rodDiatneter , e ach lengthOirect.lon-eRod '-, each widthDireetion.. (O,l ,O), each r .frame s .c O. e ach R-frame-a .R} ; Vi su a l i ze r s . Ad;ancecL Shape shape a (ndim) « e ac h shapeType "'''sphere'' . e ach color_sphereColor. each length..sphereDiameter. ea ch width..epharenfemeter- , ea ch height ..sphereDiameter , each l e ngthDi r e c t i on ..eRod a. each widthDirection.(O,l,O} , each r shape e vegod a* (sphereDiameter/2). each r ;frame 8 .r 0:each R_frame -a . R) ; Vi sual! zers •Ad;snced . Shape shape_b{ndim] ( e a c h ahape'rypee s aphere " , ea ch co lor. epherecofor , e ach length..sphereDiameter, ea ch width..sphereDiameter. ea ch height .sphereDiameter . ea ch l engthDirection-eRod a, each widthDirecti on. (0.1,0) , each r shape..eRod a· (rodLength - sphereDiameter/2), ea ch r:frame a .r 0, ea ch R_frame-a .R}; Visualizers .Ad;anced .5hape shape_masslndirn2] ( each shapeType.. " sphere" , each cofocemeaecofor , each length..massDiameter , ea ch width..massDlameter, each height.,massDiameter, each lengthDlrection..enoe a, each widthDirection-{O, I, OJ , each r _shape .eRod_a· (r od Leng t h / 2 - sphereDiameter/2) , e a c h r .,frame a.r 0, each R.frame-a.R); equat ion I I Determine relative posit ion vector between the two frames rRod 0 • frame b .r 0 • frame a .r 0 ; rR od -a _ Frame8 .re80lve2(fra~ a"':"R, rRod 0) ; eRod:a - rRod_a /rodLeng th ; -
/. Con s t r a i n t equation is removed . when taken into account s omewhere else, e .g . , when analytically solving a kinematic loop
,/ if kinemat i CConstraint then o _ rRod O*rRod 0 - rodLength*rodLength; end if; -
I I Cut-torques at frame_a and frame_b frame a .t • zeros(3) ; f rame:b .t • zeros (3) ,
1* Force and torque balance of rod Kinematics for center of mass CM of mass point r CM 0 • frame ll .r 0 + rRod 0/2 ; V-CM-O • der(r-CM 0' : a-CM- a . resol;e2(frame a .R , der(v ot 0) wOrld .gravityAcceleration{r_CM_O» I Inertial and gravity force in direction (f_CM_e) and orthogonal (f at n) to rod e Of a • m*a CM f -CM-e • f eM a.eRod a , II in direction of rod f-CM-n. rOdt.engthlf-CM a - f_CM_el, // orthogonal - // to rod Force balance in direct ion of rod f CM e _ fa rod e + tb rod e ; Force balance orthogonal to rod f CM n • fa rod n • tb rod n ; TorqUe b alance ;ith respect to trame_a o • (- f_CM_n ) *rodLength/2 • fb_rod_n·rodLength The result is: fb rod n • f CH n/2 ; fa-rod-n • fb rOd n ; f b-rod-e. f CH e-- fa rod e ; fa:roc(e is the-unknown c Ofnputed from loop
a
'/ II f b al is needed in aggregation j o i n t s to solve kine~tic loops analytically R reI • Frames. relativeRotation (frame a . R, frame_b.R) ; ifm >Othen -
r CH 0 .. frame a .r 0 • rRod 0/2; v-CH-O _ der(r-CM 0) ; f -CH-a • m*Fra;Ms:-resolve2(frame a .n, der(v CM 0) wOrld .gravityAccele ration{r 01 0) I f CM e _ (f CM a*eRod a) *eROd frame B.f . - ( f - CM a --t Of e)72 • f rod*eRod s , f b a1 • (f CM- a -; f Ore)72 ; frame b .f - - , r a mes . r e s ol ve 2 {R reI , f_b_81 f rod';eRod a ) ; el ee r eM 0 • zeros (3) ; v-0I-0. zeros(J ) ; f-OI-a. zeros(3 ) ; f -CH-e - leros(); f -b al • zerosO. ; frame a . f • f r od*eRod a ; frame-b .f . -Frames .resolve2(R eer , frame_a .t ); end if ;-
a;
it checkTot alPo.....e r t he n
tot a lPowe r . frame a.f*Frames .resolve2(frame • . R, der(frame a .r 0 )) -; frame b .f';Fra;es .resolve2 fframe b .R , der(trame-b .r 0)1 • {·m} *(dertv CM 0) - world .gra;itYAccelerationCr CM O)I·v CM 0 • frame a .t* - -Frames .anguh.rvelocitY2(frame a .R , derfframe_a.R» + frame b .t· Frames .angularVelocity2 (frame b.n, der(frame_b . .RJ) I else total Power • 0 ; end it ; end Sphe r i c a l Sph e r i c a l ;
ModellcB,Mechanlcs.MuIIIBody.Joinls.UnlversaISpherical i
~
:;l,
;;.0
This component consists ofa universal joint at frame_a and a spherical joint at frame_b that are connectedtogetherwith a rigid rod.
model UniversalSpheri cal "Universal - spheri cal j o i n t aggregat ion no po t e n t i a l s t.at es ) "
(1
constra int,
import 51 • Modelica .SIunits ; ex tends Interfac es . PartialTwoFrames i Inte rfaces . Frame_a frame_ia ; parameter Boolean an imation.true " . true , it animation shall be e na b led -; pa r ameter Boolean sh OWUni versalAxes.true " • true , i f un iversal joint shall be visualized with two
~
cylinders, otherwise with a sphere (provided animat ion..true )· ; parameter Boolean computeRodLength-false ". true , it d istance between frame a and frame b shall
--
c omputed during initialization (see info) ", parameter MultiBody .Types .Axis nl_a.{o.o,l) "Axis 1 of universal joint resolved in frame a (axis 2 is orthogonal to axis 1 and to rod)"; pa rameter 51 .P osition rRod_iaUl.{l,O,O) "Vector from origin of frame a to origin of frame b , resolved in frame La (if comPuteRodLength.true , riod._ia is only an axis vector along the connecting rod)" , parameter 51 .Diameter sp hereDiameter-world. defaul tJointLength "IAn1mationllt. animat ion. true I Dill.meter ot spheres representing the uni versal and the spherical joint· ; parameter HultiBody . Types . Color sphereColor-MuI tiBody . Types . Def a u l t s . J o i n t Co l o r " ' Ani mat i on l if a nimation. true I Color of spheres representing the uni versal and the spherical joInt" ; parameter Mul t i Body . Types . ShapeType rodShapeType."cylinder" 'IAnimationlU animation . true I Shape type of rod connecting the universal a nd the spherical joint", parameter 5 1.D istance rodtofidth_ephereDiameter I Hu l tiBody . Types . Def a u l t s . JointRodDiameterFraction "IAnimation lif animation • true I Width of rod shape in d irection of ax is 2 o f u nive r s al joint.· ; parameter 51 . Distance rodHeight.rodWidth -IAnimationlif animation. true I Height of rod shape in direct ion that i6 orthogonal to rod and to axis 2 ."; parameter Real rodBxtra-O .O - IAni mat ion I it animation - true I Additional parameter depending on rod5hapeType (see docu ot Visulilizers .FixedShape) . - ; parameter Mult i Body. Types . Color
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBodyJoints 821 rodColor..MultiBody. Types .Defaults. RodColor "IAnimation Iif animation", true I Color of rod shape connecting the universal and the spherical joints"; parameter SI. Distance cyl inderLength-world . de faul tJointLength "IAnimationlif enfmat Ion « true and showUniversalAxesl Length of cylinders representing the two universal joint axes"; parameter SI. Distance cyl inderDiameter=world. defaultJointWidth " \Animation I if animation - true and showUni versalAxes I Diameter of cylinders representing the two universal joint axes"; parameter MultiBody. Types. Color cylinderColor-Types. Defaults .JointColor "'Animation\if animation • true and showUniversalAxes\ Color of cylinders representing the two universal joint axes" ; parameter Boolean kinematicConstraint=true "IAdvancedll .,. false, if no constraint shall be defined, due to analytically solving a kinematic loop"; parameter Boolean checkTotal Power= f al se " IAdvanced II .. true, if total power flowing into this component shall be determined (must be zero)"; Frames .Orientation R reI "Relative orientation object to rotate from frame a to frame b"' SI. FOrCe' f rod "Constraint force In direction of the rod (positive, if rod is pressed)"; final parameter SI.Distance rodLength(fixed..not computeRodLength) c: Frames . length (rRod_ia) "Length of rod (distance between origin of frame_a and origin of frame_b)"; final parameter Real eRod 1a (3) .Frames. normalize (rRod La) "Unit vector from origin of frame a to origin of frame b, resolved in frame ia"; final parameter Real e2 ia(3)",Frames.normalize(cross(nl a, eRod ia») "Unit vector in direction of axis 2 of universal joint, resolved in frame ia (orthogonal to m a and eRod ia) a"; final parameter Real e3 ia (3) ",cross (eRod ia, e2 La) "Unit vector perpendicular to eRod_ia and e2_ia:resolved in frame ia"; SI. Power- totalPower "Total power flowing into this element, if ch'!ckTotaIPower:ctrue (otherwise dummy)"; SI. Force f b a1 (3] "frame_b.f-wIthout f_rod part, resolved in frame_a (needed for analytic loop handling) "; Real eRod a (3) "Unit vector in direction of rRod a, resolved in frame a (needed for analytic loop handling) "; S1. Position rRod 0 {3] (start-rRod ia) "Position vector-from origin of frame a to origin of frame b resolved in world frame"; SI. Position rRod a (3) (start=rRod ia) "Position vector-from origin of frame a to origin of frame_b resolved in frame_a"; protected SI. Force f b a (3J "frame b. f resolved in frame an; SI.Force f-ia a(3] "frame ia.f resolved in frame a"; SI.Torque t la a(3) "fr:ame ia.t resolved in frame a"; Real n2 a [3 T "Vector-in direction ofaxi s 2 of the universal joint (e2 la), resolved in frame a"; Real length2_n2_a (unit-"m2") "Square of length of vector n2_a"; Real e2 a(3) "Unit vector in direction of axis 2 of the universal joint (e2 ia), resolved in frame a"; Real e3 a [3] "Unit vector perpendicular to eRod ia and e2_a, resolved in frame a"; Real T reI ia (3, 3); Frames~Orientation R reI ia "Rotation from frame a to frame_ia"; parameter Integer ndim-if world.enableAnimation and animation then 1 else 0; parameter Integer ndiml.if world. enableAnimation and animation and not showUni versalAxes then 1 else 0;
parameter Integer ndim2 ...i f world. enableAnimation and animation and showUniversalAxes then 1 else 0; Visualizers . Advanced .Shape rodShape (ndim] ( each shapeType=rodShapeType, each cororvrodcoror , each length.. rodLength, each width",rodWidth, each height=rodHeight, each lengthDirection-eRod ia, each widthDirection=e2 ia:each r=frame ia. r 0, each R",frame- ia. R); Visualizers . Ad;anced . Shape spnericalShape b (ndim) ( each shaps'rype- II sphere II , each color=sphereColor, each length=sphereOiameter, each width=sphereDiameter, each heightc:sphereDiameter, each lengthDirection- (I,O,O) , each widthDirectione{O, 1, o}, each r shape- { - 0 .5, O,O}*sphereOiameter , each r;frame b. r t), each R",fra1\e-b. R); Visualizers . Ad;anced . Shape spherical Shape_a (ndiml] ( each shapeType=" sphere" , each color=sphereColor, each length=sphereDiameter, each width=sphereDiameter. each height-sphereOiameter, each lengthOirection= {I, o,o}. each widthDirection= {O, l, O}, each r_shape= ( - O.5,0,0) *sphereDiameter, each r=frame a. r 0, each R=frame-a,R); Visualizers .Ad;anced . Shape universalShapel (ndim2J ( each shapeType.. "cylinder", each color=cylinderColor, each length=cyl inderLength, each width",cylinderDiameter, each height ..cylinderDiameter, each lengthOirection=nl a, each widthDirection- (0, 1',O), each r shape",-nl a* (cylinderLength/2), each r;frame a.r-O, each Rcframe-a.R}i Visualizers .Ad;anced.Shape universalShape2 (ndim2] ( each shapeTypec"cylioder", each color",cylinderColor, each lE:ngth=cyl inderLength, each width=cyl inderDiameter , each height=cylinderDiameter, each lengthDirection-e2 ia, each widthDirection= (o , 1, O}, each r shape",-e2 ia* (cylinderLength/2) , each r:frame ia. r 0, each R=frame-ia.R); equation Connections.branch(frame_a.R, frame_ia.R)
i
rRod 0 - frame b.r 0 - frame a.r 0; rRod=a '" Frames. resolve2 (frame_a-:-R, rRod_O); / / Constraint equation if kinematicConstraint then = rRod O*rRod 0 - rodLength*rodLengthi end if; -
°
r*/
Determine relative Rotation R reI ia from frame_e to frame 1a and absolute rotation of frame_a. R.
eRod_Cl ... rRod_a/rodLength; n2 a ... cross (nl a, eRod a); length2 n2 a • a*n2 assert (no!vent Uength2-n2 a > l.e-10), " A MultiBody .Joints. universalspherical joint (consisting of a universel joint and a spherical joint connected togother by a rigid rod) is in the singular configuration of the uni versal joint. This means that axis 1 of the universal joint defined via parameter \ "n1_a\" is parallel to vector \ "rRod ia\ II that is directed from the origin of ~rame a to the-origin of frame b. You may try to use another' "nl_a\" vector. If this fails, use instead MultiBo1y.Joints.SphericalSpherical, if this is possible, because this joint aggregation does not havE'! a singular configuration.
n2
I~)
a;
;
e2_a - n2_a/sqrt (length2_n2_a) ; e3 a ... cross (eRed a, e2 a); T_rel_ia (eRod_Ia, e2~)a, e3_ia] *transpose ([eRoct_a,
822 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica e2 a, e3 a]); R_rel_ia = Frames. from_T(T_rel_ia)
I
I I Compute kinematic quantities of frame_ia
frame ia.r 0 = frame a.r 0; frame-ia.R-= Frames.absoluteRotation(frame a.R, R_rel_ia) ; -
1* In the following formulas f_a, f_b, f_ia, t_a, t_b, t ia are the forces and torques at frame a, frame b, frame_ia, respectively, resolved in frame_a. e_x,e_y, e z are the unit vectors resolved in frame a. T;;rque balance at the rod around the origin of frame a: 0:: t a + t ia + cross (rRod"a, f b) with tRod a-a rodLength*e xf b = - f rod *e x + f b (2] .. e y + f b ( 3] * e z follows: o '" t_a + t_ia + rodLength* (f_b(2] *e_z - f_b[3] *e_y) The projection of t_a with respect to universal joint axes vanishes: n1 a*t a = 0 e_y*t_a • 0 Therefore: o = n1 a*t ia + rodLength*f b(2) * (n1 a*e z) o :: e_y*t_Ia - rodLength*fj;(3] -or f b '" - f rod *e x e=y* (nl_a*t_ia)I (rodLength* (n1_a*e_z» + e z* (e y*t ia) IrodLerigth Force balance";" o = f_a + f_b + f_ia
*1
R r'e l = Frames.relativeRotation(frame a.R, frame b.R); (f" ia a, t ia a] • Frames .multipleResolvel (R_rel:ia, (frame Ia. f , -frame ia. t]) ; 11- f b a1 is needed in aggregation joints to solve kinematic loops analytically f_b_a1 '" -e2_a* «nl_a*t_ia_a) I (rodLength* (n1_a*e3_a») e3 a* «e2 a*t ia a) IrodLength) ; f b a = -f rod*eRod a + f b a1; frame b.f :; Frames.resolve2(R reI, f_b_a); frame-b.t - zeros(); zeros(3) • frame a.t + t b a + f ia a; zeros (J) = frame=a. t + t=ia_a + cross (rRod_a, f_b_a);
I I Measure power for test purposes if checkTotalPower then totalPower frame a.f*Frames.resolve2(frame a.R, der(frame a.r 0» -:; frame b. f.Frames. resolve2 (frame b. R, der(frame-b.r 0» + frame-ia. f*Frames. resolve2 (frame ia .R, der (frame ia. r 0» + frame a-:-t*Frames.angularvelocity2(frame a.R, der (frame a .R» + frame b. t* Frames.angularvelocity2(frame_b.R, der(frame_b.R» + frame ia. t* Frames.angularVelocity2(frame_ia.R, der(frame_ia.R» I else total Power • 0; end if; end Uni versalSpherical; II:
Modelica.Mechanics.MultiBody.Joints.lnter nal This subpackageis not reproducedexcept for the Revolutejoint. Components used for analytic solutionof kinematicloops (use only if you know what you are doing) The models in this package should not be used by the user. They are designed to build up other modelsin the MultiBodylibrary and some of them cannot be used in an arbitraryway and require particularknowledgehow to set the options in the parameter menu. Don't use the modelsof this package.
Modelica.Mechanlcs.MultiBody.Jolnts.lnternal.Revolut
e Revolutejoint (1 rotationaldegree-of-freedom, 2 potential states) Joint where frame b rotates aroundaxis n which is fixed in frame_a. The two f;mes coincide when "phi + phi_offset= 0", where "phi_offset" is a parameterwith a zero default and "phi" is the rotation angle.
In the" Advanced" menu it can be defined via parameter enforceStatesthat the rotationangle "phi" and its derivative shall be definitelyused as states (this means that the Modelica attributesstateSelect=StateSelect.always are set on these variables). The states are usuallyselected automatically. In certain situations,especiallywhen closed kinematic loops are present,it mightbe slightly moreefficient, when using the "enforceStates" setting. If a planar loop is present, e. g., consisting of 4 revolute joints where the joint axes are all parallel to each other, then there is no longer a unique mathematical solution and the symbolic algorithms will fail. Usually, an error message will be printed pointing out this situation. In this case, parameter planarCUtJoint in the "Advanced" menu of one of the revolute joints has to be set to true. The effect is that from the 5 constraints of a usual revolute joint, 3 constraints are removed and replaced by appropriate known variables (e.g., the force in the direction of the axis of rotation is treated as known with value equal to zero; for standard revolute joints, this force is an unknown quantity). model Revolute "Revolute joint (1 rotational degree-of-freedom, 2 potential states)" import SI = Modelica.Slunits; import ev ... Modelica.Slunits.Conversions; Interfaces. Frame a frame a; Interfaces.Frame-b frame-b; parameter Boolean animatIon=true "= true, if animation shall be enabled (show axis as cylinder)"; parameter MultiBody.Types.Axis n={O,O,l} "Axis of rotation resolved in frame a (D same as in frame b)"; parameter ev. NonSlunits . Angle_deg phi_offset=O "Relative angle offset (angle - phi + from deg (phi offset»"; parameter Boolean startValuesFixed=false "IInitializationl .. true, if all start values below shall be used with fixed=true"; parameter Boolean phi_start_fixed-false "IInitializationl ... true, if only phi_start shall be used with fixed ..true"; parameter Cv. NonSIunits. Angle_deg phi_start-O "! Initialization! Initial value of rotation angle phi" ; parameter MultiBody. Types . AngularVelocity_degs w start=O - "I Initialization! Initial value of derivative of phi (= relative angular velocity)"; parameter SI. Distance cylinderLength=world. defaul tJointLength "IAnimationlif animation. true I Length of cylinder representing the joint axis"; parameter SI. Distance cyl i nderDiameter=world . defaul tJointWidth "IAnimation Iif animation - true! Diameter of cylinder representing the joint axis"; parameter MultiBody . Types. Color cyl inderColor=Types . Defaul ts .JointColor "!Animation!if animation. true! Color of cylinder representing the joint axis"; parameter Boolean enforceStates-false "IAdvanced!1 = true, if generalized variables (phi,w) shall be used as states"; parameter Boolean planarCutJoint=false "IAdvancedll = true, if joint shall be used as cutjoint in a planar loop"; 8I.Angle phi ( start=ev. from_deg (phi_start) , fixed=startValuesFixed or phi_start_fixed, stateSelect-if enforceStates then StateSelect. always else if planarCutJoint then StateSelect. never else StateSelect. prefer) "Relative rotation angle from frame_a to frame_b • phi + from_deg (phi_offset) ) "; SI.AngularVelocity w( start..w start *Modelica. Constants. 02R, f ixed= startValuesFixed, stateSelect",if enforceStates then StateSelect. always else if planarCutJoint then StateSelect. never else St8teSelect. prefer) "First derivative of phi (relative angular velocity) "; SI. Torque tau=O "Driving torque in direction of axis of rotation" ; Frames .Orientation R reI "Relative orientatIon object from frame_8 to frame_b" ; Frames. Orientation R reI inv "Relative orientatIon object from frame_b to frame_a" ; SI.Angle angle ".. from_deg (phi_offset) + phi"; protected outer MultiBody. World world;
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBody.Forces 823 parameter Real e (JJ -Frames .normalize(n) "Unit vector in direction of rotation axis , resolved in frame a (. same as in frame b)"; Real npx ()) ; Real npy(3); Real nnpxl3l; Real r rel a()) "Position vector from origin of frame_a to origin of frame b, resolved in frame a"; 51 .Force f c (2) "constraInt forces in direction of npx,npy"; -
II temporarily angle. 0; end if ; end Revolute ;
parameter Integer ndim.it world . enableAn!mation and animation then 1 else 0, Visualizers .Adv a nc ed . Shape cylinder (ndim) ( each shapeType."cylinder" f
Modelica.Mechanics.MultiBody.Forces
each color-cyl i nde r Co l o r
'I frame b . t • -ettau ; frame=a . t • - f r a me_ b . t; frame B .t • {npx, npy)·t_c; frame=b .t., -Frames .resolve2(R_rel, frame_a.f);
I
each length-eyl inderLength. each width_cylinderDiameter I each hcight_cylinderDiameter. each lengthDirection-e. each "idthDirection. (O. 1 . 0). each [_shape.-e· (cylinderLength /2) • each r ...frame a . r 0, each R.frame- a.R); equation 8ssert(cardinality(frame_a) " 0, "Connector frame a of revolute joint is not connected") ; assert (cardinalityCframe b) " 0, "Connector frame b ot revolute joint is not connected") ; -
·V"'OI! ~D
World'o
0 then
frame b .t .. -force7 frame-resolve . r 0 ., ee roe (3)
-
frame b . f _ Frames. reBul ve2 {Frames. relativeRotati on (frame_resolve . R, frame b .R), force) ; frame-resolve .f .. zerosD) ; frame-resolve . t . zeros(3) i end if/frame b .t _ zeros()): end FrameForce i
Modellc8.Mechanlcs.MultIBody.Forces.FrllmeTorque r ~ ~,
Frames . resol ve2 ( Fr ames . relat i veRotation (trame_resolve . R. frame b .R ). torque) : frame-resol ve .f .. zeros (3 ) ; frame-resolve .t - eeros tar • end it. ;end FrameTorque ;
Modellca .Mechanlcs.MultIBody.Forces. FrameForceAndTorqu8
j
frame:-resol ve .R-.. Frames .nullRotat i on() ;
et ee
each ~ -frame b .r 0, each r taU .. t' in- m, each r =head--t_ in_m) : equation frame b.f .. zeros(3) i i f ca;dinal ity(frame_resolve ) •• 0 then traMe b .t .. -torque ; frame-resolve.r 0 .. ae roe D) : frame=:-esolve .R-. Frames .nullRotation l); else fr ame_b. t • -
The 3 signalsof the torque connectorare interpreted as
~ the x-, Y: and z-coordinates of a torque acting at the
frameconnectorto which this component is attached. If connector frame _resolve is not connected.the torque coordinatesare with respectto frame_b. If connector frame_resolve is connected.the torque coordinates are with respect to frame_resolve. In this case the force and torquein connectorframe_resolve are set to zero. i.e., this connectoris solely used to provide the infonnationof the coordinatesystem. in whichthe force coordinatesare defined. This torque componentis by default visualized as an arrow acting at the connectorto whichit is connected. The diameter and color of the arroware fixed and can be defined via parametersdiameter and color. The arrow pointsin the directiondefinedby the torquesignals.The lengthof the arrow is proportional 10 the lengthof the torque vector using parameter Nm_to_m as scaling factor. Forexample.if Nm_to_m=100 N/m. thena torqueof 350 Nm is displayedas an arrowof length 3.5m. model FrameTorque "External torque acting at frame_b , defined by 3 input signals and resolved in frame_b or in frame_resolve" import 81 • Modelica . S I un i t s , Interfaces .Frame a frame resolve "It: connected , the input-signals are resolved in this fr3ttle" I tneeet eees . Frame b frame b : Madellca. Blocks . Interfaces . Real Input t orque [) J ( redeclare type SlgnalType .. SI .Torque) "X#, y- , z #coordinates of torque resolved in trame_b or frame resolve (if connected) -: pararMter Boolean animation_true .... true, if animation shall be enabled " ; parameler R.eal Nm_to_mCunit-"tJ.m/m" ) • 10 00 "I if animation • true I Torque arrow scaling (length s torque /Nm_to_m)" i parameter SI .Diameter diameter_world. def aul tArrowDiameter "Iif animation - true I Diameter o f torque arrow " : parameter MultiBody. Types . Color eolor_Hul tiBody .Types. Defaul ts .TorqueColot "I if animation - true I Color of arrow" ; protected outer MultiBody .World world : parameter Integer ndim-if world . enableAnimation and animation then 1 else 0 ; SI . Position t_in_m [)J _freme_b . t /Nm_to_rn "Torque mapped from Nm to m for animation "; Visualizers . Advanced . DouhleArrow arrow[ndim] ( each diAmeter-diameter, each coroeecofor-, each R..trame_b .R,
n~ . The 6 signalsof the load connectorare interpretedas ~~ the X-, Y: and z-coordinates of a force and as the X- . y-, and z-coordinates of a torque actingat the frame connectorto which this component is attached.
If connector frame resolve is nor connected. the force and torquecoordinales;;;'e with respectlo frame_b. If connector frame reso I ve is connected.the forceand torquecoordinates are with respectto frame_resolve . In this case the force and torquein connectorframe.resolveare set to zero.i.e.•this connectoris solelyused to providethe information of the coordinate system. in whichthe forcecoordinates me defined. The inputsignalsare mapped10 the force and torquein the following way: force : load(1 :3J t orque: load[4 :6) The forceand torqueare by default visualizer! as an arrow (force)and as a doublearrow(torque)acting at the connectorto whichthey are connected. The diameters and colorsof the arrowsare fixedand can be defined via parameters forceDiameter. torqueDiameter. forceColor and torqueColor. The arrowspoint in the directions definedby the load signals. The lengthsof the arrows are proportional to the lengthof the forceand torque vectors, respectively. using parameters N_to_m and Nm_to_m as scaling factors. For example. if N_to_m =100 N/m. then a force of 350 N is displayedas an arrowof length 3.5 m. mode l FrameF orceAndTorque
"External torce and torque acting at frame_b, detined by 6
input signals and resolved in trame_b or in frame resolve" impOrt SI • Modelica .Slunits i Interfaces . Frame b trame b r Modelica . Blocks . Interfaces .Real Input load (6) "load11 =6J • x-, y., e-ccordtnates of force and X·, y- , z-coordiantes of torque resolved in trams_b or frame resolved Cit: connected)"; parameter Boolean animation-true ".. true, it animation shall be enabled " j parametor Real N_to_m(unit_-N/m") - 1000 "Iif animation - true I Force arrow scaling (length .. force/N to m)"; paremeter Real Nm_to_mCunit -"N.m/m") • 1000 " li t animation _ t rue l Torque arrow scaling (length. torque/Nm to m) " J parameter- SI -:-Diameter for ceD! ame ter_wor Ld , de taul tArrowDi ameter "I if animation - t.rue] Diameter ot force arrcw" ; parameter 51 .Diameter torqueOiameter_forceDlameter "I it animation - true I Diameter ot torque arrow" ; parameter Hult iBody . Types . Co l o r forceColor _HultiBody. Types . Def au l t.s . ForceColor " I if animation. true I Color of force arrow " ; parameter MultiBody .Types .Color torqueColor_Mul tiBody .Types. Oefaul t e . TorqueColor "lit animation - t rue] Color of torque arrow " ; protected outer MultiBody . World YOrld; parameter Integer ndJm ",Jf world. enableAnimatior. and animation then I else 0 ; Sl. Position f in ml3l-frame b . fIN to m "Force mapped-fram N to m tor animatIon" : 51 . Pos ition t _ i n_mf3 J ..frame_b . t /Nm_t o_m
826 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica "Torque mapped from Nm to m for animation "; Vi sualizers . A.dvanc ed .l\ rrow forceArrow(ndim) ( each df emet.e r e r occent eeet.er ,
each color-forceColor , ea ch
R~frame
b .R,
e ach r .,frame-b .r O. each r tail ",f' in- m, each r-hea"=~f iii m) ; Vi sual i ze r a . Advanced . DoubleArrow torqueArrow (ndim) ( each diameter -torqueOlameter,
I i neShapeWidth..world . defaultArrowDlameter "I Animat ion I if animateLine - true I Width of shape", pa rameter SI . Length lineShapeHeight.lineShapelildth "IAnimationl if animateLine • e rue] Height of shape" ; parameter Real lineShapeExtra_O . 0 "IAnimationl if animateLine - t.rue] Extra parameter tor shape , see docu of Visualizers . FixedShape" ; parameter MUltlBody . Types . Co l o r lineShapeColor-Mult iBody . Types. Defau l to . SensorColor " IAni mat l o n l if animateLine • erue ] Color of lins
each coforvcorquecotcr ,
shape" ;
each R.frame b .R , each r =frame-b .r 0,
parameter Real massDiameter..world . def aul tBodyDiameter "IAnimat ionl if animateMas8 ,. true I Diameter of mass point sphere" ; parameter MultiBody .Types . Co l o r massColor=MultiBody. Types . Defaults . BodyColor "IAnimationl if animateMass true I Color of maes point" ; parameter 51 . Position s small_t .E -tO " IAdvanced I I Prevent zero-division if distance between frame a and frame b is zero" ; SI.Distance length "Distance between the origin of frame_a and the origin of frame b" ; SI. Position r rei 0 (l) "Position vector tram frame a to frame_b resolved in world frame" ; SI. PosItIon e rei 0 (ll "Unit vector In dIrection from frame_a to frame_b , resolved in world frame" I 51 .Posit ion r CM 0(31 (stateSelect -StateSelect .avoid) "Position vector-from world frame to mass point, resol ved in world frame" I SI . Velocity v _CM_OIII (s t a t eSe l e c t . St a t e Se l ect . e v o r d ) "First derivative of r CM 0"; SI."'cceleration ag CM "der(v CM 0) gravityAcceleration"; - protected SI .Force fa "Force from flange_a"; 51 . Force fb "Force from flange_btl I
each r tail-'t in- m, each r-head:-e m);
in
public -In terfaces .Frame a frame resolve It I f conne c t e d. the input-signals are resolved in th is frame" ; equation if cardinality(frame resolve) "". 0 then frame b .t .. -load(} :3) ; frame-b .t'"' - l o a d ( 4: 6 ) ;
frame-resolve .r 0 ... zeros(3); frame=:resolve .R-. Frames .nullRotation(); else (frame b .f, frame b .t) • . Frames -:-mul tip l e ReBo lve 2 ( Frames . relativeRotat ion (frame resolve . R, frame b .R), - (lo ad ( l : l l. loadI4 :6l\l . frame resolve .f • zeros(J) ; frame-resolve .t - zeros(J} ; end if ;end FrameForceAndTorque;
Modellca.Mechanlcs.MultIBody.Forces. L1neForceWlthMass
_'S
r!.-
~
II:
ouf
This component is used to exert a line force between the origin of frame_a and the origin of frame_b by attaching components of the l -dimensional
translational mechanical library of Modelica (Modelica. Mechanics . Translational) between the two flange connectors flange_a and flange_b . Optionally, there is a point mass on the line connecting the origin of frame_a and the origin of frame_b. This point mass approximates the mass of the force element. The distance of the point mass from frame_a as a fraction of the distance between frame_a and frame_b is defined via parameter lengthFraction (default is 0.5, i.e., the point mass is in the middle of the line). In the translational library there is the implicit assumption that forces of components that have only one flange connector act with opposite sign on the bearings of the component. This assumpt ion is also used in the LineForceWithMass component: If a connection is present to only one of the flange connectors, then the force in this flange connector acts implicitly with opposite sign also in the other flange connector. model LineForceWithMass "Ge ne ra l l i ne force component with an optional mass point on the connection line" import SI - Modelica .SIunits ; extends Interfaces . PartialTwoFrames ; Modelica . Me c hani c s . Translational . Interfaces . Flange_a flange b ; Modelica . Me chani c s . Translational . Interfaces . Flange_b flange a ; parameter Boolean animateLine-troe "= true , if a line shape between frame_4 and frame_b shall be visualized"; parameter Boolean animateMass-true "_ true, if mass point shall be visualized as sphere provided m > 0" ; parameter 5I .Mass m-O "Mas s of point mass on the connetlon line between the origin of frame_B and the origin of frame_b" I parameter Real lengthFraction( min-Of max-l) _ 0 .5 "Loca t ion of po int mass with respect to frame_a as B fraction of the distance from frame a to frame b"; parameter Mul t IBoo y .Types . ShapeTypeI ineShapeTypec "cylinder" "I Animatlonllf animateLine • true! Type of shape visual izing the line from frame_a to frame_b" I parameter 51 . Length
parameter Integer ndim1_ if world. enableAnimation and anima teLine then 1 else 0 ; parameter Integer ndim2. if world .enableAnimation and animateMass and m > 0 then 1 else 0; Visualizers . Advanced . Shape llneShape (ndlml 1 ( each ehapeTypezlineShapeType, each color-l ineShapeColor , each length=length, E!!ach width-lineShapeWidth, ea ch height.lineShapeHeight, each lengthDirect ion_e reI 0, each widthDirection.Yrames-:-resolve1 (frame a. R,
(0,1 ,0)), each extra _l ineShapeExtra , each r.frame a. r O) I Vieualizers .Ad;anced .Shape massShape(ndim2) ( each ahape'rype ev aphet-e'", each color..massColor, each length=massDiameter, each width_massDiameter , each height-massDiameter, each lengthDirection _e reI 0, each widthDirection.lo-;-l ,oT. each r_shape=e_rel_O· (length·lengthFraction massDiameter/2) , each r .. trame a .r 0 ) ; equation -Connections . potentialRoot (frame a . R, 100) I connections . potentialRoot (frame-b. R, lOO) ; as sert (noEvent (length > s_small), " The dis tance between the origin of frame a and the origin of frame _b of a LlneForceWithMass cOmponent became smaller as parameter s small (_ a small number, defined In the \"Advanced\" menu). The distance is set to s small, although it is smaller, to avoid a division by zero when computing the direction of the line force . Possible eaecne for this situation: . At initial time the distance may already be zero : Change the initial positions of the bodies connected by this element . - Hardware stops are not modeled or are modeled not stiff en ough . In clude stops, e .g ., stiff springs , or increase the Stiffness if already present . - Another error in your model may lead to unrealistically
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBody.Forces 827 large forces and torques that would in reality dest ro y the stops . • The flange_b connector might be defined by a pre defined motion, e .g . • with Modelica . Mechanic::! . Translational . Pos it ion and the predefined fla nge_b .B is zero or negative . ") ;
/ I Determine relati ve position vec t o r between the two frames r _rel_O • trame_b . r_O - frame_a .r_O; length. Ftameo.length(r reI 0) ; flange a .s - 0 ; -nange:b. s • length ; e reI 0 • r:rel:O/Frames . Internal . ma xWi t hou t Eve n t (l e ng t h , s_small) 1
II Determine translational flange forces
it cardinal1ty(flange_4) > 0 and cardlnalityCflange_b)
> 0 then
fa • flanye_a . f: fb • nange_b . f ; alseit cardinality(flange_4) cardinality(flange_b) fa. flange a .f ; fb • -fa ;
Modellca.Mechanlcs.MultiBody.Forces.Sprlng
Linear spring actingas line forcebetweenframe_a
etN-b and frame_b. A forcef is exertedon the origin of frame_b and withoppositesign on the o:igin of
frame_a along the line from the originof frame_a to the origin of frame_b according to the equation: f ..
c' te - B_unstre t ched) ;
where"c" and "s_unstretched" are parameters and "s" is the distancebetween the originof frame_a and the originof frame_b. Optionally, the massof the springis takeninto accountby a pointmasslocated on the linebetweenframe_a and frame_b (default: middle of the line). If the springmassis zero,the additional equations to handlethe massare removed. model Spring
:>
"Linear translational spring with optional mass" parameter Boolean animation...t rue "s true , if animation shall be enabled "; parameter Boolean showMa8s~true .... t rue , if mass point shall be v i s ua lized as sphere if animation _true and m>O"; parameter Real c (final unitu"N/m" , fInal min-O) "Spring constant" ; flarameter 51. Length e unae reeenec-o -un ee reecnec spring length"' ; parameter 51.Mass maO "Spring mass located on the connetion line between the origin of frame_a and the origin of frame_b" ; parameter Real lengthFrsction ( min .O ,
0 and 0 then
-
eleeif cardinal ity(flange_a) ,._ 0 and cardinal it y(flange b) > 0 then fa • - f bi fb • flange_b f ; else fa • 0 ; fb • 0 , end if,
r-
Force and torque balance of mass point • Kinematics for c e n t e r of mass CM of mass point includ ing gravity r CM 0 • frame a .rO .. r_rel_C'M_O ; V-CH-O • der(r-CH 0) , eM 0 • der(;; eM 01 world.gravItyAcceleration(r eM 0) ; - Power balance tor the connection line (U .. force on frame_s side , f2_f orce on frame _b side , h.lengthFraction) (I'va ~ m'a_CM' (va. (vb-vs ) "'h) ... f2'vb - Ul • m'a_CM'" (l ~h» ·va ... (£2 - m·ag_Ot'·h) evb since va and vb are completely I nde pede n t from each other the paranthesis must vanish : fl : _ m*ag CM· (I-h)
a9
°-
t2 : _ m1tag-CM1th
Force balance o n (rame a and frame_b finally results in 0 .. frame B.f e reI a*fa - fl a 0- frame-b .f e-rel-b*fb • (2~) and: therefore -frame a .f _ -e reI a'fa + m'ag CM a 1 t { 1 - h ) frame:b . f _ -e:rel:b'fb ... m*ag=CH:b"'h
*/
max e L) - 0 .5
"Location of spring mass with respect to frame a as a fraction of the distance from frame_a to frame=b (sO : at
frame a ; -1 : at frame b)" ; pa rameter 51 .Distance- width.world .defaultForceWidth " IAnim ationtit animation . e rue] Width o f spri ng "; parameter s t vn t eeence coilWidth _width/l0 "'Animationl if animation. true I Wiring coil "; parameter Integer numberOfWlnd ings_S "IAn .t.mationlif animation - true I Number of spring windings " ; parameter Mult iBody .Types.Color color...M ultiBody. Types . Defaults . Sp r i ngCo l o r " IAni ma t i o n l i ! animation - true I Color ot spring" ; parameter Real massDiameter-max(O , (width2'coilWidth) '0.9) "IAniMationlif animation. true and showMass .., t rue] Diameter o f mass point sphere "; parame ter MultiBody . 'I)'pes . Color massColor -HultiBody . Types .ne eeut ee . BodyColor ")Animationlif an imation - t rue and showHass • t rue] Color of mass point": extends Interfaces . Partial TwoFrames ; Forces . LineForceUithMas8 llneForce (
if m > 0 then r CM 0 - frame a .r 0 ... r _rel _O'lengthFraction : v-Q / / Provide appropriate equations , if direct connections
Modellca.Mechanlcs.MultiBody.Forces.Damper
ag
49
°-
of
lIne t.orces if IsRoot(t'rame 4 .R) then frame _a.R .. Frames .n ullRotationCl ; else frame_a .t • zeros() ; end if ; if isRoot(frame b .R) then frame_b .R _ Frames .nullRotationO ;
else frame b .t • zeros(3) ; end it:l-
end LineForceWithMass ;
Linear damper aClin~ as line force betw~e? frame_a and frame_b. A forcef IS exertedon the ongm of frame_b and withoppositesign on the origin of frarne_a alongthe line from the originof frame_a to the originof frame_b according to the equation: :t
~ h
~
f
_ d'der{s) ;
828 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica where"d" is a parameter, "s" is the distance between the origin of frame_a and the originof frame_b and der(s)is the timederivative of "S" . model Damper "Linear (velocity dependent) damper" parameter Boolean andmat.Ioneti r'ue " .. true, if animation shall be enabled" ; parameter Real d ( fInal unit- "N.s /m", f inal min .O) • 0 "Damping constant ", parameter 51 .Distance length a-world .defaultForceLength "IAnimationlif animation. true I Length of cylinder at frame a side" ; parameter SI .Distance diameter 8=world .defaultForceWidth "! Ani matio n Iif animation - true I Diameter of cylinder at frame a side" ; parameter Real diameter b.O . '+dlameter a "JAnimationlif animat ion - true I Diameter of cylinder at frame b side· ; poram;;ter MultiBody . Types . Color color_a-I 100,100 ,100) "'Animationl!! animation. true I Color at frame_a "; parameter MultiBody . Types . Color color_b_ (155,155 ,1 55 I "IAnimationli! animation. true I Color at frame_bIO i extends Inte rfaces. PartialLineForce ; protected pa rameter Integer ndim ..i l world .enableAnimation and animation then 1 else 0; SI .Position rO b(J) .. e a·noEvent(min(length a , a» ; Visualizers .AdVanced .Shape shape alndimJ ( each shapeType.. "cyl inder" , each ector-corer a , each length=noEvent (min (length_a , e l j , each width.diameter a , each height-diameter a, each lengthDirection;e a , each widthDirection-{O-;l ,O), each r-f rame &.r 0 , each R.. frame -a .R); Visualizers .Advanced .Shape shape blndim) ( each shapeType_"cylinder", each corer-eotoe b , each length-noEvent (max(s . length_a , 0» , each width-diameter_b , each height-diameter_b , each lengthDirection ..e_8, each widthDirection.IO,l,O), each r s hape _rO b , each r;frame a .r 0 , each R=frame - a .RT; equation f .. d-der{s} ; end Damper:
Modellca.Mechanlcs.MultIBody.Forces. SpringDamperParallel
Linear spring and dinear damper in parallel acting as line forcebetween frame_a and frame_b. A forcef is exertedon the originof frame_b and with oppositesign on the originof frame_a alongthe line fromthe origin of frame_a to the originof frame_b according to the equation: f = CO Cs - s_unstretched) + dOder(s) ; where"c", "s_unstretched" and "d"are parameters, "s" is the distancebetweenthe originof frame_a and the originof frameb and der(s)is the timederivative of s, model SpringDamperParallel "Li ne a r spring and linear damper in parallel II import Sl - Modelica .Slunits , parameter aeoteee animation_true It .. true , il animation aha.!l be enabled It i parame ter Real c(linal unit_"N/mlt, final min-OJ ItSpring constant II ; parameter 51.Length s_unstretched.O "Uns t re t c hed spring length"; parameter Real d( final unit.. II N. s / mll , final min-OJ _ a "Damping constant It : parameter 51 .Distance width..world .defaultForceWidth "!Animationlif animation - true I Width of spring" , parameter 5I .Distance coiIWidth-",idth/10 "IAnimation lif animation. true I Width of spring coil" , parameter Integer nUmberOfM'indlngs.S "IAnimation! if animation. true! Number of spring windings" ; parameter MultiBody .Types . Color color..MultiBody. Types . Defaul t e . SpringColor
"IAnimationlif animation. t rue] Color of spring ' , extends Interfa ces . PartialLineForce; protected parameter Integer ndim..i! world . enableAnimation and animation then 1 else 0; Visualizers . Advanced . Shape shape (ndim ) ( each shapeType= "spring", each cororecojor , each Lenqt he e , each width_width , each height-coilWidth'2, each lengthDirection..e a , each wid tbDirection- {o~1,0} , each extra -n umberOfWindings , each r ~frame a . r 0 , each R.. frame-a .R) : equat ion f • ce j s - 8 unstretched) + d*der(s) ; end SpringDamperparallel ;
Modellca.Mechanlcs.MultIBody.Forces. SprlngDamperSeries ~ I:
a
-
b
Linear spri ng and linear damper in series connection actingas line force betweenframe_a and frame_b:
frame_a . - > damper . . -. > spring
I 1--
"_damper -- I (D_damper is the state variable of this system)
A force f is exertedon the origin of frame_b and with opposite sign on the origin of frame_a alongthe line fromthe originof frame_a to the originof frame_b accordingto the equations: f •
c. (s - B_unstretched - s_damper) ;
f • d-eer te damper) ;
where"c", "s=unstretched" and "d" are parameters, "s" is the distancebetweenthe originof frame_a and the originof frame_b. "s_damper" is the lengthof the damper (= an internal state of thisforceelement)and der(s_damper) is the time derivative of s_damper. model 5pringDamperSeries "Linear spring and linear damper in series ccneeeefcnimport SI ,. Modelica .Slunits i parame ter Real c(linal unit. IIN/m lt , tinal min-a) "Spring constant" ; parameter 51 . Length 8_unstretched_0 "Uns t re t ched. spring length": parameter Real d ( final unit _"N.s/m lt , final mincO) _ 0 "Damping constant" ; parameter 51 . Length 8 damper start_O "I n i ti a l length of daT;;per lt ; extends Interfaces . PartialLineForce : SI . Pos ition 8_damper(sta rt_s_damper_start , tixed=true) · Ac t ua l length of damper (frame_a - damper· spring frame b)'" equation ' t • c· (s . s unstretched . s_damper) 1 d-der(s damper) = f ; end SpringDamperSeries;
...
Modelica"Mechanics"MultiBody.Parts
.. ..
Axedrrarslfflcn
•
Body9lapo
Fhr:edRoblbn
Body
This package contains the inertial systemand elementswhich havemassand inertia. Modellca.Mechanlcs.MultiBody.Parts.Flxed
Elementconsisting of a frame(frame_b) that is fixed in the worldframeat a given positiondefinedby parameter vectorr (vectorfromorigin of worldframeto framejb, resolved in the worldframe).
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBody.Parts 829 By default, this componenl is visualized by a cylinder connecting the world frameand frarne_b of this components, as shownin the figurebelow. Note,that the visualized world frame on the left side and FixedJrame_bon the right sideare not part of the component animation and that the animation maybe switchedoff via parameteranimation =false. model Fixed "Frame fixed in the world frame at a given position " import 51 a Mode l i ee . s r un tt e r Interfaces . Frame_b frame_b ; parameter Boolean animation-true
It ..
true . if animation
shall be enabled " ;
parameter SI.PoBition r(3).{O.O .O) "Position vecto r from world frame to frame_b , resol ved in
world frame ": parameter Hul tiBody . Types. ShapeType shapeType_"cylinder" "IAnimation) it an imation .. true) Type of shapp." ; parameter SI.Posit ion r_Bhape(3).{O ,O, O) " IAni mat i on l! ! animat ion . t rua] Vector from world frame
to shape origin , resolved i n world frame to : parameter 51 . Position lengthDirection 13];ar - I_shape "IAnimationl if an imati on .. true I Vector in length direction ot shape, resolved. in world frame · ; parameter 51 . Position widthDirection (3) _ {O, 1 ,0} "IAnimationlif animati on .. truel Vec t o r in width d irection ot shape , resolved in world frame"; parameter 51 . Length length.. Frames . leng th (r - r_shape) " !Ani mat i on / if animation. true! Length of shape " ; parameter 51 .Distance width-length /world . defaul tHidthFract ion "IAnimation I it animation z true I Width of shape "; parameter 51 .Distance he ight -width "IAnimation I if animation .. true I Height of shape "; parameter Real extra-O . 0 "IAnimation lit animation true I Additional pa rameter for cone, pipe et c . (see docu of Visualizers . Advanced . Shape )" ; parameter MultiBody. TypeR . Co l o r color..MultiBody . Types . De f au l t s . RodCol or ·IAnimationl i f animation - t rue] Co l o r of shape"; II;
protected outer MultiBody. World world ; parameter Integer ndim_ if world .enableAnimation and animation then 1 else 0 ; Vi sual izers . Advanced . Shape shape (ndiml ( each shapeType -shapeType, each color-color, each length..length , each width..width, each hoight-height , each lengthDi rect ion_lengthOi rect ion , each widthDirection _widthDirection, each extra_extra , each r_Bhape-r_Bhape- , each e-eeroe (3 ) , each R-Frames .nullRotation()) j equation Connections . root (frame b .R) ;
frame b .r 0 • r ;
-
frame-b .R-z Frames .nullRota tion() ; end Fixed;
Modellca.Mechanlcs.MultIBody.Parls,FlxedTranslation
Component for a fixed translat ion of frame_b with respectto frame_a, i.e., the relationship between connectors frame_a and frame_b remainsconstantand frame_a is alwaysparallelto frame_b. By default.this component is visualized by a cylinder connectingframe_a and frarneb, as shownin the figurebelow. Note.that the two visualized frames are not part of the component animation and that the animation maybe switched off via parameteranimation = false. model FixedTranslation "Fixed translati on of trame_b with respect to frame_a" import 81 - Modelica .Slunies ; Interfaces . Frame a frar.le 8 ; Interfaces .Frame=b frame=b , parameter Boolean animation.true It _ true, if animation shall be enabled" ; parameter S!.Position r(3) .{O ,O .O)
"Vector trom frame a to frame b resolved in frame_a "; parameter Mult iBodY . TypeB . Shap"Type shapeType_"cyl inder" "IAnimationllf animation _ t rue ] Type of shape" ; parameter SI.PoBition r _Bhapel3I .(o ,O,O) "IAnimationlif animation z t rue] Vector from frame_a to shape origin , resolved in frame_a" ; parameter Hul tiBody .Types .Axi s lengthDlrection .. r r shape -" IAni mat i o n l i f animation - t rue] Vector in length direction cf shape , resolved in frame_A" ; parameter MultiBody . TypeB . Axis widthDirection.{ O, 1,?) "IAnimationlif animation _ t rue ] Vector in widt:h direction of shape , resolved in frame_an ; parameter 51 . Length length_Frames .length (r - r shape ) " IAni ma t i on l if animation. true I Leng th of shope" ; parameter 51 . Distance width_length /world . defaul tWidthFraction "'Animation Ii f animation '" true I Width of. shape "; parameter 51 . m eeence height ..wldth "IAnimation I i f animation .. true I Height of ehepe . " ; parameter Real extra .O . 0 "IAnimationlif animation .. true I Additional parameter depending on shapeType (see docu of Vi s ual izer" . Advanced . Shape) . It ; pe reroate r MultiBody .Types . Color color..Mu ltiBody . Types . De f au l t s . RodColo'!" " JAni mat i o n l i f animat i on - true I Color of shape" ; protected outer MultiBody .World world; parameter Integer ndim _if world . enableAnimation and animation then 1 else 0: Vi s ua ll zers . Adv anc e d . Shape shape (ndim] ( ea ch shapeTypeashapeType , each color-color, each r shape. r shape , each lengthD i rection ..lengthDirect ion , each wid thDirection_widthDirgction , each length-length , ea ch width-width , each he ight -height . ea ch extra-extra , each r.frame a .r 0, ea ch R.h'ame-a.R) ; equation Connections . branch (fraltle a .R , trame_b .R) ; asser t (cardinality(frame:=a ) :> 0 or cardinality(frame_b ) 0,
"Neither connector frame_a nor frame_b of FixedTranslation o bj e c t i s co nnected "); frame b .r 0 '" trame _a . r_O + Frames .resolvel(frame_a .R,
r) ;
-
-
frame_b .R .. frame_a.R ;
I· Force and torque balance - I zeros(3) - frame B .f + frame b.f; zeros (3 ) - frame -a.t + frame-b.t + e r c s e t r , frame_b .t) ; end FixedTranslation ;
Modellca.Mechanlcs.MultIBody.Parts.FlxedRotatlon
Component for a fixed translation and fixed of frame_b with respectto frame_a, i.e.• the ~ relationship between connectors frame_a and frame_b remains constant. Thereare severalpossibilities to define the orientation of frame_b with respectto frame_a: ~ rotation
•
Planarrotation alongaxis u' (thatis fixedand resolved in frame_a) witha fixedangle 'angle'. Vectorsn:x and n,...y thatare directedalongthe corresponding axes direction of frame_b and are resolved in frame_a (if n,...y is not orthogonal to n_x, the y-axisof frame_b is selectedsuch that it is orthogonal to n_x and in the planeof n_x and n_y).
•
Sequence of three planaraxes rotations. For example. 'sequence = (I,2 ,3)" and "angles (90, 45. 90}" meansto rotate frame_a around the x axis with90 degrees, aroundthe newy axis with45 degreesand around the newz axis around-90 degreesto anive at frame_b. Note, that sequence=( 1.2,3} is the Cardananglesequence and sequence= (1,3,1 }is the Euleranglesequence. By default. this component is visualized by a cylinder connecting frame_a and frame_b, as shownin the figurebelow.
=
830 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica each each each each each each
In this figureframe_b is rotated along the z-axisof frame_a with 60 degree. Note, that the two visualized frames are not partof the component animation and that the animation may be switchedoff via parameter animation = false. model FixedRotation "Fixed translation and fixed rotation of frame_b with respect to frame_a" import 51 • Modelica .Slunits ; import Cv .. Modellca .SI.Convers!ons ; Interfaces . Frame a frame a , Interfaces . Frame:b frame:b ; parameter Boolean enteee ton-eroe shall be enabled" ;
tI.
color-color , r_shape ..r_shape , lengthDirectlon-lengthDirection, widthDlrec tion-widthDirection , length",length, wi dt h_wi dt h,
each height-height. each extra -extra , each r ...frame a .r 0 , each R.frame-a. R) ; equation Connections .branch(frame a .R , frame b .R) ; assert (cardinality(frame- a) > 0 or -
true. if animation
parameter SI.Position rD)-IO,O .O) "Vector from frame a to frame b resolved in frame a tl ; parameter MultiBodY . Types . RotationTypes . Temp
-
rotationType -MultiBody . Types . RotationTypes .RotationAxls "Type of ro t a t i o n de scription" ; parameter MultiBody . Types .Axis n_ (1,0 ,0) "Iif rotationType • RotationAxisl Axis of rotation In frame a ( oo same as in franK! b)" ; parameter CV .No nS t . Angle_deg angle-O "I if rotat ionType - RotationAx isl Angle to rotate frame a around axis n into frame _b" :
cardinality(frame_b) > 0:"Neither connector frame a nor frame b of FixedRotation object is connected"} ; / - Relationships between quantities of frame_a and frame b 'j frarne b .r 0 .. frame 8 .r 0 + Frames .reBolvel(frame a .R,
r} ;
-
-
-
-
-
frame_b re solved in frame_a" ;
it Connections .isRoot(frame a .R) t he n frame b .R .. Frames .absoluteRotat!on(frame a .R, R_rel) ; zerost3} .. frame a . f + Frames .resolvel(R reI , frame b .t} ; zeros(3} .. frame a .t + Frames .resolvel(R_rel , frame b .t) c r os s (r, frame a.f) ; else frame a .R - Frames .absoluteRotation(frame b.R, R rel- inv} ; zerost3} - frame b. f + Frames . resolvel (R reI Inv, frame a .tl; zerost3) - frame b .t + Frames .resolvel(R reI inv, frame a .t} + cross(r, frame b .f}, -end if ;end FixedRotation ,
parameter Multi Body . Types . RotationSequence sequence (
Modelica.Mechanlcs.MultIBody.Parts.Body
parameter MUlt iBody .Types .Axis n_x-(l,O,O j "lif rotationType - TwoAxesVectorsl Vector along x-exfe of frame b resolved in frame a" ; parameter Mult iBody .Types:Axis n_y-{O ,I,O) "I if rotationType - TwoAxesVectors I Vector along y -axf s
of
min- (l,l .1), max_13,3,3)} _ (1,2,3) '" if rotationType _ PlanarRotationSequencel Sequence of rotat ions" : parameter Cv .NonSI.Angle_deg anglec(3)-{O,O,O) .. lit rotationType _ PlanarRotationSequencel Rotation angles around the axes defined in ' sequence''';
parameter MultiBody .Type • . ShapeType shapeType -"cylinder"
-IAnimation!if animat ion - true I Type of shape" , parameter SI.Position r_shapeI3J-(O ,O,O) "IAni mat i on l i f animation - t rue ] Vector from frame_a to shape origin , resolved in frame_a" i parameter MultiBody . Types . Ax i s lengthOirection-r ~ r_shape "'Animationl if animation - true I Vector in length d irection of shape , resolved in frame_a"; parameter MultiBody . Types .Axi s widthDirection- (0.1.0) "IAnimationlif animation _ true I Vector i n width direction of shape, resolved i n frame_a" : parameter SI . Length length_Frames . l e ng t h (r ~ r shape) "IAnimationli! an imation - true I Length ot shape" ; parameter 51 .Distance width-I ength/world . de f aul tWidthFraction "IAnimationl it animation - t rue] Width of shape" ; parameter SI .Distance height-width "IAnimation I if animation - true I Height of shape. - ; parameter Real exe ra -e . 0 "IAnimation I if animation • t rue] Additional parameter depending on shapeType (see docu of Visuali zers . Advanced . Shape ) . " I parameter MultiBody . Types . Color color-MultiBody . Types .Defaults . RodColor "IAnimationlif animation - true I color of Bhape" ; Frames . Or i e nt at i o n R rel.if rotationType •• 1 then Frames .planarRotation ( Frames . normal ize (n}, Cv . from deg (angle) else it rotationType -- 2 then Frames .from_IlXY("_X , "_y) else Frames. axes Rotations (sequence, angles) "Fixed relat ive orientation object to rotate from frame a to frame b" J Frames . Or i e nt at i o n R reI inv~Frame8.i nverseRotation (R reI) -"Inverse of R_rel (rotate trom frame_b to frame _a)" ; protected
outer MultiBody .Worlel world; parameter Integer ndim_if world. enableAnimation and animat ion then 1 else 0; Visual! zero .Advanc e d . Shape shape (ndim) ( each shapeType-shapeType ,
..
Rigid body with mass and inertiatensor. All
parameter vectors have to be resolved in frame_a , The inertia tensor has to be definedwith respectto a coordinate
systemthat is parallel to frame_a with the origin at the centerof massof the body. By default,this component is visualized by a cylinder located between frame_a and the centerof massand by a sphere that has its centerat the centerof mass. If the cylinderlengthis smaller as the radiusof the sphere. e.g., since frame_a is locatedat the centerof mass.the cylinderis not displayed. Note,that the animation maybe switched off via parameter animation false. Everybody has potential states. If possible a tool will select the statesof joints and not the statesof bodiesbecausethis is usuallythe mostefficientchoice. In thiscase the position, orientation, velocity and angularvelocity of frame_a of the body will be computed by the component that is connected to frame_a. However, if a bodyis movingfreelyin space, the statesof the bodyhaveto be used.The statesof the bodyare: • The position vectorframe_a.r_O fromthe originof the worldframeto the originof frame_a of the body,resolved in the worldframe. • 3 Cardananglesto rotatealongaxis x of frame"fix" with anglephi[I), alongaxis y with anglephi[2)and finally alongaxis z withanglephi[3]arrivingat frame_a. Frame "fix"is a coordinate systemthat is fixedrelatively to the worldframe. Whenever the Cardananglescomeclose to theirsingularconfiguration. frame"fix"is changed,such that the newCardananglesare far awayfrom their singularity. i.e., a singularconfiguration willneveroccur. The initial values of the Cardananglestates are automatically computed from the initial valuesgivenvia the sequence_start and angles_start values. Since the Cardananglesare definedrelatively to a framefix that is changing duringsimulation, these variables are not very descriptive. It is betterto use the orientation object frame_a.R to get information aboutthe body orientation. • The absolutevelocity v_O of the origin of frame_a, resolved in the worldframe (= der(frame_a.cO».
=
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBody.Parts 831 • The absolute angularvelocity w_aof frame_a withrespect to the worldframe, resolved in frame a. Alternatively, as bodystates4 quaternions can be used insteadof the 3 Cardanangles, by settingparameter useQuatemions in the" Advanced" menuto true.Quatemions do not have a singularconfiguration and therefore no stateevents willoccurduringsimulation, as it is necessary for the Cardan anglesto changethe base frame"fix". The disadvantage of quatemions is that thereis a non-linear constraint equation betweenthe 4 quatemions. Therefore, at leastone non-linear equation has to be solved per bodyduringsimulation. In most cases,the Cardananglechoicewill be moreefficientas the quatemion choice, but theremay be cases wherequatemions are bettersuited. model Body "Rigid body with mass, inertia tensor and one frame connector (12 potential states)" import 51 • Modelica .5Ilmits; import Cv • Modelica. 51. Conversions; Interfaces.Frame_a frame a t r O(start""r 0 start) R(start-R_start) ) ; - -
I
paramet9r Boolean animation-true ". true, if animation shall be enabled (show cylinder and sphere)" ; parameter 51.Position r_CM(3)={0,0,0} "Vector from fr~me_a to center of mass, resolved in frame_a" ; parameter 51.Mass m=l "Mass of rigid body"; parameter 81. Inertia I 11.0.001 "I Inertia tensor (resolved in center of mass, parallel to frame_a) I (l, 1) element of inertia tensor"; parameter 81. Inertia I 22.0.001 .. I Inertia tensor (resolved in center of mass, parallel to frame_a) I (2,2) element of inertia tensor"; parameter 51. Inertia I 33 =0 .001 "I Inertia tensor (resolved in center of mass, parallel to frame_a) I (3,3) element of inertia tensor"; p~rameter 51. Inertia I 21=0 "I Inertia tensor (resolved in center of mass, parallel to frame_a) I (2,1) element of inertia tensor"; parameter SI. Inertia I 31=0 "I Inertia tensor (resolved in center of mass, parallel to frame_a) I (3,1) element of inertia tensor"; parameter SI. Inertia I 32-=0 " I Inertia tensor (resolved in center of mass, parallel to frame_a) I (3,2) element of inertia tensor"; parameter Boolean startValuesFixed=fa1se "I Initialization II '" true, if all start values below &hall be used with fixed.true"; parameter 51. Position r_O_start (3] ={o, (J, o} "f Initialization II Initial values of frame a. r (vector from origin of world frame to origin of frame a resolved in world frame)"; parameter Mul tiBody .Types. Rotation5equence sequence_start .. {I, 2,3} " I Initialization II Sequence of rotationR to rotate world frame into frame_a at initial time"; parameter Cv . NonSI .Angle_deg angles_start [3] -to, 0, o} "I Initialization II Initial values of angles to rotate world frame around' sequence start' axes into frame an. parameter 5I. Velocity v_O_start (3) -(O, 0, 0) , " I Initialization II Initial values of velocity v der(frame a.r 0)"; pa rameter-Multi Body . Types . AngularVeloci ty degs w_O_start [3) a{ O,O,O} Of" I Initialization II Initial values of angular velocity
°
°..
trame_a resolved in world frame"; parameter 81. Diameter sphereDiameter-world. defaul tBodyD!ameter ~ I Animationf if animation - true I Diameter of sphere"; parameter MultiBody. Types. Color sphereColor-MultiBody. Types .Defaults. BodyColor "IAnimationl!f animation - true I Color of sphere"; parameter 81. Diameter cylinderDiameteresphereDiameter/Mul tiBody. Types. Defaul ts. BodyCylinderDiameterFraction " I Animation I if animation. true I Diameter of cylinder";
parameter MultiBody. Types. Color cyl i nderColor-sphereColor "IAnimation I if animation .. true I Coior of cylinder"; parameter Boolean useOuaternions-false "IAdvancedll .. true, if quaternions shall be utilized when body states are requi t'ed (e. 3., when body is moving freely in space)"; parameter Boolean enforceStates=false "IAdvancedll true, if absolute variables of body object shall be used as states"; final parameter S1. Inertia 1[3, 3) = (I 11, 1_21, 1_31 j I 21, 1 22, I 32; I 31, I 32, I 33) "Inertia tensor"; final parameter Frames. Orientation R_start=Frarnea. axesRot8.tions (sequence start, Cv. from_deg (angles_st~rt» "Orientation object from world frame to rrame_a at initial time"; IS
final parameter SI.AngularVelocity w_a_start [3) =Frames. resolve2 (R start, w_O_start* Model ica . Constants. D2R) ; 51. velocity v 0(3) (start=v 0 start) "Absolute velocity of frame i, resolved in world frame"; 51.Acceleration a 0 (3) "Absolute acceleration of framE' a resolved in world frame" i 51.AngularVelocity w a [3; (start=w a start) "Absolute angular velocity of frame- a resolved in frame a"' SI .AngUl~rACceleration z a (3] "Absolute angular acceleration of frame_a resolved in frame a'" 51 .Ac~el~ration g_o [3] "Gravity acceleration resolved in world frame"; protected outer MUltiBody. World world;
1/ Declarations for quaternions (dummies, if quaternions / I are not used) parameter Frames. Ouaternions . Or ienta t ion o start ...F rames. to 0 (R start) "Ouaternion orientation object from world frame to frame a at Ini tial time"; Frames. Ouaternions. Orientat ion 0 (start ..O start) "Ouaternion orientation object from world frama to frame a (dummy value, if quaternions are not used as states)" i II Declarations for Cardan angles (dummies, if cardan angles are not used) constant Real phi2_critical ..Modelica. 81. Conversions. from deg (80) "Change frame base when this angle is reached to avoid Cardan angle singularity": constant Real c2 small ..1.e-S "i f cos (phi [2) ; c2 small then c2 small is used as ~ud against zero di vision" ; 51.Angle phi (3] "Dummy or cardan angles from fram~_fixed (fixed in world) to frame_a of body"; 5I.AngularVelocity phi_d (3] ". der (phi) "; 81.AngularAcceleration phi dd (3) "III der (phi_d) "; Real sl; Real s2; Real s3; Real cl; Real c2a; Real cz , Real c3; Real rl; Real r2; Real phi d 12; Real phi-d-13; Real pili-d-23; Real T_abs13, 3) (start=identity(3}) "Dummy or absolute transformation matrix from world frame to frame_8 of body"; discrete Real T_fixf3, 3] (start-identity(3» "Dummy or T_abs • f (phi) trT_fix"; II Declarations for animation parameter Integer ndiml-ifworld. enableAnimation and animation and cylinderDiameter > then 1 else 0;
°
832 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica parameter Integer ndim2= i f world. enableAnimation and animation and sphereDiameter > 0 then 1 else 0; Visualizers.Advanced.Shape cylinder [ndim1) ( each shapeType="cylinder", each cororxcyt inderColor, each length=if Frames.length(r eM) > sphereDiameter/2 then Frames . length ( -. r_CM) - (if cylinderDiameter > 1.1*sphereDiameter then sphereDiameter/2 else 0) else 0, each width=cyl inderDiameter, each height=cylinderDiameter, each lengthDirection=r eM, each widthDirection= (O~1,0), each r=frame a. r 0, each R=frame-a. R); Visualizers .Ad~anced.Shape sphere [ndim2) ( each shapeType=nsphere", each color::sphereColor, each length=sphereDiameter, each width=sphereDiameter, each height=sphereDiameter, each lengthDirection= (1,0,0), each widthDi rect ion= (0, 1,0) , each r_shape::r_eM - (1,0,0) *sphereDiameter/2, each r=frame a. r 0, each R=frame-a. R), Real TT fix [3, 3)=Frames.to T(R. start); initial-equation if startValuesFixed then frame a.r 0 '" r 0 start, v_O ..-v_o=start7 w a == w a start; if not IsRoot (frame a.R) then / / use equality constraint of orientation object zeros (3) .. Frames .Orientation .equalityConstraint (frame a. R, R start); elseif useQuaternions then I I use quaternions zeros (3) • Frames .Quaternions .Orientation. equalityConstraint (Q, o start); else 1/ use Cardan angles phi = Frames. axesRotationsAngles (R_start, (1, 2,3) ; end if, end if, if isRoot (frame a. R) and not useQuaternions then T fix = Frames. to_T(R_start); else T_fix :: identity(3); end if; equation if enforceStates then Connections. root (frame a.R); else Connections .potentialRoot (frame a. R) , end if; -
elseif useOuaterniona then 1* OUaternions will be used as potential states leading to dynamic state selection during integration
*I
w_a .. Frames .Ouaternions. anguiarVelocity2 (0, der (0» , z a • der (w a); frame a. R ..-Frames. from 0 (0) ; [o] =-Frames. ouaternions. orientationConstraint (0) ; a1 • 0; s2 • 0; s3 • 0; cl = 0; c2 • 0; c2a .. 0; c3 .. 0; r1 -= 0; r2 .. 0; phi • zeros (3) ; phi_d. zeros (3) , phi dd = zeros (3) ; phi=d_12 .. 0; phi d 13 • 0; phi:d:23 • 0; T_abs • identity(3); when initial () then T fix III pre (T fix); end-when; else
o•
Frames .Ouaternions .nullRotation () ;
/ / Cardan angles will be used as states (. minimal coordinates) a1 = Modelica .Math. sin (phi [1]) ; s2 • Modelica.Math.sin(phi[2)); s3 • Modelica.Math.sin(phi [3); c1 .. Modelica.Math.cos (phi [1J); c2a • Modelica .Math .cos (phi [2J) ; c3 .. Modelica.Math.cos (phi (3) ; /* Below, some expressions are divided by c2a. Due to the change of the base frame T fix, it is not possible that c2a-=0, during continuous simulation. However, at initial time, at internal large steps of the integrator, this may occur reSUlting in a division by zero. This is avoided by: - an "assert ( .. )" signals to the integrator to reduce the step size, once the assert conditions become false. - c2 .. c2a if c2a is not zero, and cz is a small value when caa is around zero.
*1
assert (c2a > c2 small or c2a < -c2 small, "Singularity of-actual angle sequence reached. Should not occur"); c2 .. noEvent (if c2a > c2_small or c2a < -c2_small then
I I translational kinematic differential equations
eza else (if c2a >= 0 then c2_small else -c2_small);
/* Absolute transformation matrix from world frame to frame a of body T ibs .. [ c3, s3, 01 -S3, c3, 0, 0, 0, 1) * [c2, 0, -s2;
v 0 = der(frame a.r 0), a=o .. der (v_O) ; -
II rotational kinematic differential equations --------
0, 1, 0;
if not isRoot (frame a.R) then 1/ Body frame is computed somewhere else (variables from else branch are dummies)
s2, 0, c2)*[l, 0, 0; 0, el, s1; 0, -sl, cl] *T fix;
*1-
=
w a
Frames. angularVelocity2 (frame_a. R, der (frame_a. R) ) ; z a .. der (w a); 0-= Frames. Quaterniona. nullRotation () , 0; s1 s2 0; a3 '" 0; cl 0; c2 0; t=
cza '" OJ c3 '" 0; r1 = 0; r2 '" 0; phi. zeros (3) ; phi d '" zeros (3) ; phi- dd = zeros (3) ; phi-d 12 • 0; ph(~d=13 .. 0; phi_d_23 '" 0; T abs .. identity(3); when initial () then T_fix .. pre (T_fix) ; end when;
T_abs
[e2*c3, c1 *s3 + s1 *s2*c3, s1*s3 - cl '*s2*c3; c2*s3, c1*c3 - sl*s2*s3, sl*c3 + c1*s2*s3;
S2, -sl*c2, c1*c2) *pre(T_fix); frame_a.R = Frames.from_T(T_abs); when phi (2) >= phi2_critical or phi [2] phi2 critical then T fix .. Tabs; reinit (phI, zeros (3» ; end when,
/* In the body equations the angular velocity w_a and the angular acceleration Z_8 are needed. One might define w_a • f (phi, der(phi» and then z a • der (w a). In this case w a would be selected as state, if the body is freely moving. Dymola has a special technique for real-time code generation, called mixed-mode integration. The generated code for
Appendix D-Modelica Standard Library Modelica.Mechanics.MultiBody.Parts 833 mixed ~mode integration is usually significantly more etficient , if the formula ti on below is used . wa - ( O. O, p h i d(31) • I c3 , 03, Q ,
-
-
-e3, ca , O.
I
0,
0 , II'(O,phi _d!2J,0) •
ca,
83, 0;
-e3 , ca , 0 ;
e.
O.
II "(e 2 , O. -8 2 ; 0 , I, 0 ,
02 , 0, c 2! -(phi_ dil l ,0,0 )
"
derlphil - phi d, der(phi _dl - phi_dd ; w_a - (03'phi_dI21 • c2'c3'phi_dll) , c 3' p h i _d (2 ) c2's3'phi_dIlJ,phi_dI3) • S2'phi_dII)) ,
"
• der(w al - {s3'phi ddl21 • c2'c3-phi ddlil • c3'phi_d_23 C2·S3*phi_d_13 - s2*c3"phi d 12 , c3'phi dd(2) - c2's3'phi_ddI11 - s3'phi_d_23 C~.C3.phi d 13 + s2*s]*phi d 12. phi_dd 131-.-02'phi _dd 11) • - c2 'phi_d_'2) ;
phi_d_'2 _ phi_dIIJ'phi_d[2) ; phi_d_lJ _ phi_dll) 'phi_dI31 , phi_d_23 _ phi_d(2) 'phi_dIJI ; rl •
1.
a(1)
r2 • z_8(2) -
(c)"phi d 23 - C2*s3"phi d 13 -
s2*c3·phI d 12) ; - ( -s)*phi_d:23 - c2"c3"phi _d_13 • 82"s3"phi_d_12) ;
phi_dd. (c)"rl • s3·r2)!c2 ,s3"rl s2"phi_dd{lJ
+
c3*r2 ,z_a(l) -
- c2 *
phi_d_I2) ; end it ; II end of rotational kinematic dif ferential equations
II gravity acceleration at center o f mas s resolved in world frame 9_0 • world . g r a v i t yAc c e l e r a t i on (frame_a . r _O + Frames . ee ec t ve a (frame_a .R , r_OO); /* Newton/Euler equations with respect t o frame_a - The equations are written witn respect to trame_a , sJnce usually variables at a specific g eome tri c po i nt are better s uited as state var iables , than var ia ble s from the center of mass - The equat t o ns are wr i tten s uch that only one vec t o r (a_O - gO) is transformed from t he world frame to frame_a and not two vectors (8_0 and g_O) . The original equations are : a CH • a a + crOBs (z a , r CM) + crOBB (w-a, CrOSB (w a, [CM) ; f CM • m* a CM - m*g a ; t-CM. I*z-a + crossCw a , I*wa) ; framea.f:fCM frame:=a. t '" t:=CM + crOBS ([ _CH , f_eM) ;
,/
frame_a .t - m*(Frames .resolve2(frame a .R , cross(z a , r CM) + cross (w a, crOBS fw r Ot») : trame a"':t - I*z a -:; croS's(w a , I*wa) + cross irection-r head,
widthDirection. (o-;-1, 0) , s h ap eType." c y l i nde r " I coj.oe-cotor -, r_shape",r_tail , re r , R.R) ,
Visualizers . Advanced . Shape arrowHead1 (
length.h.adLength , width.headlfidth . height-headlfidth. lengthDirect ion.r head ,
widthDire ction. (0-;-1 ,0). shapeType-"cone" , cojorecofor ,
840 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica r _ar rowLine . rvisobj + arrowLine . rxv i Bobj· arrowLine . length , R-R ) , Visuali zerB . Advan ced . Shape l e ngth-hea dLength. width.headlfidth , height_he adWidth , lengthDi re ct i o n_r_ he ad , widthDirect ion- (0 ,1 ,0 I, shapeType.-cone - •
arrowHead~«
color- color, r _a rrowLine . rv iB Obj + arrowLine . rxvf ecb] * (arrowL ine . length . l e ng t h l , R-R) , end DoubleArro",;
+
O. S*arrowHeadl
I'
Modelica.Mechanlcs.MultIBody.Visualizers. Advanced.Shape
LJ
ModelShape definesa visualshape that is shownat the locationof its referencecoordinate system,calIed 'objectframe'below. All describing variables such as size and color can varydynamically. The default equationsin the declarations shouldbe modifiedby providing appropriate equations. ModelShape is usuallyused as a basic buildingblockto implementsimplerto use graphicalcomponents. The folIowing shapes are supportedvia parametershapeType (e.g., shape'Typee'box"),
The dark blue arrowsin the figureaboveare directedalong variablelengthDirection. The lightblue arrowsare directed along variablewidthDirection. The coordinate systems in the figure representframe_a of the Shapecomponent. AdditionalIy, externalshapes are specifiedas DXF-files(only 3DFaceis supported). Externalshapesmust be named "I", "2" etc.. The corresponding definitionsshouldbe in files "I.dxf", "2.dxf" etc.Since the DXF-files containcolorand dimensions for the individualfaces. the corresponding information in the modelis currentlyignored. The DXF-files mustbe foundin the current directory. The following variablesare declared as input. If the default equationis not appropriate, a corresponding modifierequations has to be provided in the modelwherea Shape instanceis used, e.g., in the form Visualizers .Advanced .Shape shape {length • 8in(time))
ou tput Real ryvisobj (3 J · y - ax i s unit vector of shape , resolved in world frame· , output 81 . Position rvis obj 131 "po si t i on vector from world frame to shape frame , resolved in world frame· ; output 81. Length size 131 • (length, width , height) of shape" ; protected output Real Material , o utput Real Ext ra; equat ion /* Outputs to file . */ Form. (987000 + PackShape(shapeType)) -1820 ,
I
model Sh ape -Different v isual shapes with variable size, all data have to be s e t as modifiers (see info layer)" import SI _ Modelica .Slunits , parameter Str ing shapeType-"box" "Type of shape (box, sphere, cylinder, pipecylinder, cone , pipe, beam , gearwheel, spring) ", input Frames . Or i e nt at i on R.MultiBody . Frames . nu llRo t a t i o n () "Orientation object to rotate the world frame into the object frame." , input 81.Position rl31-(O ,o,ol "Position vector from origin of world frame to origin of object trame, resolved in world frame" ; input 8 1.Position r_shape(31_(o,O ,OI "Po s i t i o n vector from origin of object frame to shape origin , resolved in object frame" , input Real lengthDirection13I-(l,O ,O) "Vector in length direction, resolved in object frame ." , input Real widthDirectionl31-(O,l,O) · Ve c t o r in ",idth direction , resolved in object frame ." ; input SI. Length length.O "Lengt h of visual object ." ; input SI. Length width.O "Width of visual object.·, input SI . Leng th he ight.O "Height of visual object.· ; input Re a l extra _O.O ·Additional size data for some of the shape types (details see doeu ) .· , input Real color 131_(255, 0, 0) 'Color (details see doeu) . " ; protected Real rxry [3 , 2J 1 output Real Form,
public output Real rxvisobj 13l · x -a x i s unit vector of shape, resolved in world frame· ,
[ rxvieobj , ryvlsobj J Frames. to exy (Frames . absoluteRotation (R, Frames . frOm_nxy{lengthDirection, widthDirection ))) : +/ rxry • Frames . to exy(Frames . abs o l u t e Ro t at i o n (R , Frames . from_nxy{lengthDirection , widthDirection))) , rxvisobj _ rxry[ " 1) , ryvisobj - r x ry ( " 21 , rvisobj • r + Frames. resolve1 (R. r_shape) , size - (leng th , width , height) , Material - PackMaterial(colorIlI/255 .0, color[21/255.0, color[31/255.0 , 0 .0) , Extra _ extra, end Shape ;
Appendix D-Modelica Standard Library
Modelica.Thermal
Interfaces HeatCapacitor
Components for thermalsystems.
Modelica.Thermal.HeatTransfer This packagecontainscomponents to model I-dimensional heat transferwith lumpedelements. This allowsespeciallyto model heat transferin machines providedthe parameters of the lumped elements. such as the heat capacityof a part. can be determined by measurements (due to the complexgeometries and many materialsused in machines, calculating the lumpedelement parametersfromsome basicanalyticformulas is usuallynot possible). Examplemodelshow to use this library are given in subpackage Examples. For a first simpleexample. see Examples.TwoMasses where two masseswith differentinitial temperatures are getting in contact to each other and arrivingafter some time at a conunon temperature. A morerealisticexampleis providedin Examples.Drive wherethe heatingof an electricalmotoris modelled. see the following screenshot of this example: (examplenot shown) The filled and non-filled red squaresat the left and right side of a componentrepresent thermal ports (connectorHeatPort). Drawinga line betweensuch squaresmeans that they are thermallyconnected. The variables of a HeatPortconnectorare the temperature T at the port and the heat flow rate Q_dot flowing into the component(if Q_dotis positive. the heat flows into the element,otherwiseit flowsout of the element): Model Iee . Slunt t.e •Temperature T "absolute temperature at port I n Ke l v i n "; ModI!l!ca.Slunits .HeatFlowRate Q dot "flow rate at the port in Watt ";
Note, that all temperatures of this package,includinginitial conditions.are givenin Kelvin. For convenience, in subpackagesHeatTransfer.Celsius.HeatTransfer.Fahrenheil and HeatTransfer.Rankinecomponents are providedsuch thai source and sensor information is availablein degree Celsius,degree Fahrenheit. or degreeRankine. respectively. Additionally, in packageSIunits.Conversions conversionfunctions betweenthe units Kelvinand Celsius. Fahrenheit. Rankineare provided. These functions may be used in the following way:
import SI .MQdelica . SIunits l import Modelica .SIunitll .Convflr8ions . •
t
parameter 51 . Temperature T • t'rOfll_degC(2S) ; / / convert 25 degree Celsius to Kelvin
This packagecontainsthe following modelcomponents: ElUU11ples (subpackage) Examples of libraryusage.
841
(subpackage) Interfacedefinitions. Lumpedthermalelementstoring heat.
ThennalConductor Lumpedthermalelement transporting heat withoutstoring it. Convection Lumped thermalelementfor heat convection. BodyRadiation Lumpedthermalelement for radiation heat transferbetween two bodies FixedTemperature Fixedtemperature boundarycondition. PrescribedTemperature Variabletemperature boundary condition FixedHeatFlow Fixedheat flowboundarycondition. PrescribedHeatFlow Variableheat now boundarycondition. TemperatureSensor Absolute temperature sensor. RelTemperatureSensor Relativetemperature sensor. HeatFlowSensor Sensorto determinethe heat flow rate between two ports. Celsius (subpackage) Elements with Celsius interface. Fahrenheit (subpackage) Elements with Fahrenheit interface. Rankine (subpackage) Elements with Rankineinterface. Thereare severalother components available, such as AxialConduction (discretized PDE in axial direction), which have been temporarily removedfrom this library. The reason is that thesecomponents referencematerialproperties, such as thermalconductivity. and currentlythe Modelicadesign group is discussinga generalscheme to describematerialproperties. For technical detailsin the designof this library,see the following reference: Michael Tiller (2001): Introduction to PhysicalModeling with Modelica. K1uwer Academic Publishers Boston. ReleaseNotes: July 15,2002 by MichaelTiller, Martin Otter and Nikolaus SchUrmann: Implemented. Acknowledgements: Severalhelpfulremarksfrom the following persons are acknowledged: John Batteh,Ford Motors,Dearborn,U.S.A; AntonHaumer, Technical Consulting & ElectricalEngineering, Austria;LudwigMarvan,VA TECHEUN EBG Elektronik GmbH,Wien, Austria; HansOlsson.DynasimAB, Sweden; Hubertus Tumrnescheit, Lund Instituteof Technology, Lund, Sweden. Copyright@2001-2002. Modelica Association, MichaelTiller and DLR. This Modelicapackageis free software;it can be redistributed and/or modified underthe termsof the Modelicalicense,see the licenseconditionsin the frontpagesof this book.
842 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Modelica.Thermal.HeatTransfer.lnterface
Modellca.Thermal.HeatTransfer.lnterfaces.HeatPort
s
Thennal port for l-dim. heat transfer
Modellca.Thermal.HeatTransfer.lnterfaces.HeatPort_a
Thermal port for I-dim. heat transfer (filled rectangularicon) This connector is used for I-dimensional heat flow between components. The variables in the connectorare: T O_dot
Temperature in IKelvin) . Heat flow rate In (Watt) .
Accordingto the Modelica sign convention,a positive heat flow rate Q_dot is considered to flow into a component.This convention has to be used whenever this connectoris used in a model class. Note, that the two connector classes HeatPort_aand HeatPort_b are identical with the only exception of the different icon layout. connector H@atPort_a
IIThermal port for l·dlm . heat transfer (filled rectangular
icon ) • extends HeatPorti end HeatPort_a;
Modellca.Thermal.HeatTransfer.lnterfaces.Element1 0
Partial heat transferelement with two HeatPortconnectors that do not store energy. This partial modelcontains the basic connectorsand variables to allow heat transfer models to be created that do not store energy, This model defines and includesequations for the temperature drop across the element, dT, and the heat flow rate through the element from port_a to portb, Q...dot. By extending this model. it is possibleto write simple constitutive equations for many types of heat transfer components. p a rtial model El ementlD
·Partial heat transfer element
with two HeatPort connectors that does not store energy · 51 .HeatFlowRate 0 dot "Heat flow rate-from port_a - > port_b- : 51 .Temperature dT ·port_s .T. port_b .T· ; public HeatPort a port a ;
Heat Port -b port-b; equation -
dT. port_B .T - port_b.T;
port a .O dot. 0 dot ; port-b .O-dot • -0 dot ; end ElementlD, -
Modellca.Thermal.HeatTransfer.lnterfaces.HeatPort_b
Thermal port for l-dim. heat transfer (unfilled rectangularicon) This connector is used for l-dimensional heat flow between components. The variables in the connectorare: T O_dot
Temperature in (Kelvin) . Heat floW' rate in IWattJ .
According to the Modelica sign convention,a positive heat flow rate Q_dot is considered to flow into a component.This convention has to be used whenever this connectoris used in a model class. Note, that the two connector classes HeatPort_aand HeatPort_b are identical with the only exception of the different icon layout. connector HeatPort_b icon) " extends HeatPort ; end HeatPort_b ,
·Thermal port tor i-dim . heat transfer (unfilled rectangular
partial connector HeatPort "Thermal port for l -d im . heat transfer " 51 . Temperature T ·Port temperature ", flow 5I.HeatFlowRate 0 dot "Heat flow rat e (posItive if fl owing from outside into the component) "; end HeatPort J
Modellce,Thermal.HeatTransfer.HeatCapacltor
Lumped thermalelement storing heat This is a generic model for the heat capacity of a material. No specific geometry is assumed beyond a total volumewith unifonn temperature for the entire volume. Furthermore, it is assumed that the heat capacity is constant (independentof temperature). The temperatureT [Kelvin]of this component is a state. A default of T = 25 degree Celsius (= Slunits.ConversionsJrom_degC(25» is used as start value for initialization. This usually means that at start of integrationthe temperatureof this component is 25 degrees Celsius. You may, of course, define a different temperatureas start value for initialization. Alternatively. it is possible to set parameter steadyStateStartto true. In this case the additional equation 'der(T) =0' is used during initialization,i.e., the temperatureT is computed in such a way that the component starts in steady state. This is useful in cases. where one would like to start simulation in a suitable operatingpoint without being forced to integrate for a long time to arrive at this point. Note. that parametersteadyStateStartis not available in the parameter menue of the simulation window, because its value is utilizedduring translationto generatequite different equations dependingon its setting. Therefore, the value of this parameter can only be changedbefore translating the model. This componentmay be used for complicated geometries where the heat capacityC is determined my measurements. If the componentconsists mainlyof one type of material, the mass m of the component may be measured or calculated and multipliedwith the specificheat capacity cp of the component material to computeC: Typical values for cp at 20 degC in J/(kg.K): aluminium concrete copper iron silver steel wood
896 841 0
383 452
:235 420 . •• 500 (V2AI 2500
model HeatCapacitor " Lu mped thermal element storing heat" parameter Sl.HeatCapacity C "Heat capacity of part f. cp.m) ", parameter Boolean steadyStateStart-talse "true, if component shall start in steady state", 51 . Temperature T (start.trom._degC (25)) ·Temperature of part" , Interfaces . HeatPort_a port, equation T. port.T; C·der(T) • port .O_dot ; initial equation if steadyStateStart then der(T) • 0 ; end if ; end HeatCapaci tor ;
Appendix D-Modelica Standard Library Modelica.Thermal.HeatTransfer.Interfaces 843 v , Air velocity in ImlBJ
Modellca.Thermsl.HestTrsnsfer.ThermslConductor
a
Lumpedthermalelement transporting heal without storingit
ThermalCon...
0-
Laminarflowwith constant velocityof a fluid along a nat plate where the heat flow rate from the plate to the fluid (= solid.Q_dot)is kept constant(accordingto lP.Holman : Heat Transfer.8th edition. McGraw-Hili. 1997.p.270): h
This is a modelfor transportof heat withoutstoring it. It may be used for complicated geometries where the thermalconductance 0(= inverseof thermalresistance) is determined by measurements and is assumedto be constant over the range of operations. If the componentconsists mainlyof one type of materialand a regulargeometry, it may be calculated,e.g., with one of the following equations: Conductance for a box geometry under the assumption that heat flowsalong the box length: G • "·A/L k : Thermal conductivity (material c o nstant) A: Area of box L : Length of box
G • 2*pi *k*L/log (r_out/r_ln)
Modelica .cons eanee . p i Thermal conductivity (material constant) Length of cyl inder log Modelica .Hath .log , rout : OUter radius of cyl inder r~)n : Inner radius of cyl inder
pi
k L
Typical values for k at 20 degC in W/(m.K):
wood
where h Heat transfer c o e f fi c i e nt (Nusselt number) Nu • h·x/k = v-x-rho/mue (Reynolds number) Re (Prandtl number) Pr .. cp-mue /k Absolute velocity of fluid v x distance from leading edge of flat plate rho , density of fluid (material constant mue: dynamic v iscosity of fluid (material constant) cp : specific heat capacity of fluid (material constant) k : thermal conductivity of flu id (mater-ial constant)
and the equation for h holds.provided Re < 5e5 and 0 .6 < Pr e 50
Conductance for a cylindricalgeometryunder the assumption that heat flowsfrom the insideto the outsideradius of the cylinder:
aluminium concrete copper iron silver steel
• Nu·k/x ; Nu.0 .45 3·Re'1l/2)·Pr·1l /3I ,
220 1
364 14
407 45 . . 15 (V2AI 0 .1 .. . 0.2
model ThermalConductor "Lumped thermal element transporting heat without storing it"
model Convection
"Lumped thermal element for heat conve cti on" SI . ThermalConductance Gc "Conv e c t i ve thermal conductance of element" ; S I. He at Fl owRa t e 0 dot "He at flow rate-from 801id ~> fluid" ; S I. Te mpe r a t ur e dT ". solid .T - tluid .T" ; Model iea . Blocks . Interfaces . RealInput G( redeclare type SignalType • 81 .ThermalConductance) "S i g nal representing the convective thelmal conductance in tW/K)" , In terfaces .He at Po r t a solid ; Interfaces .He a t Po r t -b fluid ; equation Gc • G, dT . solld .T - fluid .T , solid .O dot . 0 dot ; flu ld .Q-dot • -0 dot , a dot . -Cc-dT ; end-Convect ion ;
Modelics.Thermal.HestTrsnsfer.BodyRsdlatlon
extends Interfaces . ElementlD ;
parameter SI. ThermalConductance G "Constant thermal conductance of material " 1 equation o dot. G*dT; end- ThermalConductor ;
Modellcs.Thermsl.HestTrsnsfer.Convection
~
i
Lumpedthermalelementfor radiationheat transfer This is a modeldescribingthe thennal radiation,i.e.• electromagnetic radiation emitted betweentwo bodiesas a resultof their temperatures. The following constitutiveequationis used: :::
O_dot ... Gr· sigma· (port_B .T .... . - port_b .T.....) ;
#
Lumpedthennal elementfor heat convection ] s, -~-w, This is a modelof linear heat convection. e.g.• the heat transferbetweena plate and the surroundingair. It may be used for complicated solid geometries and fluid flowover the solid by detennining the convectivethennal conductance Gc by measurements. The basic constitutive equationfor convection is I
] ".i11'
Q_dot • Gc·(Bolld .T - fluld .TI,
o dot :
Heat flow rate trom connector ' s o l i d ' (e .g . a
plate) to connector ' f l u i d ' (e .g . the surrounding air)
=
O.signal[IJ is an input signal to the component, since Gc is nearlyneverconstant in practice, Forexample. Gc may be a functionof the speed of a cooling fan. For simplesituations.Gc may be calculatedaccordingto
Gc
nc •
A·h
A: Convection area (e.g . perimeterfl'length of a box) h : Heat transfer coefficient
wherethe heat transfercoefficienth is calculatedfrom properties of the fluid flowing over the solid. Examples: Machinescooledby air (empirical.veryrough approximation accordingto R. Fischer: ElektrischeMaschinen, lOthedition. Hanser-Verlag 1999.p. 378): h • 7 . s·v .... O. 78 [WI (m2. X) J (forced convection) • 12 (III 1m2. K) J (free convection) where
whereGr is the radiation conductance and sigma is the StefanBoltzmann constant (= Modelica.Constants.slgma). Or may be determined by measurements and is assumedto be constantover the rangeof operations. Forsimplecases. Or may be analytically computed. The analytical equationsuse epsilon.the emission valueof a body whichis in the range 0..1. Bpsilone l, if the bodyabsorbsall radiation (= blackbody). Epsilon~. if the body reflects all radiation and does notabsorbany. Typicalvaluesforepsilon: alum inium, polished copper. polished gold , polished paper rIJ1,ber silver, polished wood
0 .04
0 .04 0 . 02 0 .09 0 .95 0 .02 0 .65 .. 0 .9
Analytical Equations for Gr Smallconvexobject in largeenclosure(e.g., a hot machinein a room) :
where e : Emission value of object CO . . ll A: Surface area of object where radiation heat transfer takes place
Two parallelplates:
844 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica Gr • A/ (I/e1 + 1/e2 •
Modelica.Thermal,HeatTransfer.PrescrlbedHeatFlow
1)
where et: Emission value of platel CO . . 1) e2 : Emission value of plate2 CO . . 1) A : Area of pla.tel (. area of plate2)
Two long cylinders in each other, where radiation takes place from the inner 10 the outer cylinder): Gr • 2' pi 'r1'L/ (I/e1 , U/e2 -
1)'
(r1/r211
where pi : rl : r2 : L : el : e2 :
• Modellca .Constants .pi Rad ius of inner cylinder Radius of outer cylinder Length of the two cyl indl!rs Emission value of inner cylinder (0 . . 1) Emission value of outer cylinder (0 . , 1)
model BodyRadiation "Lumped thermal element for radiation heat transfer" extends Interfaces . ElementlD;
~o Prescribedheat flow boundary condition
This model allows a specified amount of heat flow rate to be "injected" into a thermal system at a given port. The amount of heat is given by the input signal into the model. The heat flows into the component to which the component PrescribedHeatFiow is connected, if the input signal is positive. model PrescribedHeatFlow "Prescribed heat flow boundary condition " Modelica . Bl oc ks . Interfaces . Reallnput 0 dot I Interfaces.HeatPort_b port , equation port.o dot · -0 dot ; end PrescribedHeatFlow;
Modellca.Thermal.HeatTransfer.TemperatureSensor
parameter Real Gr(unit_"m2") "Net radiation conductance between two surfaces (s ee docu) II;
equation O_dot • Gr·Modelica . Co ns t a nt s . sigma· (port_a. T A4 port_b.T"'4) ; end BodyRadiation ,
Modellca.Thermal.HeatTransfer.FlxedTemperature
Fixed temperatureboundarycondition in Kelvin. This model defines a fixed temperatureT at its port in Kelvin, i.e., it defines a fixed temperatureas a boundarycondition. model FixedTemperature " Fi xed temperature boundary. condition in Xelvin" parameter 51 .Temperature T "Fixed temperature at port" ; Interfaces .HeatPort_b port ; equati on port.T . T, end FixedTemperature ;
Modellca.Thermal.HeatTransfer.PrescrlbedTemperatur
e Variable temperatureboundarycondition in Kelvin. This model represents a variabletemperature boundarycondition. The temperaturein (K) is given as input signal to the model. The effect is that an instance of this model acts as an infinite reservoir able to absorb or generateas muchenergy as required to keep the lemperatureat the specified value. model prescribedTemperature "Variable temperature boundary condition in Xelvln" Interfaces . He a t Por t _b port: Model l ea . Blocks . Interfaces. Real Input T(redeclare type SignalType • SI . Temperature) i equation port .T. T ; end PrescribedTemperature ;
Modellca.Thermal.HeatTransfer.FlxedHeatFlow
.--===t
o Fixed heat flow boundary condition This model allows a specifiedamount of heat flow rate to be "injected" into a thermal system at a given port.
The constant amount of heat flow rate Q..dot is given as a parameter. The heat flows into the component to which the component FixedHeatAow is connected, if parameterQ..dot is positive. model FixedHeatFlow ·Fixed heat flO'tf boundary condition· parameter SI .HeatFlowRate 0 dot "Fixed heat flow rate at Port"; Interfaces . HeatPort_b port ; equation
port .O_dot • -O_dot; end FixedHeatFlow;
Absolutetemperature sensor in Kelvin This is an ideal absolute temperature sensor which K returns the temperatureof the connected port in Kelvin as an output signal. The sensor itself has no thermal
f-:
• .._-
interactionwith whateverit is connected to. Furthermore, no thermocouple-like lags are associated with this sensor model. model TemperatureSensor "Abs o l ut e temperature sensor in Kelvin'" Model iea . Blocks . Interfaces . RealOutput T ( redeclare type SignalType • 51. Temperature) ,
Interfaces .Hea t Por t a port; equation T . port .T ; porLO dot. 0; end Temperaturesensor;
Modellca.ThermaI.HeatTransfer.ReITemperatureSenso
r
. -nt-aRelative Temperaturesensor ~ The relative temperature "port_a.T - port_b.T" is detennined between the two ports of this component and is providedas output signal in Kelvin. model RelTemperatureSensor '"Relative Temperature sensor '" extends Model Ice . Icons .TranslationalSensor, Interfaces . He a t Po r t _ a port_a; Interfaces . HeatPort_b port_b; Modelica . m c c k s • Interfaces . RealOutput T reI ( redeclare type SlgnalType - 51 . Temperature) ; equation T_rel • port_s . T - port_b . T ; a • port a .O dot , a • port-b .O-dot , end RelTemPeraturesensor,
Modellca.Thermal.HeatTransfer.HeatFlowSensor
•
port b" , Interfaces . Ne a t Po r t a port A; Interfaces . Ne &t Por t =b port:b, equation port_o . T • port_b . T; port 0.0 dot + port b .O dot. 0, O_dot • Port_o .O_dot, -
Appendix D-Modelica Standard Library Modelica.ThermaI.HeatTransfer.Examples 845 heat. 0 dot ; end HeatFlowSensor ;
Model/ca.Thermal.HeatTransfer.Exampl es Example models to demonstrate the usage of package Modelica.Thennal.HeatTransfer
Modellca.Thermal.HeatTransfer.Examples.TwoMasses mast 1
'7 ' -Fe
",.., 2
Simple conduction demo This example demonstrates the thennal response of two masses connected by a conducting element. The two masses have the same heat capacity but different initial temperatures (T1=IOO [degC). T2= 0 [degC)).
The mass with the higher temperaturewill cool off while the mass with the lower temperature heats up. They will each asymptotically approach the calculated temperatureT_finaLK (T _finaLdegC) that results from dividing the total initial energy in the system by the sum of the heat capacities of each element. Simulate for 5 s and plot the variables rnass l .T, mass2.T, TJmal_K or Tsensorl .T, Tsensor2.T. T_final_degC encapsulated model TwoMasses "Simple conduction demo" import Modelica .Icons; import Modelica . Thermal .HeatTranster ; import sr • Modelica .SIunits , import Modelica . S t uDi t s . Conversions . • ; import NonSI • Modelica ,Slunits . Cofiversions .NonSIunits i extends Icons . Example ; parameter 51 . Temperature T_f inal _K(fixed -false ) ·Projected tinal temperature" ; parameter sensr , Temperature_degC T final degClfixed.falsel - "Proj e c t ed final temperature "; HeatTransfer .He at Capac i t o r massl (C=IS , TIstart .from degC(lOO))) ; HeatTransfer .HeatCapacitor mass2 (C=I5, T(start_from_degC(O)}} J Heat Transfer. ThermalConductor conduction (G=10) ; HeatTranster .Ce l s i u s . TemperatureSensor Tsensorl ; HeatTransfer .Celsius . TemperatureSensor Tsensor2; equation connect (massl . port , c onduction . port a) ; connect (conduction . po rt _ b , mass2 . port) ; c onne c t (massl . port , Tsensori .port) ; connect (m3ss2 . po rt , Tsensor2. port) 1 initial equati on T_final_K _ (massl .p ort .T.masBl.C + maBs2 .po rt . T'lnaS82 . C) I (mas81 .C + maB82. C) ; T_final_degC = to_degC( T_final_X) ; end TwoMasses :
Modellca.Thermal.HeatTransfer.Examples.Frequency! nvertar First order thennal model of a frequency inverter This example contains a simple first order thennal model of a frequency inverter. The periodic power losses in the frequency inverter are described by two tables. "conduction'Fable" describes the convection conduction G and "lossTable" the generated power loss P_loss dependent on the time, The power dissipation to the environment is approximated by heat flow through a thermal conductance.partially storage of the heat in a heat capacitor and fmaUy by forcedconvection to the environment.defined in the two tables. Simulate for 5 s and plot the heat flow rate and the temperature in the frequency inverter. encapSUlated model Frequencylnverter I'First order thermal model of a frequency in verter "
import Model ica.Icons ; import Madelica . Blocks . Sources; import Model ica .Thermal . HeatTranster 1 import SI e Modelica .Slunits ; impor t Modelica . SIunits . Conversions .· : e xtends t cons . Example ; Sources. TimeTable conducti onTable (table., (0 , 0 .001 ; 1 , 0 .014 ; 2 , 0 .00 7;
3 , 0.014, 4. 0.00 7; 5 . 0.014) ; Sources . TimeTable reeeracr e (table(0 , 10000 ; I, 7000 ; 2 , 10000 1 3, 1000 ; 4, 10000 , 5. 70001) ; HeatTransfer. HeatCapac itor C (C-lOOOO) I HeatTransfer . Celsius . TemperatureSensor TsensoL·; HeatTranster . ThermalConductor G lG-SO) 1 HeatTransfer . Convection convection ; HeatTransfer. PreE'cribedHeatFlow 0 dot; HeatTransfer . c eae Iue . FixedTemperature en vironment (T-20t ; equation connect (O_dot . po r t. , G.port_a) ; connect (O_dot .port , Tsensor . po r t ) : connect(G.port b , convection . solid. ) 1 connect(c.port"; G.pore b) ; co nne c t (en v ironment . port , convection . tluid) ; connect (lossTable .y . O_dot .O_dot) I connect (conductionTable -v, coevece ton. m , end Frequencylnverter ;
Modellca.Thermal.HeatTransfer.Examples.ControlledT emperature
"..A.
Control temperatureof a resistor A constant voltageof 10 V is ., ... ,- applied to a temperaturedependent ...... resistor of 10*(1+(TI • 2OC)I(235+2OC» Ohms. whose losses v**2Jrare dissipated via a thermal conductanceof 0.1 WIK to ambient temperature20 degree C. The resistor is assumed to have a thermalcapacity of I 11K. having ambient temparatureat the beginningof the experiment.The temperature of this heating resistor is held by an OnOff-conlrollerat reference temperature within a given bandwith +1- I K by switching on and off the voltagesource. The reference temperature starts at 25 degree C and rises between t =2 and 8 seconds linear to 50 degree C. An approppriatesimulating time would be 10 seconds. .- !9
.
~ --
~
lO_ . •
encapsulated model ControlledTemperature "Control temperature of a res istor" import Modelica . Icons ; import Model iea . Blocks . Sources ; import Modelica . Electrical .Analog; import Modelica .Thermal . HeatTransf er: import 51 - Modellca .Slunits; i mpo r t NonSt • MOOe1ica.SIunits.Conversions.NonSlunits ; import Modelica . S l un i t s . Conve rs i ons. ·; extends I cons . Example ; parameter NonSI . Temperature_degC TAmb..20 "Amb i ent Temperature" ; parameter NonSI. Temperature_degC TOi£-2 "Er ro r in Tempe rat ure "; output NonSI . Temperature_degC TRee "Resulting Temperature" ; Analog .cas i c .Ground Groundl; Analog . Sourc e s . ConstantVoltage ConstantVoltagel (V.lO) ; HeatTranster . He at Capac i t o r HeatCapacitor1 (C.l, TIBtart.from degC(T~mbl)) ; Analog . Bas ic . J.te at i ng Re s i s t o r HeatingRes istor1 ( R ref .lO , T- ref.from degC(20) , alpha.l / (235 + 20)) ; HeatTransfer . Celsius . FixedTemperature FixedTempBraturellT.TAmbl , HeatTranst'er . Ce l s i us. TemperatureSensor TemperatureSensorl ; HeatTranster . ThermalConductor ThermalConductorl (0.0 .1) ; SwitchController SwitchControllerl Ib a ndwi d t h . rolf ) ; Analog . Ideal. IdealSwitch IdealSwitchl ; Sources . Ramp Ramp! ( height . 25. duration-6, oftset - 25 , startTime-2) ; encapsulated block SwltchController "On-off controller for use with Modelica . Blectrical .Analog . Ideal . IdealSwitch" import Modellca .Blocks l extends Blocks . Interfaces . SI2BooleanSO; parameter Real bandwidth_O .1
846 Peter Fritzson Principles of Object-Oriented Modeling and Simulation withModelica IIBandwidth around reference signal"; protected Real u=u2 "Input signal II ; Real uRef..ul "Reference input signal II ; equation y = (u > uRef + bandwidth/2) or (pre (y) and not (u < uRef - bandwidth/2»; end SwitchControl1er; equation connect (ConstantVo1tagel.n, HeatingResistorl.n); connect (ConstantVoltagel.n, Groundl.p); connect (HeatingResistorl.heatport, ThermalConductorl.port_a) ; connect (ThermalConductorl.port b, FixedTemperaturel.port) ; connect (HeatingResistorl.heatport, TemperatureSensorl.port) ; connect (HeatingResistorl. heatPort, HeatCapacitorl.port) ; connect (TemperatureSensorl . T, Swi tchControllerl . u2) ; connect (ConetantVoltagel.p, IdealSwitchl.p); connect (IdealSwitchl. n, HeatingResistorl. p) ; connect (SwitchControllerl. ul, Rampl. y) ; connect (Swi tchContro11erl . y. IdealSwi tchl . control) ; TRes • to_degC(HeatingResistorl.heatport. T) ; end Control1edTemperaturei
Modellca. Thermal.HeatTransfer.Examples.ControliedT emperature.SwitchController
On-off controller for use with Modelica.Electrical.Analog.ldeal.ldeaISwitch The block SwitchControllersets the output signal to false when the input signal falls below the referencesignal minushalf of the bandwidthand sets the output signal to true when the input signal exceeds the referencesignal plus half of the bandwidth. The reference signal is representedby uland the input signal by u2. Note: This componentwin be removed when package ModeIicaAdditions.BJocks.Logical is incorporatedinto the ModelicaStandard library. encapsulated block switchController "On-off controller for use with Modelica. Electrical.Analog. Ideal. Idea1Switch" import Modelica.Blocks; extends Blocks. Interfaces .S12BooleanSO; parameter Real bandw.idth.O. 1
"Bandwidth around reference signal"; protected Real u=u2 II Input signal" 1 Real uRef-ul "Reference input signal"; equation y .. (u > uRef + bandwidth/2) or (pre (y) and not (u < uRef - bandwidth/2»; end Swi tchController;
ModelicaAdditions Main Author:Martin Otter. Copyright(C) 1999-2000, ModelicaAssociationand DLR. The Package ModelicaAdditions is a collectionof libraries which is supplied by DLR (DeutschesZentrum fUr Luft- und Raumfahrt) to provideoften neededcomponentswhich are missingin the Modelicastandardpackage. It is planned to move the componentsof package ModelicaAdditions in an improved fonn to a future versionof package Modelica. In the subpackagesof ModelicaAdditions it is explained why the corresponding sublibraryis not yet included in package Modelica, The ModelicaAdditions package is free softwareand can be redistributed andlor modifiedunder the terms of the Modelica License. The ModelicaAdditions package currently(Sept 2(03) consists of the following subpackages: Blocks Additional input/outputcontrol blocks, soon to be integratedwith Modelica.Blocks.
HeatFlowlD l-dimensional heat flow. A libraryreplaced by the Modelica.Thennal and Modelica.Fluid libraries. MultiBody 3D-mechanical systems- old version ot the MultiBodylibrary, that now has been replaced by Modelica.MultiBody, but still is in use by a large number of applications, and probablywill continue to be used for several years in old applications. Infonnationabout the old MultiBody libraryis availableon the book web page www.DrModelica.org and on the ModelicaAssociationweb page www.Modelica.org. PetriNets Componentsto modelsimple state machinesand Petri nets, largelymade obsoleteby the ExtendedPerriNests library. Tables Linearinterpolation in one and two dimensions.Table data may be read from file.
847
Appendix E-Modelica Scripting Commands
The following are short summaries of scripting commands for three different Modelica environments: • • •
OpenModelica lvlathModelica Dymola
These commands are useful for loading and saving classes, reading and storing data, plotting of results, and various other tasks. The arguments passed to a scripting function should follow syntactic and typing rules for Modelica and for the scripting function in question. In the following tables we briefly indicate the types or character of the formal parameters to the functions by the following notation: • • • • •
String typed argument, e.g. "hello", "myfile.mo". TypeName - class, package or function name, e.g. MyClass, Modelica. Math. VariableName - variable name, e.g. v L, v2, varsl [2] .x, etc. Integer or Real typed argument, e.g. 35,3.14, xintvariable. options - optional parameters with named formal parameter passing.
OpenModelica and MathModelica Modelica Scripting Commands The following are brief descriptions of the most common scripting commands available in the OpenModelica environment as well as in Modelica command cells in the MathModelica environment. animate (className, options}
Display a 3D visaulization of the latest simulation. Inputs: TypeName className; Outputs: Boolean res;
cd(dir)
Change directory. Inputs: String dir; OU~UU:Boolean res;
checkModel{className)
Instantiate model, optimize equations, and report errors. Inputs: TypeName className; Outputs: Boolean res;
claar ()
Clears everything: symboltable and variables. OU~U~:Boolean res;
clearClasses()
Clear all class definitions from symboltable. OU~U~:Boolean res;
clearLog ()
Clear the log. Outputs: Boolean res;
clearVariables()
Clear all user defined variables. Outputs: Boolean res;
closePlots()
Close all plot windows. Outputs: Boolean res;
getLog()
Return log as a string. Outputs: String log;
instantiateModel(className}
Instantiate model, resulting in a . mof file of flattened Modelica. Inputs: TypeName className; OU~U~:Boolean res;
848 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica list (className)
Print class definition. Inputs: TypeName className; Outpu~:String
classDef;
listVariables()
Print user defined variables. Outputs: VariableName res;
loadFile(fileName)
Load models from file. Inputs: String fileName Outputs: Boolean res;
loadModel(className)
Load the file correspondingto the class, using the Modelica class name to file name mapping to locate the file. Inputs: TypeName className Outputs: Boolean res;
plot (variables, options)
Plots vars, which is a vector of variable names. Inpu~:VariableName
variables; String title; Boolean legend; Boolean gridLines; Real xrange [2] i.e. {xmin, xmax} ; Real yranqe Iz l i.e. {ymin,ymax}; OU~U~:Boolean res;
plotParametric(variablesl, variables2, options)
Plot each pair of correspondingvariables from the vectors of variables varsl, vars2 as a parametric plot. Inpu~:variableName variablesl[:]; VariableName variables2[size(variablesl,l)]; String title; Boolean legend; Boolean gridLines; Real range[2,2]; OU~U~:Boolean res;
plotVectors(vl, v2, options) Plot vectors vl and v2 as an x-y plot. Inputs: VariableName vl; variableName v2; OU~U~:Boolean res; readMatrix(fileName, Read a matrix from a file given filename and matrixname. matrixName) Inpu~:String fileName; String matrixNamei OU~U~:Boolean
matrix[:,:];
readMatrix(fileName, Read a matrix from a file, given file name, matrix name, #rows matrixName, nRows, nColumns) and #columns. Inputs: String fileName; String matrixName; int nRows; int nColumns; Ou~u~:Real res [nRows,nCo!umns] ; readMatrixSize(fileName, matrixName)
Read the matrix dimension from «file given a matrix name. Inpu~:String
fileName; String matrixName; sizes[2];
Ou~u~:Integer
readSimulationResult( fileName, variables, size)
Reads the simulation result for a list of variables and returns a matrix of values (each column as a vector or values for a variable.) Size of result is also given as input. Inputs: String fileName; VariableName variables[:]; lnteger size; Ou~ut~Real res[size(variables,l),size}];
readSimulationResultSize( fileName) runScript(fileName)
Read the size of the trajectory vector from a file. Inputs: String fileName;
Outpu~:Integer
Executes the script file given as argument. Inpu~:String
saveLog(fileName)
size;
fileName;
OU~U~:Boolean
res;
OU~U~:Boolean
res;
Save the log to a file. Inpu~:String
fileName;
saveModel(fileName, className)
Save class definition in a file. Inputs: String fileName; TypeName className Outputs: Boolean res;
saveTotalModel(fileName, className}
Save total class definition into file of a class. Inputs: String
Appendix E-Modelica Scripting Commands 849 fileName; TypeName className Outputs: Boolean res; simula te (className, opt ions) Simulate model, optionally setting simulation values. Jnpu~:TypeName
classNamei Real startTime;
Real stopTime; Integer numberOfIntervals; Real outputlnterval; String method; Real tolerance; Real fixedStepSize; Outputs: SimulationResult simRes; system (f ileName)
Execute system command. Inputs: String fileName; Outputs: Integer res;
translateModel(className)
Instantiate model, optimize equations, and generate code. Inputs: TypeName className; Outputs:SimulationObject res;
writeMatrix(fileName, matrixName, matrix)
Write matrix to file given a matrix name and a matrix. Inpu~:String
fileName; String matrixName; Real matrix[:,:]; OU~UU:Boolean res;
Examples The following session in OpenModeIicaillustrates the use of a few of the above-mentioned functions. »
»
model test Real x; end test; OK
translateModel(test) SimulationObject record flat, exeFile="test.exe" end record; » a:=1:10 » »
{1,2,3,4,S,6,7,S,9,10} a*2 {2,4,6,S,lO,12,14,16,lS,20}
clearVariables() true » list(test) "model test Real X; end test; clear () true » getClassNames() {}
>:>
The common combination of a simulation followed by a plot: >
translateModel{mycircuit);
> simulate (stopTime=10.0) ; >
plot ( {Rl . v }) ;
850 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Mathematica-style MathModelica Scripting Commands The following table contains a selected subset of the specific Mathematica-style MathModelica scripting commands expressed in Mathematica syntax. In addition to these, almost a thousand Mathematica commands are available. Moreover, the OpenModelica scripting commands in Modelica syntax style are also available in MathModelica as a Modelica-syntax alternative. Clear [ [var s }I , ClearAll[]
Clear all variables.
ClearSymbolTable[]
Clears everything, i.e, AST (abstract syntax trees in workspace) together with possible user-defined variables.
ClearSymbolTable[]
Clear all class definitions.
Directory []
Get current working directory.
GetRawSimulationData[ variable]
Reads the simulation result for a variable and return a vector of values.
GetRawSimulationTimeData[]
Returns the raw time data vector from the simulation.
ListModelNames[class] Lists all model names in class if class is present in memory. ListPlotSimulation[ Plots a list of values with specified x and y coordinates. {{xII, yl1 } , {x12, yI2 } , ...}] ListPlotSimulation3D[{{xl1,y Plots a list of values with specified x, y and z coordinates. 11,zll},{xI2,y12,ZI2},~})
LoadSimulationData[filename] Loads the simulation result stored in filename into memory and returns a SimulationData object as a reference. MathModelicaConfiguration[ Sets the configurations of the MathModelica system and stores options...] the settings in "Conf ig . m" in the MathModelica root directory. ParametricPlotSimulation[ {fx,fy},{t,tmin,tmax}J
Produces a parametric plot with x and y coordinates [x and fy generated as a function of t.
ParametricPlotSimulation3D[ Produces a three-dimensional space curve parameterized by a {fx,fy},{t,tmin,tmax}J variable t, which runs from tmin to tmax. PlotSimulation[f, Plot one or more variables as functions of time. {t, tmin, t.max}] PrintDefinition[classJ Returns the definition of class in a new cell. PrintDiagram[class]
Returns the diagram of class in a new cell.
PrintDocumentation[classl
Returns the documentation of class in a new cell.
Printlcon[classl
Returns the icon of class in a new cell.
SaveSimulationData[ filename.mat,simdatal SetDirectory[string]
Saves the SimulationData object simdata on the file filename. mat. Change current working directory.
SetOption[s, namel->vall, name2->va12, ...l SetSymbolizeableSymbols[ {sl,s2, ...}J
Set default values for any Mathematica command.
ShowBuildLog []
Displays the build log for the last simulation.
ShowDefinition[class]
Will open a notebook showing the definition of class.
ShowLog []
Displays the instantiation, build and simulation logs for the last simulation.
ShowSimulationLog[)
Displays the latest simulation log.
Make Mathematica treat expressions {s1,s2,...0 } as symbols. Useful for e.g. index expressions.
Appendix E-Modelica Scripting Commands 851 ShowSimulationVariables[ varpatternl
Lists the variables from the latest simulation having varpattem as prefix.
ShowTranslationLog[]
Displays the instantiation log for the last simulation.
Simulate [modelname,options]
Instantiate model, generate code and simulate model, optionally setting simulation values. The following optional arguments can be given: Method, Tolerance, IntervalLength, NumberOfIntervals, InitialValues, ParameterValues and InteractiveVariables
StartModelEditor(]
Starts the MathModelica Model Editor.
UpdateModelicaCache[]
Creates cache files for all standard Modelica files (. mo) in $Model icaPath.
Examples Below follows a few examples of using the scripting commands in MathModelica. The most common case is a Simulate followed by a PlotSimulation, referring to the results of the last simulation: Simulate [Pendulum, {t,O,4}] PlotSimulation[x[t], {t,0,4}];
A more advanced example is from the design optimization (Section 15.7) with a loop of simulations, collecting the simulation results into a vector (using Table): res = Table (Simulate [LinearActuator, {t,O,4}, ParameterValues ->{springDamperl.d == s}l, {s,2,lS,2}l; PlotSimulation[slidingMassl.s[t], {t, 0, 4}, SimulationResult -> res, Legend -> False);
Actually, the whole Mathematica language is available for advanced scripting. A number of metaprogramming scripting examples are presented in Section 19.5.2.
Dymola Scripting Commands These are the Modelica scripting commands available in the Dymola environment. animationColor(options)
Set animation colors. Inputs: Real background [3) ; Real selected[3] ; Real grid[3] ; Real selectedbackground[3] ; OU~UU:Boolean ok;
animationFollow(opti.ons)
Set what animation view should follow, Inputs: Booleanm followFirst; Boolean followx; Boolean followY; Boolean followZ; Boolean followRotation; Outputs: Boolean ok;
animationFrames(options)
Set animation frame properties. Inputs: Integer history; Integer interval; Integer delays; OU~U~:Boolean ok;
animationGrid(grid_square, grid_size)
Set grid size in animation window. Inputs: Real grid_square;
animationOnline(options)
Set realtime animation properties. Inputs: Boolean
Real grid_size;
OU~U~:Boolean ok;
852 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica onlineAnimation; Boolean realtime; Real scaleFactor; Real loadInterval; OU~U~:Boolean ok; animationPerspective( perspective)
perspective [7] ;
animationPosition(position)
Set positionof animation. Inputs: Rea 1 pos it ion [4] ;
Set animation perspective properties. Inputs: Real
Integer id;
OU~~~Boolean
OU~U~:Boolean
ok;
ok;
animationRedraw()
Redraw animation window. Outputs: Boolean ok;
animationRemove(id)
Remove animation window. Inputs: Integer id; Outputs: Boolean ok;
animationSelected(options)
Select animation object. Inputs: Boolean name; Boolean highlight; Boolean follow; Boolean trace; Integer selected; String selectedName; Outputs: Boolean ok;
animationSetup ()
Generatescript with currentsetup of animation window. OU~U~:Boolean
animation~peed(speed)
ok;
Set animation speed. Inputs: Real speed; Outputs: Boolean ok;
animationSubdivisions( subdivisions)
Set animation subdivision properties. Inputs: Integer
animationVectorScaling( options)
Set animation scaling properties. Inputs: Rea 1 force; Real
animationView(view)
Set animation view. Inputs: Real view (4 ,4]
subdivision [12l ;
OU~U~:Boolean
ok;
torque; Real velocity; Real acceleration; Real angularvelocity; Real angualracceleration; OU~UU:Boolean ok; ;
Outputs:
Boolean ok; animationViewing(options)
Set properties of animation. Inputs: Boolean cylinder; Boolean fillmode; Boolean unitcube; Boolean xygrid; Boolean xzgrid; Boolean yzgrid; Boolean perspective; Boolean antialias; Outputs: Boolean ok;
cd(dir)
Changedirectory. Inputs: String dir; Outputs: Boolean result;
checkModel(problem)
Instantiate model, optimizeequationsand report errors. Inpu~:String
problem;
Ou~ut~Boolean
result;
classDirectory ()
Directory containingthe class definition, or directorywhere additional files associated with the class should be stored.
clear ()
Clearseverything, i.e. abstractsyntaxtree representation of code togetherwith possibleuser defined variables. Outputs: Boolean result; Clear the log. Outputs: Boolean result;
Ou~ut~String
clearlog () closeModel() Compile () Continue ()
dir;
Close a model. Outputs: Boolean result; Compiledefault model. Outputs: Boolean result; Continuethe default model. Outputs: Boolean _resul t;
Appendix E-Modelica Scripting COffilnands 853 document (function)
Write calling syntax for named function. Inputs: String function;
eraseClasses(classNames_)
OU~U~:Boolean
result;
Remove classes from symbol table. Inpu~:String
classNames_[:]; result;
OU~U~:Boolean
Execute(file)
Execute file/command. Inputs: string file; Outputs: Boolean ok;
exit()
Exit Dymola.
experiment (options)
Set default simulation values,e.g. start time, stop time, tolerance, etc. Inputs: Real StartTime i Real StopTime; Integer NumberOfIntervals; Real OutputInterval; String Algorithm; Real Tolerance; Real FixedStepSize; Outputs: Boolean result;
exportlnitial(dsName, scriptName, options) importlnitial(dsName)
Export initial values to a script file. Inpu~:String
dsName; String scriptName; Boolean exportAllVariables; OU~U~:Boolean ok;
Import initial values as as script file. Inpu~:String
dsName;
OU~U~:Boolean
ok;
instantiateModel(problem)
Instantiatemodel, results in mof file. Inputs: String problem; Outputs: Boolean resu.l t;
interpolateTrajectory( fileName, signals, times)
Read simulationresult from file and interpolatevalues given as a vector of name on time instants given as a vector and return a matrix of interpolated values (one vector for each interpolated variable). Inputs: String fileName; String signals [ : ] ; Real times[:]; Ou~ut~Real values [size (signals, 1), size (times, 1)] i
linearize ( )
Linearizedefault model. Outputs: Boolean _result;
linearizeModel(problem, options)
Translate, simulate and linearize model. Inputs: String
list ()
Print user defined variables. Outputs: Boolean
problem; Real startTime; Real stopTime; Integer numberOflntervals; Real outputlnterval; String method ; Real tolerance; Real fixedstepsize; String resultFile; Ou~uU: Boolean result; resul t;
listfunctions() List builtin functions on screen. Outputs: Boolean _ resul t ; messageBox(message, timeOut, Show messagebox. Inputs: String message; Real position) timeOut; Real position[2]; OU~U~:Boolean ok; messageDialog(message, Wait for user input. Inputs: String message; Real timeOut, position) timeOut; Real position [2] ; OutPU~:Boolean ok; openModel(path)
Load models from file path. Inputs: String path; Outputs: Boolean result;
openModelFile(model,path)
Load thefile that contains the class. Inputs: String model; String path;
plot (_x)
result;
Plot one or more variablesas functions of time. Jnpu~:String
plotArray(x,y)
OU~U~:Boolean
x[:];
OU~U~:Boolean
result;
Plot the given values as an x-y plot. Inpu~:Real x[~];
Real y[size(x,l)]; Integer
854 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica style; String label; plotSetup ( )
Ou~ut~Boolean
result;
Generatescript with current setup of all plot windows. Outputs: Boolean ok;
plotWindowSetup(_window)
Generatescript with current setup of plot window. Inputs: Integer
window;
OU~U~:Boolean
ok;
Plot and print given variables. Inputs: String _x (:]; Outputs: Boolean result; printPlotArray(x, y, style, label)
Plot and print given data. Inputs: Real x [: ]; Real y[size(x,l)]; Integer style; String label; OU~U~:Boolean result;
readMatrix(fileName, modelName,rows,columns)
Read a matrixfrom a file. Inputs: String fileName;
readMatrixSize(fileName, matrixName)
String modelName; Integer rows; Integer columns; Outputs: Real matrix [rows, columns];
Read the matrixdimension from a file given a matrix name. Inpu~:String
Ou~ut~
readTrajectory(fileName, signals, size)
fileName; String matrixName; Integer size[2];
Reads the simulation result for a list of variables and returns a matrix of values(each column as a vectoror valuesfor a variable.) Size of result is also given as input. Inputs: String fileName; String signals[:) Integer rows; values[size(signals,l),rows];
Ou~u~:Real
readTrajectorySize(fileName) Read the size of the trajectory vector from a file. Inpu~:String fileName; Ou~uU: Integer rows; removeMessageBox() Remove messagebox. Outputs: Boolean ok i RemovePlots() RunAnimation(immediate, loadFile, ensureAnimationWindow) RunScript(_script) or filename
@
savelog(logfile)
Removes all plot windows. Outputs: Boolean ok; Run animation. Inputs: Boolean immediate; String loadFile; Boolean ensureAnimationWindow; Boolean ok;
Outpu~:
Executes the script file given as argument. Inputs: String script; Outputs: Boolean _result; Save the log to a file. Inputs: String logfile; Outputs: Boolean resul t ;
saveSettings(fileName, options)
Stores current settingson a file. Inputs: String fileName;
saveTotalModel(fileName, modelName)
Save total class definition in file. Inputs: String fileName;
SetVariable(name, val)
Set variablein model. Inputs: String name; Real val;
ShowComponent(path, components)
Show component. Inputs: String path; String
showMessageWindow(show)
Showlhide log. Inputs: Boolean show; Outputs: Boolean
Boolean storePlot; Boolean stroeAnimatioD; Boolean storeSettingsi Boolean storeVariables; Boolean storelnitial; Boolean storeAIIVariables; OutpUU:Boolean ok; String modelName;
OU~U~:Boolean
result;
OU~~~BooleaD ok;
components[:); ok;
OU~U~:Boolean
ok;
Appendix E-Modelica Scripting Commands 855
simulate ()
Simulate the default model. Outputs: Boolean _resul t;
simulateExtendedModel( problem, options)
Simulate a Modelica model. Inputs: String problem; Real startTime; Real stopTime; Integer numberOflntervals; Real outputlnterval; String method; Real tolerance; Real fixedstepsize; String resultFile; Boolean result; String initialNames [: ]'; Real initialValues[size{initialNames,l)]; String finalNames[:]; Ou~uU:Real finalValules[size(finalNames,l)] ;
simulateModel(problem, options)
Simulate a model. Inputs: String problem; Real startTime; Real stopTime; Integer numberOfIntervals; Real outputInterval; String method; Real tolerance; Real fixedstepsize; OutpUU:Boolean result;
switchLayer(layer)
Switch layer. Inputs: Integer layer; Boolean show; OU~UU:Boolean ok;
switchToModelingMode()
Switch to modeling mode. Outputs: Boolean ok;
switchToSimulationMode()
Switch to simulation mode. Outputs: Boolean ok;
translateModel(problem)
Instantiate model, optimize equations and generate code. problem; OU~U~:Boolean result;
Inpu~:String
variables ( )
List variables on screen. Outputs: Boolean _result;
vizualize3dModel(problem)
Display a 3D visualization of the latest simulation. Inputs: String problem; Outputs: Boolean resul t;
writeMatrix(fileName, matrixName, matrix)
Write matrix to file given a matrix name and a matrix. Inpu~:String fileName; String matrixName; Real matrix[:,:]; OU~~~Boolean status;
Example Below follows an example of a Dymola script file for the CoupledClutches example in the standard Modelica library.
// Script generated: 06/21/00 15:01:45 translateModel("Modelica.Mechanics.Rotational.Examples.CoupledClutches") experiment (StopTime=1.2) simulate plot ({ "Jl. w" , "J2. w" , "J3. wIt , "J4. wIt }) ;
857
Appendix F-Related Object-Oriented Modeling Languages
In this appendix we give an overview of the languages which have been used as starting point for the Modelica design, i.e, Modelica builds upon the experience gained with these languages. Some additional equation-based modeling languages are also briefly presented. Since the definition of CSSL in 1967 most modeling languages have essentially been block oriented with inputs and outputs. The mathematical models are defined as assignment-like equations for auxiliary variables and derivatives. Physical equations thus need to be transformed to a form suitable for calculations. The only aid in transforming the equations to an algorithm for calculating derivatives is automatic sorting of the equations. On the contrary, the object oriented modeling languages that constitute the background for development of Modelica all have general equations, i.e. expression = expression, as the basic element. Hierarchical decomposition and reuse are typically supported by some kind of model class. Several languages have provisions to describe physical connection mechanisms, i.e, to associate a set of variables with some kind of port. Such ports can be used at higher hierarchical levels when connecting submodels without having to deal with individual variables.
Language Developments behind Modelica The designers of the following object-oriented modeling languages have actively participated creating the Modelica language in part based on experience from these languages.
Dymola Language Dymola, (here meaning Dynamic Modeling Language), as introduced already in 1978 is based on equations for non-causal modeling, model types for reuse and submodel invocation for hierarchical modeling, and is one of the most important predecessors of Modelica. The Dymola translator utilizes graph theoretical methods for causality assignment, for sorting, (i.e, BLT-partitioning), and for finding minimal systems of simultaneous equations. Computer algebra is used for solving for the unknowns and to make simplifications of the equations. Constructs for hybrid modeling, including instantaneous equations, were introduced in 1993. Crossing functions for efficient handling of state events are automatically generated. A graphical editor is used to build icons and to make model compositions. Major application areas include multi-body systems, drivetrains, power electronics, thermal systems.
NMF - Neutral Model Format The Neutral Model Format (NMF) is a language in the Dymola and Omola tradition and was first proposed as a standard to the building and energy systems simulation community in 1989. The language is formally controlled by a committee within ASHRAE (Am. Soc. for Heating, Refrigerating and Air-Conditioning Engineers). Several independently developed NMF tools and model libraries exist, and valuable lessons on language standardization and development of reusable model libraries have been learned. Salient features
858 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica of NMF are: (1) good support for model documentation, (2) dynamical vector and parameter dimensions (a model can, e.g., calculate required spatial resolution for PDE), (3) full support for calls to foreign models (e.g. legacy or binary Fortran or C models) including foreign model event signals. Inheritance was not present in the original language proposal but was added 1995 to the language specification. Simulation models can be translated automatically from NMF into the local representation of a particular simulation environment. Several simulation environments have been built around the language. One of these is the IDA Simulation Environment IDA SE, which includes a graphical modeler, an NMF translator, and a solver. In order to illustrate the language a model of a thermal conductance from 1996 is presented below: CONTINUOUS MODEL tq_conductance ABSTRACT "Linear thermal conductance" EQUATIONS /* heat balance */ o = - Q + a_u * (Tl - T2)i LINKS variables /* type name TI, POS_IN Q; TQ terminal 1 TQ terminal 2 T2, POS_OUT Q; VARIABLES role description /* type name IN Temp Tl "1st temp" IN Temp T2 "2nd temp" OUT HeatFlux Q "flow from 1 to 2" PARAMETERS description /* type name role Area aSP "cross section area" HeatCondA u S P "heat transfer coeff" HeatCond a u C_P "a * u" PARAMETER PROCESSING a_u := a * U; END MODEL
ObjectMath ObjectMath (Object Oriented Mathematical Modeling Language), is a high-level programming environment and modeling language designed as an extension to Mathematica, with its first version appearing in 1991. The language integrates object-oriented constructs such as classes, and single and multiple inheritance with computer algebra features from Mathematica. Both equations and assignment statements are included, as well as functions, control structures, and symbolic operations from standard Mathematica. Other features are parameterized classes, named equations that can be specialized at inheritance, hierarchical composition, and dynamic array dimension sizes for multi-dimensional arrays. The environment provides a class browser for the combined inheritance and composition graph and supports generation of efficient code in C++ or Fortran90, as well as an experimental version for generating parallel code. The user can influence the symbolic transformation of equations or expressions by manually specifying symbolic transformation rules, which also gives an opportunity to control the quality of generated code. The main application area so far has been in mechanical systems modeling and analysis.
Omola Omola, 1989, is an object-oriented and equation based modeling language. Models can be decomposed hierarchically with well-defined interfaces that describe interaction. All model components are represented as classes. Inheritance and specialization support easy modification. Omola supports behavioral descriptions in terms of differential-algebraic equations (DAB), ordinary differential equations (ODE) and difference equations. The primitives for describing discrete events allow implementation of high level
Appendix F-Related Object-Oriented Modeling Languages 859 descriptions as Petri nets and Grafcet. An interactive environment called OmSim supports modeling and simulation: graphical model editor, consistency analysis, symbolic analysis and manipulation to simplify the problem before numerical simulation, ODE and DAE solvers and interactive plotting. Applications of Omola and OmSim include chemical process systems, power generations and power networks.
SIDOPS+ SIDOPS+, 1997, supports nonlinear multidimensional bond-graph and block-diagram models, which can contain continuous-time parts and discrete-time parts. The language has facilities for automated modeling support like polymorphic modeling (separation of the interface and the internal description), multiple representations (component graphs, physical concepts like bond graphs or ideal physical models and (acausal) equations or assignment statements), and support for reusability (e.g. documentation fields, physical types). Currently, SIDOPS+ is mainly used in the field of mechatronics and (neural) control. It is the model description language of the package 20-SIM SIDOPS+ is the third generation of SIDOPS which started as a model description language for singledimensional bond-graph and block-diagram models.
Smile Smile, 1995, is an object-oriented and equation-based modeling and simulation environment. The objectoriented and imperative features of Smile's model description language are very similar to Objective-C. Equations may either be specified symbolically or as procedures; external modules can be integrated. Smile also has a dedicated experiment description language. The system consists of translators for the above-mentioned languages, a simulation engine offering several numeric solvers, and components for interactive experimenting, visualization, and optimization. Smile's main application domain traditionally has been the simulation of solar energy equipment and power plants, but thanks to its object-oriented modeling features it is applicable to other classes of complex systems as well.
U.L.M. - Allan The goal of ALLAN, 1996, is to free engineers from computer science and numerical aspects, and to work towards capitalization and reuse of models. This means non-causal and hierarchical modeling. A graphical representation of the model is associated to the textual representation and can be enhanced by a graphical editor. A graphical interface is used for hierarchical model assembly. The discrete actions at the interrupts in continuous behavior are managed by events. Automatons (synchronous or asynchronous) are available on events. FORTRAN or C code can be incorporated in the models. Two translators toward the NEP11JNIX and ADASSL (modified DASSLRT) solvers are available. Main application domains are energy systems, car electrical circuits, geology and naval design. The language U.L.M. was designed in 1993 with the same features as the ALLAN language in a somewhat different implementation. It is a model exchange language linked to ALLAN. All aspects of modeling are covered by the textual language. There is an emphasis on the separation of the model structure and the model numerical data for reuse purposes. It also has an interesting feature on model validation capitalization.
Related Languages Here we describe some related equation-based modeling languages. Some of the early languages have influenced Modelica to some extend, other languages are later developments, or are independent parallel developments.
860 Peter Fritzson Principles of Object-OrientedModeling and Simulation with Modelica
ASCEND ASCEND (Advanced System for Computation in ENgineering Design) was developed at Carnegie Mellon University, PA, USA to be a rapid model building environment for complex models comprising large sets of nonlinear algebraic equations (Piela t 989, Piela et.al. 1991). The language is textual. It supports quantity equations, single inheritance and hierarchical decomposition, but it does not have well defined submodel interfaces. The application domain is chemical process modeling. Later versions support dynamic continuous time modeling.
VHDL-AMS The VHDL-AMS language, 1999, is a hardware description language that has been developed to support the modeling of analog, digital, mixed-signal and mixed-technology systems. The language extends the IEEE standard digital design language VHDL (IEEE Std 1076.1-1999) to cover mixed analog and digital systems. It is a large and rich modeling language targeted mainly at the application domain of electronics hardware. Structuring is done by means of entities and architectures. An entity defines the external view of a component including its parameters (generics), its discrete signal interface and its continuous interface (ports). The architecture associated with an entity describes the implementation which may contain equations (DAEs). As in the case of other equation-based modeling languages the VHDL-AMS language does not specify techniques for the solution of the expressed DAEs, leaving the selection of a suitable numerical method to the simulation environment. A typical VHDL-AMS simulation framework consists of a compiler and a simulator. The compiler translates the VHDL-AMS source code into an intermediate representation structured as abstract syntax trees with annotated symbol tables and additional semantic information. Similar to other equation-based simulation environments, a hierarchical application model is flattened to a set of discrete and continuous equations. An analog kernel calculates the analog solutions of the equations at a specified time step by providing an interface to a numerical solver. In this way the original model description is compiled into intermediate object code, linked together with a simulation kernel, and directly executed. The same translation process is also used by the SEAMS VHDL-AMS based simulation framework that incorporates an analyzer, an analog and digital kernel, a code generator, and a compilation module. A design support environment called SIDES (Simulation-Interactive Design Environment System) is attached to SEAMS and includes a GUI viewer, editors, debugging and editing support, library access, and a file and data exchange database to enable all the necessary design environment-simulator interactions. For reasoning and verification purposes, a denotational semantics of the language has been developed. The general behavior of VHDL-AMS programs is derived by translating the semantics into a prototype simulator implementation. In order to illustrate the syntax of the language, a simple linear resistor model is given below:
use electrical_system. all entity resistor is generic (resistance: real); port(terminal n1, n2: electrical); end entity resistor; architecture signal_flow of resistor is quantity vr across ir through n1 to n2; begin ir == vr / resistance; end architecture signal_flow.
Appendix F-Related Object-Oriented Modeling Languages 861
The XLanguage for Hybrid Systems Simulations The Xlanguage, 1999, has been designed with the aim of providing a general language for hybrid system simulations. A X program consists of processes, systems and function specifications, which are later instantiated by a top-level model. As is the case with most equation-based languages, the top model instance is executed by the simulation environment. A process in Xmay have a discrete-event part and/or a continuous-time part and a system may be composed from processes and system instantiations. The continuous-time behavior in X is expressed with the help of equation statements defined on the local variables of the processes. Model composition in X is achieved by the use of channels in the interface specifications of the sub-models. The channels have the same role as connectors in the Modelica language. A process example is given below:
proc P
I rv,x: {
= := 0
real]
, Q: real ,b: bool
:=
true
V' = 2 - Q ,IQIQ=sqrt(V} , [b - > x'
I
not b
= 1 - x]
Ixl x
->
]
]I
//eqO //eql // = 2
eq 2 /leq3
}
gPROMS gPROMS, 1992, is a general modeling language for combined lumped and distributed parameter processes described by mixed systems of integral, partial differential, and algebraic equations (IPDAEs). The language is a further development of the Speedup language. The gPROMS language has constructs for certain kinds of partial differential equations. The major application domain is chemical process modeling. The language does not contain constructs for component-based modeling with connectors, and does not support discrete-event modeling. The modeling language is integrated in a more general simulation system called gPROMS System, 1993, designed to support both continuous and discrete simulation. The language distinguishes two modeling entities: MODELs (containing DAEs which describes the physical system behavior) and TASKs (containing events representing external actions and disturbances imposed on the simulation model). Continuous models and tasks are combined into a single entity called process. Below we illustrate a lumped parameter model which is defined in gPROMS as follows: MODEL IsothemalFlash
PARAMETER Nocomp AS VARIABLE M,
F, V,L x,y K
INTEGER
AS ARRAY (Nocomp) OF Holdup AS ARRAY (Nocomp) OF Flowrate AS Flowrate AS ARRAY (Nocomp) OF MoleFraction AS ARRAY (Nocomp) OF Kvalue
EQUATION #Component mass balance $M = F - L * x - V * Yi #Phase equilibrium relationship FOR i:= 1 TO Nocomp DO K(i)
END
*
x(i)
= y(i};
SIGMA(x) =SIGMA(y) =1;
END #model IsothermalFlash
862 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica In the above example it can be seen that a MODEL is composed of sections labeled VARIABLE and EQUAT I ON. In the equation section algebraic, differential, and partial differential equations are allowed. The reusability of simulation models described with gPROMS is achieved by hierarchical submodel decomposition and by inheritance.
Abacuss II Abacuss II (Advanced Batch and Continuous. Unsteady State Simulator), 2002, provides a high level declarative input language for describing process model simulation. It is an enhanced version of the gPROMS language described by Barton already 1992. The syntax of the Abacuss II language is in the tradition of Pascal and Modula-2. The integrated simulation environment built around the language uses DAEPACK (Differential-Algebraic Equation Package) to perform the required symbolic and numerical calculations. Abacuss II uses single inheritance, invoked by the keyword INHERITS and the identifier of the parent immediately followed by the identifier of the new model entity. This is illustrated by the following example: MODEL Father PARAMETER PI AS REAL DEFAULT 4 * ATAN(1.0) END MODEL Child INHERITS Father PARAMETER E AS REAL DEFAULT 2.718 END
The Child model will inherit all the parameters of the Parent model, and in this particular case Child will contain both PI and E as parameters. Multiple or selective inheritance are not allowed in the language. The interaction of models with the environment is realized through stream attributes that are subsets of the variables describing the time-dependent behavior of the system. Connecting two models in Abacuss is realized by setting up a relationship between stream attributes corresponding to each submodel providing a compressed way of specifying interaction equations among components. The connection relationships need to be declared in the EQUATION section of the model entity. Conditional equations are also allowed to define dynamic changes in the topology of the simulation system. Equality constraints stated between stream variables is the most common kind of constraint used in process simulation.
Cob Cob, 2002, is a programming language based on the concept of constrained objects for compositional and declarative modeling of engineering structures. The abstraction models are specified using a declarative object-oriented language. The associated environment includes a graphical editor for developing Cob class definitions, a domain-specific visual interface where already developed components can be combined and a translator, which takes the declarative specification and generates an equivalent CLP(R) (Constraint Logic Program in the Real domain) program. This translator represents the main difference compared to the other languages and environments in this overview. Instead of generating an imperative equivalent form of the original source code and linking it to numerical solvers, the Cob translator generates an equivalent declarative specification, which is sent to an underlying CLP(R) engine. In this way Cob extends the declarative properties of eLP by introducing object-orientation, conditional constraints and preferences and subsumes the paradigms of CLP and HCLP (hierarchical eLP). By introducing these additional capabilities the applicability of constraint-based languages can easily be extended to engineering applications where components are modeled much more naturally in terms of objects and inheritance hierarchies. The Cob language is rather expressive compared to the equivalent generated CLP form as seen in the following simple electrical circuit example from (Jayaraman and Tambay 2001).
Appendix F-Related Object-Oriented Modeling Languages 863
class component pcomponen( [VI, II, Rl], [V, I, R]) ~ attributes Real V,I,R V=I*R, V=Vl, 1=11, R=R1. constraints V::1*R; 'pparallel ( [B] , [V, I, R, PC] ) t PC = B, constructors compnent (VI, I I, RI) { p:omponen~_, [V, I, R] ), foralll (PC, X, V) V=V1.
1=11.
R=Rl.}
} class parallel extends co~ent attributes compnent [] PC constraints forall X in pc: x.v = v. sum Y in £ : Y.I=I. sum Z in PC : (l/Z.R)=I/R. constructors paralel(B) { PC=B}
Nl=I, suml(PC,Nl, Y,I),
N2=1/R, sum2{PC,N2,Z,R). foralll([] X,V). foralll{[XrTail],X,V»:X V=V, X=[X V,X I,X R], foraIll{Tail,X~V).--
8um2([],O,Z,R). sum2([zITail], (1/Z_R)+Sumrest,Z,R~: sum2(Tail,Sumrest,Z,R), Z= [Z V, Z I, Z R] . suml([] ,D,Y,I). sum2 ( [YI Tail] , (Y I) +Sumrest, Y, 1)-: sum2{Tail,Sumrest,Y, I) , Y= [Y_V, Y_I, Y_Ii.
The Cob language successfully extends several previous object-oriented constraint imperative languages with stratified preference logic programs that allows an efficient simulation of the constraint hierarchies.
Object-Oriented Biomedical System Modeling (OOBSML) The OOBSML language, 1999, has been developed at Uppsala University Hospital aimed at the development of a biomedical continuous system modeling language. It is fully object-oriented and supports model inheritance, encapsulation, and model component instantiation. The language resembles Omola very much. Besides DAEs the language also includes formal expressions for documenting models and defining model quantity types and quantity units. It supports explicit definition of model input, output and state quantities, model components, and component connections. The OOBSML model compiler produces self-contained, independent, executable model components that can be instantiated and used within other OOBSML models and/or stored within model and model component libraries. In this way complex models can be structured as multilevel, multi-component model hierarchies. Technically the model components produced by the OOBSML compiler are executable computer code objects based on distributed object and object request broker technology. The most basic concept of the OOBSML language is the model concept. A model encapsulates system knowledge and information related to the purpose of modeling such as: input and output quantities, state quantities, types and units, and model behavior represented by algebraic and differential equations. A simple example of a two compartment model used for medical simulation illustrates the language syntax: model TwoCompWithMetabolism: TwoComp has inputs meta: reaction_rate [mol/L/h] outputs Fmeta: substance flow [mol/h] behaviour Dynamic is begin Np'=Fpo-Fop+Fpe-Fep+Fmeta Fmeta=Vmeta *Vp end Dynamic end TwoCompWithMetabolism
864 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica
Literature In the introduction to this appendix, we mention the CSSL definition, described in (Augustin, Fineberg, Johnson, Linebarger, Sansom, and Strauss 1967). A number of object-oriented equation-based modeling languages, whose originators have participated in the design of the Modelica language, are presented in the following references: • • • • • • •
Dymola as Dynamic Modeling Language-(Elmqvist 1978; Cellier 1991; Elmqvist, Cellier, and Otter 1993; Elmqvist, Bruck, and Otter 1996). NMF-(Sahlin and Sowell 1989; Sahlin, Bring, and Kolsaker, 1995; Sahlin 1996; Sahlin, Bring, and Sowell 1996; Equa 2(03). ObjectMath-(Fritzson, Viklund, Herber, Fritzson 1992; Fritzson, Fritzson, Viklund, Herber 1994; Fritzson, Viklund, and Fritzson 1995). Omola-(Andersson 1989; Andersson 1992; Mattsson and Andersson 1992; Mattsson, Andersson, and Astrom 1993; Andersson 1994). Smile-(Kloas, Friesen, and Simons 1995; Ernst, Jahnichen, and Klose 1997). SIDOPS+ - (Broenink 1997; Breunese and Broenink 1997). ALLAN, U.L.M.-(Jeandel, Boudaud, Ravier, and Bushing 1996).
The following are related equation-based modeling languages: • •
•
• • • •
ASCEND-(Piela, Epperly, Westerberg, and Westerberg 1991). VHDL-AMS-(Frey, Nellayappan, Shanmugasundaram, Mayiladuthurai, Chandrashekar, and Carter 1998; Christen and Bakalar 1999; IEEE Std 1076.1-1999; Schneider, Mades, Glesner, Windisch, and Ecker 2000). Abacuss II-the language with applications is described in (Tolsma, Clabaugh, and Barton 2002; Tolsma, and Barton 2(00). It is actually an enhanced version of gPROMS as described in (Barton 1992). gPROMS-(Barton 1992; Barton and Pantelides 1993; Barton and Pantelides 1994; Oh 1995; Oh and Pantelides 1996). The X system-(Fabian 1999). Cob-(Jayaraman and Tambay 2001; Jayaraman and Tambay 2002). OOBSML-(Hakman and Groth 1999; Hakman 2000).
865
Appendix G-A Modelica XML Representation The Modelica XML language representation (here a beta version 0.9) is a textual XML tree representation intended as an interchange format between various tools. This representation provides a structured form of the Modelica language similar to Abstract Syntax Trees (AST) generated by a compiler when parsing Modelica code. The Modelica XML representation can be used by tools to perform the following tasks: • •
•
Analysis of Modelica models. Pretty printing (unparsing) Modelica source programs into various forms, e.g. documentation. Restructuring or translation of Modelica programs using XLST transformation tools.
This appendix defines the Modelica XML representation. We first take a commented example and then we give the Document Type Definition (DTD) for the Modelica XML representation. In this appendix we use the following syntactic conventions regarding XML elements, attributes and entities: • • •
Elements from the DTD are in bold. Attributes are in italics. Entities are underlined.
To avoid confusion we use "item(s)" to refer to XMUDTD "element(s)", because Modelica grammar has a non-terminal symbol denoted "element". The Modelica XML example files and Modelica DTD (modelica.dtd) file were constructed and validated using XML Spy 5.0. Furthermore these files have been validated using the service at (http://www.stg.brown.edu/service/xml valid/), Our Modelica DlD is can express Modelica language from Mcdelica Language Specification version 2.0 and 2.1.
Modelica vs. Modelica XML In order to show the difference between the standard Modelica textual syntax and the Modelica XML syntax, we first show a sirnple Modelica model and its XML representation: class SecondOrderSystem Real x(start=O); Real xdot(start~O}; parameter Real a=l; equation xdot = der (x) ; der(xdot)+a*der(x)+x = 1; end SecondOrderSystem;
This appears as follows in Modelica XML: < 1DOCTYPE program SYSTEM "modelica.dtd"> <program within:""> <definition ident="SecondOrderSystem" restriction="class">
The first two lines of our XML representation specify that our file should be checked for conformance with the DTD ("modelica.dtd"). As root item we have a Modelica program. The child items of program are a list of definitions and an optional within attribute. All items can have sline. scolumn, eline, ecolumn and info as optional attributes, which are being grouped by the location entity from the DTD. To make our example more clear the last attributes are not shown. <definition ident="SecondOrderSystem" restriction="class"> <equation> The definition item can have import? extends, elements, equation or algorithm as subitems. The required attributes for definition are ident and restriction. Optional attributes for definition items are presented in the DTD definition under Class Definition.
866 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica In our case we have only component and equation subitems inside definition. <modification arguments> <element modification> <modification equals> <modification equals>
Component items have attributes representing the Modelica type prefix (flow, variability, direction), and type name (type). The first component declaration in the example represents the "Real x (start=O) i" line from our Modelica class. The last component has the variability attribute set to "parameter" as in "p~rameter Real a=l;" <equation> < e qu_equa 1 >
<equation> <eCLequals> declaration comment
• • •
An attribute list is conforms to the following declaration:
Some of the terminals from the Modelica grammar are represented as attributes as follows:
• •
•
" I" has the same meaning as in the Modelica grammar. # IMPLI ED means that the attribute is optional. #REQUIRED means that the attribute is mandatory.
Design decisions When designing the Modelica XML representation we started from the Modelica grammar. We simplified the common cases to compact the XML representation without loss of information or structure. The Modelica DTD has a rather close correspondance to the Modelica grammar with the following exceptions:
•
Attributes are used to make the XML representation more concise The DID jumps skips some nonterminals from the Modelica grammar to make the XML representation more compact.
Stored definition Modelica programs are a list of definitions combined with a within attribute that indicates the hierarchical position of the program.. The parametric entity location appears inside attribute list declaration and will be expanded by the XML parser into sline, scolumn, eline, ecolumn and info optional attributes.
Class definition Classes are defined using the definition item with several attributes and with child items that make together a class definition. We use the entities class specifier, composition and elements to break the complexity of the class declaration. We pushed all the type modifiers from the grammar up to the definition item and store them as attributes.
868 PeterFritzson Principles of Object-Oriented Modeling andSimulation withModelica The entity class specifier states that a class can be defined either using a composition entity, is derived from another class (using =), or consists of an enumeration type.
The external item declaration has the attributes ident (the identifier of the function to be called), and language_specification (which holds the language in which the function is expressed "C", "Fortran"). To express the external_function_call non-terminal from the Modelica grammar we use the optional item external_equal and the optional entity expression list followed by two optional annotation items that have a semicolon in between to differentiate them. Inside external_equal item we have the component_reference item. The external_equal item was introduced to make the DTD deterministic. If we use component_reference instead of external_equal in the external item definition the DlD becomes ambiguous because expression list contains component_reference too, and an XML parser would not know which component_reference is parsing.
An import item declaration has the attributes
ident, name and dotstar. When both ident and name attributes are present we have (import IDENT n = u name) from the Modelica grammar. When only name and optional dotstar is present then we have (import name [U." U* II] ).
Appendix G-A Modelica XML Representation 869
%location;
>
x would have attribute value "start", y would "continue", and z would have "end".
component items. Here
Extends
Component clause Variable declarations, i.e, components, are defined in the Modelica grammar using a component list that can contain one or more components. For simplicity reasons in our XML representation we are using only one component item to define components that include the type_array_subscripts to specify the array subscripts applied to the type (ex: "Real [3] x; -). The array subscripts applied to the component are specified with array_subscripts item (ex: "Real x [3] ; -). Also, the comment is merged into the component item. The Modelica type_prefix is represented by several attributes. The type_specifier appears as the attribute type. One can use the list attribute to specify when a component list (variable list) that is sharing the same type in a declaration (e.g. "Real x, y, z; "), is starting ("start" value), ending ("end" value) or continuing ("continue" value). Such a list is broken apart into several
have
The extends items are defined as class modification entities which are presented in the Modification section in the following. The constrain items are used to constrain definition items (for example: "replaceable type CompType Resistor extends TwoPin i "). Here extends actually constrains the type to the super-type and is not representing any inheritance despite the same keyword extends.
a list
Modification A Modelica modification captures the changes that should be applied to a class or to the components of a declaration. For example in the code "Real x(start=O) .», the modification is " s tart =0" and is applied to the component x. Modification items can be expressed with one the modification_arguments, modification_equals or modification_assign items. These tree items model one of the alternatives of the modification non-terminal from the Modelica grammar. A class modification entity states what modifications are made to a class when it is used and is a list of arguments that can be either element_modification or element_redeclaration items.
of
%location;
>
Expressions Expressions are represented using the exp entity. All the expression statements are grouped into this entity for ease of use. We can have the following kinds of expressions: if expressions (if), simple expressions (range), binary logical operators (or, and), unary logical operator (not), relation operators (It "=", eq "==", ne ""), unary operators (add "+", sub "_"), binary operators (add "+", sub "". mul "*", div "I"), power operator (pow "?") and primary expressions (integer_literal, real_literal, strlngIiteral, boot_literal, component_reference, call, paran, concat, arr, end).
Tummescheit, Hubertus, and Jonas Eborn. Thermofluid library web page http://www.sf.netlprojects/thennofluid. 2003. Unger, 1., A. Kroner, and W. Marquardt. Structural Analysis of Differential Algebraic Equation Systems-Theory and Applications, Computers Chem. Engng. 19:18, pp. 867-882,1995. Uno, Takeaki. Algorithms for Enumerating All Perfect, Maximum and Maximal Matchings in Bipartite Graphs. In Proceedings of 8th Annual International Symposium on Algorithms and Computation (ISAAC '97), Singapore, Dec. 17-19,
1997. Uno, Takeaki. A Fast Algorithm for Enumerating Bipartite Perfect Matchings. In Proceeding of 12th Annual International Symposium on Algorithms and Computation (ISAAC2001), LNCS 2223, pp. 367-379, Springer-Verlag, 2001. Viklund, Lars, and Peter Fritzson. ObjectMath--An Object-Oriented Language and Environment for Symbolic and Numerical Processing in Scientific Computing, Scientific Programming, Vol. 4, pp. 229-250, 1995. Voit, Eberhard O. Computational Analysis of Biochemical Systems: A Practical Guide for Biochemists and Molecular Biologists, Cambridge Univ. Press, 2000. Volterra, V. Variations and Fluctuations of the Number of Individuals in Animal Species Living Together, J. du Conseil, Vol. II, 1928. Wiesmann, Hans-Jurg, Private communicat.ion regarding the SPOT library, and Modelica array concatenation and construction. ABB Corp. Research, Segelhof, CH-5405 Baden, Schweiz.
[email protected], 2001. Visio. http://www.microsoft.com/office/visio/. 2001. Wolfram, Stephen. Mmhemasica-e-A System for Doing Mathematics by Computer. Addison-Wesley, 1988. Wolfram, Stephen. The Mathematica Book. Wolfram Media Inc, 1997. Wolfram, Stephen. A New Kind ofScience. Wolfram Media Inc, 2002. Wrangsjo, Andreas, Peter Fritzson, and K. Sheshadri. Transforming Systems of PDEs for Efficient Numerical Solution. Available at http://south.rotol.ramk.fi/....keranenlIMS99/paper7rrransformations.pdf. In Proceedings of the International Mathematica Symposium (IMS99), Linz, Austria, 1999. Zeigler B.P. Multifaceted Modeling and Discrete Event Simulation. Academic Press, London, 1984. Zeigler B.P. Object-Oriented Simulation with Hierarchical, Modular Models, Academic Press London, 1990. AhIander, Krister. An Object-Oriented Framework for PDE Solvers Ph.D. thesis, Dept. of Scientific Computing, Uppsala University, Sweden, 1999.
886 PeterFritzson Principles of Object-Oriented Modeling andSimulation with Modelica Astrom, Karl-Johan, Hilding Elmqvist, and Sven-Erik Mattsson. Evolution of Continuous-Time Modeling and Simulation. In Zobel and Moeller (eds.), Proceedings of the 12th European Simulation Multiconference (ESM'98), pp. 9-18, Society for Computer Simulation International, Manchester, U.K., 1998.
887
Index Abacuss II, 862 abs function, 47, 193, 199,298,309,420 abstractclass, 39 abstractdata types,333 abstractsyntax,57, 707 acausal,34 acausalconnections, 151 acausalmodeling, 19,34 accesscontrol,77 accessoperator, 197, 198 acos function, 200,618 adamsmethods, 672 algebraic equation, 21 algebraic loop,426 algebraic variable, 399 algorithm, 46, 49, 50, 57, 83, 185,283,285,286 algorithm sections, 285, 657 algorithmic constructs, 46 algorithms, 46, 283, 285, 310 aliases,54 Allan-U.M.L,63 AllSizes, 102 altitude,77 Analogcomputing, 65 analogsimulators, 64 analysisType function, 201, 309 analyzing models modelverification, 10 model-based diagnosis, 10 sensitivityanalysis, 9 analyzing models, 9 and, 185, 188, 196 annotation, 54, 185,357,358 algorithm, 361 Bitmap,368 choice,368, 369 choices, 132 class, 359 CoordinateSystem, 363 Diagram, 362 documentation, 369 elements, 359 Ellipse,367 equations, 360 Extent,363 function, 372, 374 graphical, 361, 363, 364 HTMLdocumentation, 370 Icon, 362 import,360 interactive menus,368 Line, 366 Point,363 Polygon, 367 Rectangle, 367
redecIaration, 359 standardnames,358 statement, 361 Text, 367 transformation, 365 type checking, 358 variable, 360 versionhandling,370, 371, 372 versionnumbering, 371 annotation conversion, 371 annotations, 358 function derivative, 372 graphical layers,362 Apollo12,76 application examples, 523 application expertise, 9 argument mapping, 315 argument passing,301 arithmetic operators, 195 array, 118,207,208,209,210,212,213,214,216,217, 219,220,221,223,225,227,228,229,231,232,309 arithmetic operators, 223 concatenation, 45, 187,213,214,219,229, 234 concatenation examples, 216 construction, 107,210, 213 declarations, 207 dimension, 88, 225 equalityoperator, 221 indexing, 216 indexing with booleanvalues,217 indexingwith enumeration values,217 iterators, 212 of connectors, 167 reduction, 227 reduction with iterators, 227 size, 209, 225 types, 207 usageexamples, 220 Array, 103 array dimension indexbounds,208 array dimensionality matching, 166 arrayequality assignment operator,221 array operator, 223 array types,209 arrays,44, 208 assignments, 222 asin function, 200, 618 assert,249 assertfunction, 172, 185,240,247,250,296,298,385, 387,415 assignfunction, 324 assignment, 287 assignment conversion, 190
888 Peter Fritzson Principles of Object-Oriented Modeling and Simulation with Modelica AST, 707 atan function, 200, 618 atan2 function, 200, 618 attribute,75 start, 94 attributes displayUnit, 85,375 f~ed,85,94, 120,682 max, 29,84,85 min, 29, 84, 85 nominal,85 quantity, 85, 374, 375 start, 20, 27, 33, 75, 85, 198 unit, 85, 374, 375 backlash,464 DCMotorCircuitBacklash model, 466 ElastoBacklash model,467 SimpleElastoBacklash, 465 base class, 29 base functions, 308 base quantities, 374 BasicVolume model, 533, 536 behavior redefmition, 139 biochemical application, 15 block,28, 81, 82,91, 148, 185 blockdiagram,65, 396 block diagrams, 396, 398 Blocklower triangular,62 blockorientedmodeling, 35,36, 381 BLT transformation, 57 BLT-transformation, 62 board temperature, 100 BoardExample class, 100 bodies,588 Boolean, 23, 25, 29, 84, 86, 185,186,194 bottom-up modeling, 383, 384 BouncingBall model, 52 break,291 built-in array functions, 225 data types, 23 functions, 44, 173, 190, 191, 199,309,413 functions and operators,305 operators, 83, 183,201 time variable,42, 198,243,412,419,445 types, 29, 73,84,101,185 C,315,316,318 C functions, 312, 313, 316, 318, 374 CAD model, 611 call structuremapping,313 capacitor, 12, 35,40,41,478 cardinality,83, 203, 308, 309, 311 cat function, 229 causal connections, 151 causality,34, 37, 82, 145,287,396 analysis, 164 tixed,28, 81,655 prefix,28 prefixes,91, 94, 165 ceil function, 191, 193,200,309,420 CelestialBody class, 74 cellular automata,437 change function, 83, 202,286,308,309,311,419,436
characterset, 183 chemicalreactions, 553 CircuitBoard, 176 CircuitBoardl class, 100 class, 74, 115 extensiondesign, 137 Class, 104 class parameter, 133 class parameters constraining types, 135 instances, 30 types, 31 classes, 73 communication port, 567 generic,30, 133 parameterized, 133 restricted, 28 ColorData record,30 coloredpetri nets, 460 ColoredClass, 31 comments, 24, 183, 184,369 communication link model, 572 communication networks,564 ComplexNumbers, 326 Compliantmodel, 154 component framework, 145 component library design,41 use, 41 components, 37, 145,146,151 composite connections, 151 Compressors, 538 concurrency, 406 conditional assignments, 292 conditional equations,40 I conditional expressions, 51, 52, 198,293,294,413,416, 422 conduction, 488 connect,39, 59, 149, 169, 185 annotation, 366 connectequation,35, 38, 57, 59, 149, 155, 156, 167, 173,244,447 connectequations, 240 connecting multiple, 155 connecting arrays of connectors, 167 connecting components, 162 connection equations, 278 graphs. See connection constraints arrays, 166 constants, 166 subscripts, 166 connection diagrams, 37, 146 connection equations, 169, 171, 172 cardinality-dependent, 173 generation of, 169 Connection Graphs,276 connectionmechanism, 145 connection semantics, 162 connection sets, 169, 170, 171 connection structures, 175 connections, 38, 145, 148
Index 889 electrical, 149 mechanical, 150 connections, explicit, 148 connections, implicit, 148 connector, 28, 38, 82, 185 composite, 162 design guidelines, 158 Frame_a, 592 hierarchical, 163 input, 164 inside, 163 output, 164 outside, 163 signal-based, 161 connector classes, 146 block/signal, 529 composite, 162 design guidelines, 158 mechanical, 528 physical, 159 signal-based, 161 connector matching, 172 connectors, 145, 146, 151, 365 conservation of energy, 534 of mass, 532 conservation equations, 382 conservation of energy, 496 consmnt, 23, 24, 33, 89, 90,93,94, 104, 131, 185,398 declarations, 33, 120 equations, 172 literals, 24 variables, 60 constant subscript constraint, 167 constants, 24, 89 constitutive equations, 40, 41, 152 defmition, 382 constraining type, 129 constraints, 251 constructor functions, 226 continuous flow model, 566 continuous PI controller, 387 continuous PID controller, 389 continuous-time, 90 continuous-time variables, 409 contract designer - user, 73 control systems, 406, 452 control volume, 530, 531 controllable, 5 controller discrete, 256 Controller model, 27 convection, 490 conversion, 190 conversion functions, 225 coordinate direction, 152 coordinate system, 151 coordinate systems mechanical component, 153 cos function, 200,618 cosh function, 200, 618 cross function, 229 crossing functions, 685 DAE. See differential algebraic equation
DAEexample model, 22 dangerous, 5 DASSL,674 data dependency order, 427 data fields, 105 data-flow principle, 410 DC-motor, 524 DC-motor servo, 392 DCMotorCircuit, 525, 526, 528, 529 DEABM, 673 debugging, 693 declaration order, 115 processing, 114 declaration equations, 238, 239, 657 arrays, 222 declaration order, 95,427 declaration prefixes, 88 declarations, 73 declarative constructs, 283 declarative programming, 25 deductive modeling, 382 default mapping, 312 definition declaration, 99 delay, 83, 203, 308, 309, 311, 419 der,12,20,60,89,201,286,308,309,311,372,429, 717, 718 derivative. See der derived class, 29 design optimization, 578 determinism, 406 diagnosis, 696 diagonal function, 226 Diagona~anices,324
difference equations, 401 differential algebraic equation, 20, 21, 57, 59,400,654, 655,656,657,667,682,683 differential algebraic equations, 673 differentiation. See der digital circuits, 433 dimension, 374 dimension and quantity checking, 377 dining philosophers problem, 470 Diode model, 51 direction, 203, 309 discrete, 89, 90,93, 94, 193,409 discrete event, 50 discrete event system specification, 444 discrete model, 566 discrete variables, 189, 654 discrete-time, 89, 654 discrete-time variables, 409 displayUnit attribute, 85, 375 disturbance inputs, 5 disturbance signal, 398 div function, 193, 199, 309, 420 divide function, 324 domain physical, 160 duplicate, 75 Dymola, 63, 699, 711 Dymola language, 857 Dymola commands, 851 dynamic model, II
890 PeterFritzson Principles of Object-Oriented Modeling and Simulation withModelica continuous-time, 12 discrete-time, 12 dynamic models discrete-time, 13 dynamic semantics, 703 each, 120 edge function, 83, 202, 286, 294, 308, 309, 311, 419 elaboration,707 electrical circuits, 50 Electrical Circuits, 478 electrical component EMF, 526 Ground, 526 TwoPin, 526 ElectricalComponent Inductor,526 Resistor, 526 electrical connector classes NegativePin,528 Pin, 528 PositivePin,528 element-wise,230 e~~46,51, 185, 188, 189,245 elseif, 46, 185,245, 292 elsewhen, 185, 246, 248, 293, 296 empty functioncalls, 304 encapsulated, 54,81, 93, 94, 185, 333, 339, 352, 354 encapsulation, 93,333 end, 46, 185 end-to-endcommunicationprotocols, 564 energy conservation,477 energy flow, 159 energy forest, 559 enthalpy,496 enumeration, 23 subtype, 108 Enumeration, 84, 86, 102 environmentvariables, 174 equal function, 324 equalEqualfunction, 324 equalitycoupling, 148 Equalitycoupling, 39 equalityequations,240 equation,46, 149, 185,237,240,241,283, 285,293, 360,439 categories,237 equation operators,274 Equationsign, 63 equations, 11,32,237 algebraic,400 differential,399,401,656 differential-algebraic, 57 in declarations,239 escape codes, 186 euler integrationmethod, 62 EuroSim,63 evaluation order of, 188 event, 12, 190,247,293,407,412,415,420,421 event iteration, 204 event synchronization, 425 event-basedstochastic processes, 441 example electrical component library, 41
examples DC motor, 163 moon landing, 78 pendulum, 598,600,604,605,606,607 execution, 57 execution and run-time module, 700 exp function, 200, 618, 625 expensive, 5 expensive dynamic state selection, 687 experiments,3, 5 explicit equation, 60, 402 explicit state space form, 402 expressions parameter, 192 expressions, 183 conditional, 51 constant, 192 type, 190 variability, 192 expressions discrete-time, 193 expressions continuous-time, 193 expressivityof equations, 238 extends, Ill, 113, 115, 117, 122, 123, 185 extension, 139 of class, 137 external, 185, 311 external events, 412, 444 external force elements, 603 external function example, 317 external functions,49, 318, 319, See function, external external objects, 320 external transition, 444 false, 23, 185, 192,416, 428 fill function, 44, 226 FilterslnSeries model, 29 final, 91, 93, 104, 127, 128, 185,375 finite state automata,433 first principles,405 fixed attribute, 85, 94, 120,682 flat tank system, 385 flattening, 57 floating point arithmetic, 195 floating point numbers, 186 floor function, 191, 193,200,309,420 flow, 38, 91,94, 104, 131, 148, 185 flow variables, 39, 148, 160, 171 for, 47, 211, 212,227, 241, 242,288,290 force field, 177 for-equations, 244 formal parameters, 299 Fortran 77, 315, 316 fourier analysis, 582 frame, 588 Free-flying Body, 589, 590 fully qualified name, 53, 335 function, 47,81,83,148, 185,287,298,300,311 assign, 324 divide, 324 equal, 324 equalEqual, 324 external, 311
Index 891 greater, 324 index, 324 indexedAssign,324 less, 324 lessEqual,324 minus, 324 multipleresult, 302 named arguments, 196 notEqual,324 plus, 324 power, 324 properties,308 reinit, 52, 296 restrictions,308 return, 304 single result, 302 times, 324 unaryMinus,324 unaryPlus,324 Function, 104 function calls, 657 function declaration,299 function inversion, 687 function results, 25 function type, 104 functions, 283, 310 abs,47, 193,199,298,309,420 acos, 200, 618 analysisType, 201, 309 asin, 200, 618 assert, 172, 185,240,247,250,296,298,385,387, 415 atan, 200, 618 atanl, 200, 618 cat, 229 ceil, 191, 193,200,309,420 change, 83,202,286,308, 309,311,419,436 cos, 200,618 cosh, 200, 618 cross, 229 diagonal, 226 diY, 193, 199,309,420 edge, 83,202,286,294, 308,309,311,419 exp,200,618,625 fill, 44, 226 floor, 191,193,200,309,420 identity, 122,226 initial, 21,83,201,241,286,297,308,309,311,414 integer, 191,200, 309,420 linspace,226 log, 200, 433,618 10g10, 201, 618 matrix, 44, 45, 62, 80, 88, 103,207,208,213,214, 219,220,224,225 max, 45, 227, 228 min, 45, 227,228 mod, 47, 200, 309,420 ndims, 210, 214, 225 ones, 226 outerProduct,228 overloaded,323 pre, 204 product, 159, 227, 228 rem, 200, 309, 420
sample, 83, 202, 286, 309, 311, 415 scalar, 225 sign, 193, 199, 309, 420 sin, 200, 618 sinh, 200, 618 size, 46, 225 skew, 229, 520 smooth, 201, 286, 309, 417 sqrt,47,199,298,309 sum, 45, 227, 228 symmetric, 228 tan, 200, 618 tanh, 200,618 terminal, 83, 201, 247, 286, 308, 309, 311,414 terminate, 240, 247, 250, 296, 298 transpose, 44, 228 vector, 225 zeros, 44, 226 game of life, 438 gas turbine model, 15 GASP-IV, 64 generic classes, 133 GenericResistorCircuitmodel, 134 generics, 111 getting started, 19 graphical elements definitions, 366 graphical layer diagram, 362, 366 icon, 362, 366 graphical layers diagram, 363 icon, 363 graphical model editor, 701 gravitation, 177 gravity, 76, 77, 79 gravityInterface, 177 greater function, 324 greaterEqual function equalEqual,324 GreenClass, 31 grid function, 270 Grid Function 2D,273 ground, 43 growth model, 559 guard, 189 guard expressions, 189
continuous-timeconditions, 189 discrete-timeconditions, 189 hardware/software,406 HeatPort, 176 HeatTank model, 137 HeatTankExpandedmodel, 137 HelloWorld model, 20 hierarchical, 163 connections, 163 modification, 124 hierarchical libraries, 339 history, 63 hybrid DAEs, 401 hybrid model, 566 hybrid modeling,50 hybrid system, 460
892 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica hydraulics, 484 Hydraulics Library, 641 hydrogen iodine, 554 Ideal diode, 51 identical names, 75 identifiers, 184 identity function, 122, ,226 it 46, 51, 185, 188,237,245,292,294,421,423 if, 292 if-equations, 245 if-expression, 197 IlIegalDuplicate class, 75 implementation, 57 implementation phase, 15 implicit connections, 173 import, 53,83,97,335,336,351,352 qualified, 336 renaming, 337 single defmition, 336 unqualified, 337 in, 185 index function, 324 indexedAssign function, 324 indexing Array, 216 enumeration, 217 scalar, 217 inductive modeling, 382 inductor, 42 industry robot, 15 information hiding, 333 inheritance, 29, 111, 112 equation, 112 modification, 119 MoonLanding model, 115 multiple, 113 predefmed types, 118 protected, 117 short class, 117 subtyping, 116 inhibitor petri nets, 460 initial, 253 initial algorithm, 286 initial equation, 250, 252 initial function, 27, 83, 201, 247, 286, 297, 308, 309, 311,414 initial values, 94 initialization, 27, 94, 250, 251,252,253 local, 286 number of equations needed, 255 inlet, 244 inner, 93, 99, 107, 172, 185 InPort,529 input, 28, 35,46,60,81, 91, 93, 94, 164,311 input signals, 161 input variable, 398 inputs,S inside connector, 164 instance, 26, 73, 75, 77 instance hierarchy lookup, 99 instance parameters, 30 instantiation, 707 Integer, 23, 29, 84, 86, 185, 186, 194 integer arithmetic, 195
integer function, 191,200,309,420 integration phase, 15 interactive programming environments, 709 interactive session handler, 700 interfaces extension ot: 136 internal events, 412, 444 internal representation, 57 internal states,S internal transition, 444 internal variable, 398 ISO C standard, 195, 196 isPresent,203 iteration ranges, 242, 289 joints, 588 keyword, 74 algorithIn,46,49, 50, 57, 83, 185,283,285,286 annotation, 54, 185,357,358 annotations, 358 block, 28, 81, 82, 91, 148, 185 break, 291 class, 74, 115 connect, 39, 59, 149, 169, 185 connector, 28, 38, 82, 185 constant, 23, 24,33,89,90,93,94, 104, 131, 185 discrete, 89, 90, 93, 94, 193, 409 each, 120 else, 46, 51, 185, 188, 189,245 elseif, 46, 185, 245, 292 elsewhen, 185,246,248,293,296 encapsulated, 54, 81,93,94, 185,333,339, 352,354 end, 46, 185,217,285 equation, 46, 149, 185,237,240,241,283,285,293, 360,439 extends, 111, 113, 115, 117, 122, 123, 185 external, 185,311 false, 23, 185,416,428 final, 91, 93, 104, 127, 128, 185,375 flow, 38,91,94, 104, 131, 148, 185 for, 47, 211,212,227,241,242,288,290 function, 47, 83, 148, 185,287,298,300 i~46,51, 185, 188,237,245,292,294,421,423 import, 53, 83, 97, 335, 336, 351, 352 initial, 285 inner, 93, 99, 107, 172, 185 input, 28, 35,46,91,93,94, 311 model, 6, 19,22,25,28,81, 148, 185 oute~93,99, 172, 173 output, 28, 35,91,93,94, 185 package, 53, 54, 81,83,92, 133, 148, 185 parameter, 20, 89, 93, 94, 185 partial, 94, 185 protected, 26, 46, 77, 88, 93, 124, 185,285 public, 46, 77,88,93,185,285 record, 28, 82, 148 redeclare, 91, 93, 127 replaceable, 91, 93, 127 return, 304 then, 185, 188 true, 185,416 type, 82, 102, 185 variables, 74, 75 when, 185,246,293,295,296,423 while, 290
us,
Index 893 within,341 keY1Words, 184, 185 kinematic loops,601 kinematic outlineapproach, 597 kinematics, 504 kinetic,535 kinetics,504 Kirchhoff's currentlaw, 150 Kirchhoff's CurrentLaw, 148 languages ACSL,64 Ada, 30, 53, 133,357 ASCEND, 64, 860 C,20,25,207,372 C++, 25, 30, 133 Cob, 862 CSSL,64 Fortran,25, 207 Fortran77, 372 gPROMS, 64,861 Haskell,30, 133 Java, 25, 53 Lisp, 64 ModelicaXML, 865 ObjectMath, 65 Ornola,64 OOBSML,863 Ptolemy, 698 Simula,25, 67, 64 Smalltalk, 25 StandardML, 30, 133 VHDL-AMS, 860 XML,865 Xlanguage, 861 leastSquares function, 49 left limit, 202 less function, 324 lessEqual function, 324 limitedupdating, 321 linearmodels,402 linspacefunction, 226 literalconstants, 186 literals, 183 array, 187 Boolean, 186 Enumeration, 187 Integer, 186 Real, 186 record, 187 String, 186 literateprogramming, 714 local class definitions, 80 local Classes, 105 local variables, 75, 94, 286, 293 log function, 200,433,618 log10 function, 20I, 618 lookupprocedure, 97 loop, 185 loops,46, 211, 288 LowPassFilter model,29 LSODAR,673 LSODEI,673 LSODE2,673 lumped, 10
Mathematica, 711 mathematical model, 6, 10 mathematical modeling, 25 MathModelica, 20, 708 MathModelica commands, 847,850 Matlab,45, 207,219 matrices,207 matrix, 220, 221 matrixalgebra,228 matrix function, 44, 45, 62, 80, 88, 103,207,208,213, 214,219,220,224,225 MatrixGain, 168 max attribute,29, 84, 85 max function, 45, 227, 228 maximalfiring petri nets, 460 MBS library,588, 591, 597 mechanical component inertia, 526 rigid, 526 mechanical rotational 1D, 483 mechanical translationallD, 481 mental model,6 messagepassing, 25 min attribute,29,84,85 min function, 45, 227, 228 minus function, 324 mod function, 47, 200, 309, 420 model, 6, 8, 19,22,25, 28, 74, 81, 115, 148, 185 continuousflow, 566 discrete, 566 dynamic, 11 hybrid, 566 tnathematical, 6, 10 mental,6 network,565 physical,6 qualitative, 13 quantitative, 13 static, t t verbal, 6 Model Editor, 712 model parameter, 398 model verification, 696 Modelica,63 Association, iv, 338 StandardLibrary,42,53,55, 147, 159,338,342,615 Modelicascripting,847 Modelicacompiler,700 Modelica.Blocks, 623 Modelica.Blocks.Continuous, 625, 764 Modelica.Blocks.Interfaces, 623, 762 Modelica.Blocks.Math, 625, 760 Modelica.Blocks.Nonlinear, 625, 766 Modelica.Blocks.Sources, 626,769 Modelica.Constants, 617, 751 Modelica.Electrical, 619, 773 Modelica.ElectricaI.Analog, 620, 773 Modelica.Icons, 618, 759 Modelica.Math.Random, 618, 760 Mod elica.Math, 618, 760 Modelica.Mechanics, 627,786 Modelica.Mechanics.Rotational, 628 Modelica.Mechanics.Translational, 630, 786 Modelica.SIunits
894 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica types, 529 Modelica.SIUnits, 618 Modelica.Mechanics.MultiBody, 633,795 Modelica.Mechanics.MultiBody.Examples, 640 Modelica.Mechanics.MultiBody.Interfaces, 636 Modelica.Mechanics.MultiBodyJoints, 636 Modelica.Mechanics.MultiBody.Parts, 636 Modelica.Mechanics.MultiBody.Sensors, 639 Modelica.Mechanics.MultiBody.World, 635 MODELICAPATH,344 modeling, 3, 14 modification, 21,33,91, 119 prefix final, 128 prefix redeclare, 127 prefix replaceable, 127 modification equations, 238 modifications, III ModifiedFiltersInSeries model, 29 modifier hierarchical, 124 in nested extends, 123 in variable declarations, 119 iterative, 120 priority of, 123 protected, 124 single modification, 125 modifier equations, 239, 240 modifiers in array declarations, 120 in constant declarations, 120 in extends, 122 in short class definitions, 122 MoonLanding class, 77 multibody system graph, 597 multibody systems, 502 mechanical, 587 MultiBody.Forces, 596 MultiBody.Frames, 593 MultiBody.Interfaces, 592 MultiBodyJoints, 594 MultiBodyJoints.Assemblies, 596 MultiBody.Parts, 593 MultiBody.Sensors, 596 multidomain models, 162 multiple connections to a single connector, 155 multiple inheritance, 113 name lookup, 96, 340 named arguments. See function, named arguments names, 184, 185 naming conventions, 55 natural semantics, 705 ndims function, 210, 214, 225 neighborhood, 437 nested, 96 nested classes, 80 nested packages, 349 network model, 565 Newton, 63 NMF,63, 867 node, 39, 133, 155 noEvent, 190, 193,201,286,309,415 nominal attribute, 85 nondeclarative constructs, 283 nontlow variables, 171
non-MBS models, 603 normal equations, 238 normal petri nets, 460 not, 185, 188, 196 notEqual function, 324 numerical cancellation, 687 object, 75 object creation, 80 ObjectMath, 63, 858 observable, 5 Ornola, 63, 858 ones function, 226 ontinuous-time, 654 OpenModelica, 699 OpenModelica commands, 847 operators, 183, 188 ·,44,47,188,195,231 ., 188 1,44,47, 188, 195 :=,231 [ ], 188 ",188, 195 +,44,47,188,195,197,231 =, 188, 196 and, 185, 188, 196 associativity, 187 delay, 83,203,308, 309,311,419 der,12,20,60,89,201,286,308,309,311,372,429, 717, 718 equality, 196 logical, 196 miscellaneous, 197 noEvent, 190, 193,201,286,309,415 not, 185, 188, 196 or, 185, 188, 196 overloaded, 323 pre, 83,202,286, 308,309,311,418 precedence, 187 reinit, 83, 202,308,309,311,420 relational, 196 operators:, 196 optional function results, 303 or, 185,188,196 ordering, 103 ordinary differential equations, 399,401,668 oscillating mass, 156 Oscillator model, 156 outer, 93, 99, 172, 173 outerProduct function, 228 outlet, 244 OutPort, 529 output, 28, 35,93,94, 164, 185 output consistency, 286 output variable, 398 outputs, 5 outside connector, 164 overconstrained, 274 overconstrained connection loop, 274
Index 895 overloadeddefinition lookup, 325 package, 53, 54,81,83,92, 133, 148, 185,333-54 naming, 338 packages, 53 encapsulation,352 generic, 346 identification,353 inherited, 347 local, 348 moving, 350 nonencapsulated,349 parameter, 20, 89, 93, 94, 185 parameter subscriptconstraint, 167 parameters, 30, 89, 134, 135, 172 ParametricPlotSimulation, 850 parsed, 57 parsing, 707 partial, 39, 93, 94, 138, 185 partial class, 39 partial differentialequations, 258, 401, 584 PartialDCMotormodel, 163 Particle model, 178 Partic1eslnPointGravity model, 178 passing opaque references,320 POE. See partial differentialequations 2D domain, 270 pendul~,4,598,600,604~605,606,607
Pendulum model, 21 PendulumlmplicitLmodel, 254 Person record, 28, 103 petri nets, 45{}-60 physical domain, 160 physical model, 6 physical modeling, 34, 35, 237 planar pendulum, 21 plot, 20,848 plotParametric,23, 848 PlotSimulation,850 plus function, 324 pneumatic cylinder, 547 PneumaticCylinderVolume model, 548 Pneumatics Library, 646 pointGravity, I78 polynomialequation, 34 polynomialEvaluatorfunction, 47 population dynamics, 556 potential, 535
product design, 14 product function, 159, 227, 228 protected, 26, 46, 77, 88, 93, 124, 185 public, 46, 77,88,93,185 qualitative model, 13 qualitative models, 10 quantitative model, 13 quantity attribute, 85, 374, 375 radiation, 490 range vector, 211 reactive system, 406 real, 85 Real, 23,29, 84, 85, 185, 194,740 receivers, 571 record, 28, 82, 148,305 record field, 75 Record/Class, 102 records, 218 redeclaration, 125 redeclarations annotation, 132 restrictions, 13I redeclare, 91, 93, 127, 133 redefinition, 139 reference declaration, 99 referentially transparent, 283, 284 reinit, 83,202, 249, 308, 309, 311,420 reinit function, 52, 296 reliability, 406 rem function, 200, 309, 420 repetitive connection structures, 244 repetitive equation structures, 33 replaceable, 30, 91, 93, 127, 133 replaceable elements, 129 replaceable redeclaration, 130 requirementsanalysis, 14 reserved words, 184 resistor, 40, 41 ResistorCircuit, 155 ResistorCircuitmodel, 155 ResistorEquationclass, 139 restricted classes, 81 result type mapping, 315 return, 304 reusability, 37, 146 reuse, 28,40, 138, 145 reuse of variable declaration, 138
power function, 324
rigid-body, 505
pre, 83, 202, 286, 308,309, 311,418 predator-preymodel, 557 predefined types, 84, 185 prefixes ordering, 93 pressure, 538 sink, 543 source, 543 PressureEnthalpySource model, 543 primitive connection set, 169, 170 primitive data types, 23 Principia, 63 priority petri nets, 460 ProcessControlmodel, 256 ProcessControl2 model, 257 ProcessControl3 model, 257 product deployment, 15
RML,705 Robert Recorde, 63 Rocket class, 76 RoomInEnvironmentmodel, 552 RotFlange_a, 528 RotFlange_b, 528 Router12,577 Router21,576 routers, 576 runge-kutta methods, 672 sample function, 83, 202, 286, 308, 309, 311, 415 sampled systems, 429 scalar function, 225 scalar functions, 229, 309 scalar index expressions, 217 scalars, 229
896 PeterFritzson Principles of Object-Oriented Modeling and Simulation with Modelica scoping,96 scripting commands,847 SCS, 63 second derivative,399 secondary sensor variables, 687 semantics, 28 senders, 568 set formers, 212 ShirtSizes,86, 217 short class definition,80, 117, 122 side effects, 83, 189,284 SIDOPS+,63, 859 sign conventions, 632 sign function, 193, 199,309,420 signal, 527 signal voltage, 527 SignalVoltage, 527 SimpleCircuit, 35, 58 SimpleCircuitclass, 43 SimpleValveFlow model, 544 simulate, 20, 849 Simulate,851 simulation,3, 7, 8, 14, 577 simulationlanguages, 64 simulationtime, 682 Simulink, 396,403 sin function, 200, 618 singleassignment,238, 239 singleassignmentprinciple, 411 single definitionimport, 336 sinh function,200, 618 size function, 46, 225 skew function, 229, 520 SmallSizes, 102 Smile, 63, 859 smoothfunction, 201, 286, 309, 417 SO,527 softwareand knowledgeengineering,9 softwarecomponentmodel, 36, 145 solar-heated, 4 solver, 20, 41, 57, 94 sorting,61 special operators,285 Speed-Up, 64 Springmodel, 155 sqrt function, 47, 199,298, 309 standardlibraries,55 start attribute,20, 27, 33, 85, 94, 198, 251 start values,25 state, 437 state events, 413 state space form, 60, 382 state variables,686 statements,46, 285 stateSelect,86 statespaceequations,402 static model, 11 Step, 527 stiff: 384 stiff differentialequations, 671 stiffness, 628 Stting, 23,29, 84, 86, 185,186,194 string concatenation, 197, 223 structure, 88
subclass, 29 subcomponent, 9, 38 subconnectors, 366 submatrices,220 subpackages,338 subranges, 102 subscripts, 167 subsystem verification, 15 subtype, 84, 100 subtyping, 194 subtyping definition, 108 subtypinguse, 107 sum function, 45, 227, 228 sum-to-zerocoupling, 148 Sum-to-zerocoupling, 39 superclass,29 supertype, 101 symbolic manipulation, 189 symmetric function,228 synchronousdata-flow principle,239 system design phase, 15 system initialization examples,256 system model, 9, 381 system models examples, 15 systems, 3 artificial,4 biological, 556 ecological,556 economic, 562 mechatronic,524 natural, 4 tan function,200, 618 tanh function, 200, 618 tank system, 385 tatic semantics,703 TCP protocols, 566 TCP SACK, 565, 566, 568, 569 TCP Westwood,565, 566, 568, 569 TCP window size, 565 TempResistormodel, 101 TempResistor3 model, 139 terminal function, 83, 201, 247,286,308,309,311,414 terminate, 249 terminate function, 240, 247, 250, 296, 298, 415 textual model editor, 70I then, 185, 188 thermal systems,488 thermodynamics, 490, 530 thrust, 77 time, 42, 198,243,412,419,445 time constraints,406 time events, 412 time petri nets, 460 time residual, 444 timed petri nets, 460 times function, 324 tolerances,9, 85 top-down modeling,383 top-down physical componentap, 597 transformationmatrix, 509 transition, 438 transpose function,44, 228
Index Triangle model, 26 TripleSprings, 156 TripleSprings model, 156 true, 185,416 Turbines,537 TwoPin class, 39 ~,82,
100,102,185
type checking,209 type conversions, 190 explicit, 191 implicit, 191 type equivalence, 106 type prefixes,94 types, 73, 75 array, 118 Array, 103 Boolean,23,25,29, 84, 86, 185, 186,194 built-in, 29, 73, 84, 101, 185 Class, 104 Enumeration, 84, 86, 102 Function, 104 Integer,23, 29, 84, 86, 185, 186, 194 Real, 23, 29,84,85, 185, 194,740 Record/Class, 102 Strl.ng, 23, 29, 84, 86, 185, 186, 194 subranges, 102 type-specifier, 88 V.L.M. - Allan, 859 unaryMinus function, 324 unaryPlusfunction, 324 unit expressionsyntax, 377 unit attribute, 85, 374, 375 unit conversion,376 units, 10
unqualifiedimport, 337 use before declaration,95 utility functions, 319 validation phase, 15 ValveFlow model, 545 VanDerPolmodel, 22 variability, 89, 194 variable, 398 variable annotation, 360 variable declarations,88 variable specifier, 88 variable-lengthvector, 244 variables, 22, 74,75,94,120 vector algebra, 228 vector function, 225 vectors, 104,207,211,217,220 verbal model, 6 virtual prototypes, 14 voltage, 12, 33 voltage source, 42 watchdog system, 435 when, 185,246,293,295,296,423 when-equations, 245, 246, 252, 253 restrictions,247 single-assignment rule, 248 when-statements, 293 conflicts, 295 restrictions, 296 while, 290 within, 341 YellowClass,31 zeros function, 44, 226
897