TUTORIAL Introduction To Object-Oriented . - Modelica Association

Transcription

TUTORIALIntroduction to Object-OrientedModeling and Simulation withOpenModelicaPeter FritzsonPeter BunusCopyright (c) by Peter FritzsonModelica2006, September 4, 2006, Vienna

AbstractObject-Oriented modeling is a fast-growing area of modeling and simulation that provides a structured,computer-supported way of doing mathematical and equation-based modeling. Modelica is today the mostpromising modeling and simulation language in that it effectively unifies and generalizes previous objectoriented modeling languages and provides a sound basis for the basic concepts.The Modelica modeling language and technology is being warmly received by the world community inmodeling and simulation with major applications in virtual prototyping. It is bringing about a revolution inthis area, based on its ease of use, visual design of models with combination of lego-like predefined modelbuilding blocks, its ability to define model libraries with reusable components, its support for modelingand simulation of complex applications involving parts from several application domains, and many moreuseful facilities. To draw an analogy, Modelica is currently in a similar phase as Java early on, before thelanguage became well known, but for virtual prototyping instead of Internet programming.The tutorial presents an object-oriented component-based approach to computer supportedmathematical modeling and simulation through the powerful Modelica language and its associatedtechnology. Modelica can be viewed as an almost universal approach to high level computationalmodeling and simulation, by being able to represent a range of application areas and providing generalnotation as well as powerful abstractions and efficient implementations.The tutorial gives an introduction to the Modelica language to people who are familiar with basicprogramming concepts. It gives a basic introduction to the concepts of modeling and simulation, as well asthe basics of object-oriented component-based modeling for the novice, and an overview of modeling andsimulation in a number of application areas.The tutorial has several goals: Being easily accessible for people who do not previously have a background in modeling,simulation.Introducing the concepts of physical modeling, object-oriented modeling and component-basedmodeling and simulation.Giving an introduction to the Modelica language.Demonstrating modeling examples from several application areas.Giving a possibility for hands-on exercises.

Presenter’s dataPeter Fritzson is a Professor and Director of the Programming Environment Laboratory (Pelab), at theDepartment of Computer and Information Science, Linköping University, Sweden. He holds the positionof Director of Research and Development of MathCore Engineering AB. Peter Fritzson is chairman of theScandinavian Simulation Society, secretary of the European simulation organization, EuroSim; and vicechairman of the Modelica Association, an organization he helped to establish. His main area of interest issoftware engineering, especially design, programming and maintenance tools and environments.Peter Bunus is an Assistant Professor at the Programming Environment Laboratory at Department ofComputer and Information Science, Linköping University, Sweden. His primary research interests are inthe area of program analysis, model-based diagnosis, debugging of declarative languages, and modelingand simulation environments design.1. Useful Web LinksThe Modelica Association Web Pagehttp://www.modelica .orgModelica htmlModelica related research and the OpenModelica open source project at Linköping University withdownload of the OpenModelica system and link to download of MathModelica Lite.http://www.ida.liu.se/ pelab/modelica/OpenModelica.htmlThe Proceedings of 5th International Modelica Conference, September 4-5, 2006, Vienna, 06/The Proceedings of 4th International Modelica Conference, March 7-8, 2005, Hamburg 05/The Proceedings of 3rd International Modelica Conference, November 3-4, 2004, Linköping 3/The Proceedings of 2nd International Modelica Conference, March 18-19, 2002, "Deutsches Zentrum furLuft- und Raumfahrt" at Oberpfaffenhofen, 002/The Proceedings of Modelica Workshop, October 23 - 24, 2000, Lund University, Swedenhttp://www.modelica.org/events/workshop2000/

2. Contributors to the Modelica Language, version 2.2Bernhard Bachmann , University of Applied Sciences, Bielefeld, GermanyJohn Batteh, Ford Motor Company, Dearborn, MI, U.S.A.Dag Brück, Dynasim, Lund, SwedenFrancesco Casella, Politecnico di Milano, Milano, ItalyChristoph Clauß, Fraunhofer Institute for Integrated Circuits, Dresden, GermanyJonas Eborn, Modelon AB, Lund, SwedenHilding Elmqvist, Dynasim, Lund, SwedenRüdiger Franke, ABB Corporate Research, Ladenburg, GermanyPeter Fritzson, Linköping University, SwedenAnton Haumer, Technical Consulting & Electrical Engineering, St.Andrae-Woerdern, AustriaChristian Kral, arsenal research, Vienna, AustriaSven Erik Mattsson, Dynasim, Lund, SwedenChuck Newman, Ford Motor Company, Dearborn, MI, U.S.A.Hans Olsson, Dynasim, Lund, SwedenMartin Otter, German Aerospace Center, Oberpfaffenhofen, GermanyMarkus Plainer, Arsenal Research, Vienna, AustriaAdrian Pop, Linköping University, SwedenKatrin Prölß, Technical University Hamburg-Harburg, GermanyAndré Schneider, Fraunhofer Institute for Integrated Circuits, Dresden, GermanyChristian Schweiger, German Aerospace Center, Oberpfaffenhofen, GermanyMichael Tiller, Ford Motor Company, Dearborn, MI, U.S.A.Hubertus Tummescheit, Modelon AB, Lund, SwedenHans-Jürg Wiesmann, ABB Switzerland Ltd.,Corporate Research, Baden, Switzerland

Principles of Object-OrientedModeling and Simulationwith ModelicaPeter FritzsonPeter BunusLinköping University, Dept. of Comp. & Inform. ScienceSE 581-83, Linköping, Sweden{petfr,petbu}@ida.liu.seCourse Based on Recent Book, 2004Peter FritzsonPrinciples of Object OrientedModeling and Simulation withModelica 2.1Wiley-IEEE Press940 pages2Copyright Peter Fritzsonpelab

Acknowledgements, Usage, Copyrights If you want to use the Powerpoint version of these slidesin your own course, send an email to:peter.fritzson@ida.liu.se Thanks to Emma Larsdotter Nilsson for contributions tothe layout of these slides Most examples and figures in this tutorial are adaptedwith permission from Peter Fritzson’s book ”Principles ofObject Oriented Modeling and Simulation with Modelica2.1”, copyright Wiley-IEEE Press Some examples and figures reproduced with permissionfrom Modelica Association, Martin Otter, Hilding Elmqvist Modelica Association: www.modelica.org OpenModelica: www.ida.liu.se/projects/OpenModelica3Copyright Peter FritzsonpelabOutline Introduction to Modeling and Simulation Modelica - The next generation modeling andSimulation Language Classes Components, Connectors and Connections Equations Discrete Events and Hybrid Systems Algorithm and Functions Modeling and Simulation Environments Demonstrations4Copyright Peter Fritzsonpelab

Why Modeling & Simulation ? Increase understanding of complex systemsDesign and optimizationVirtual prototypingVerificationBuild more complex systems5pelabCopyright Peter FritzsonWhat is a system? A system is an object or collection ofobjects whose properties we want to study Natural and artificial systems Reasons to study: curiosity, to build itCollectorHot waterStorage tankHeaterElectricityCold water6Copyright Peter FritzsonPumppelab

Examples of Complex Systems Power plantsHardware-in-the-loop,real-time simulationCopyright Peter FritzsonpelabExperimentsAn experiment is the process of extracting informationfrom a system by exercising its inputsProblems Experiment might be too expensive Experiment might be too dangerous System needed for the experiment might not yet exist8Copyright Peter Fritzsonpelab

Model conceptA model of a system is anything an experiment can beapplied to in order to answer questions about that systemKinds of models: Mental model – statement like “a person is reliable”Verbal model – model expressed in wordsPhysical model – a physical object that mimics the systemMathematical model – a description of a system wherethe relationships are expressed in mathematical form – avirtual prototype Physical modeling – also used for mathematical modelsbuilt/structured in the same way as physical models9Copyright Peter FritzsonpelabSimulationA simulation is an experiment performed on a modelExamples of simulations: Industrial process – such as steel or pulpmanufacturing, study the behaviour under differentoperating conditions in order to improve the process Vehicle behaviour – e.g. of a car or an airplane, foroperator training Packet switched computer network – study behaviourunder different loads to improve performance10Copyright Peter Fritzsonpelab

Reasons for Simulation Suppression of second-order effects Experiments are too expensive, too dangerous, orthe system to be investigated does not yet exist The time scale is not compatible with experimenter(Universe, million years, ) Variables may be inaccessible. Easy manipulation of models Suppression of disturbances11Copyright Peter FritzsonpelabDangers of SimulationFalling in love with a modelThe Pygmalion effect (forgetting that model is not the realworld, e.g. introduction of foxes to hunt rabbits in Australia)Forcing reality into the constraints of a modelThe Procrustes effect (e.g. economic theories)Forgetting the model’s level of accuracySimplifying assumptions12Copyright Peter Fritzsonpelab

Building Models Based on KnowledgeSystem knowledge The collected general experience in relevant domains The system itselfSpecific or generic knowledge E.g. software engineering knowledge13Copyright Peter FritzsonpelabKinds of Mathematical Models Dynamic vs. Static models Continuous-time vs. Discrete-time dynamic models Quantitative vs. Qualitative models14Copyright Peter Fritzsonpelab

Dynamic vs. Static ModelsA dynamic model includes time in the modelA static model can be defined without involving timeResistor voltage – static systemInput currentpulseCapacitor voltage - dynamictime15pelabCopyright Peter FritzsonContinuous-Time vs.Discrete-Time Dynamic ModelsContinuous-time models may evolve their variable valuescontinuously during a time periodDiscrete-time variables change values a finite number of timesduring a time periodContinuousDiscretetime16Copyright Peter Fritzsonpelab

Quantitative vs. Qualitative ModelsResults in qualitative dataVariable values cannot be represented numericallyMediocre 1, Good 2, Tasty 3, Superb 4SuperbTastyGoodMediocretimeQuality of food in a restaurant accordingto inspections at irregular points in time17pelabCopyright Peter FritzsonUsing Modeling and Simulationwithin the Product Design-VLevel of AbstractionExperience ecificationProduct verification anddeploymentPreliminary feature designDesignIntegrationArchitectural design andsystem functional designDesignRefinementVerificationDetailed feature design andimplementationSubsystem level integration testcalibration and verificationSubsystem level integration andverificationComponent verificationRealizationDocumentation, Version and Configuration Management18Copyright Peter Fritzsonpelab

Principles of Equation-Based Modeling Each icon represents a physical componenti.e. Resistor, mechanical Gear Box, Pump Composition lines represent the actualphysical connections i.e. electrical line,mechanical connection, heat flow Variables at the interfaces describeinteraction with other componentComponent 1 Physical behavior of a component isdescribed by equationsComponent 3Component 2Connection Hierarchical decomposition of components19pelabCopyright Peter FritzsonApplication Example – Industry Robotk2iqddRefqdRefqRef11SSk1axis6cut el0.03Jmotor JpSumKvsumw Sum 1-0.3 1-rate2rate3b(s)340.8a(s)Sjoint 0axis4SiRefgear ifric Rv0qRefspring C 0.004*D/w mRd1 100Rp1 200Rd2 100Ri 10-- diff pow er OpIRa 250 La (250/(2*D*wm))Rp2 50qdaxis1VsRd4 100emfyxinertialRd3 100Srel n*transpose(n) (identity(3)- n*transpose(n))*cos(q)skew(n)*sin(q);g3wrela n*qd;g1zrela n*qdd;Sb Sa*transpose(Srel);r0b r0a;hall1vb Srel*va;wb Srel*(wa wrela);g4ab Srel*aa;qdg2zb Srel*(za zrela cross(wa, wrela));hall2wrqCourtesy of Martin Otter20Copyright Peter Fritzsonpelab

GTX Gas Turbine Power Cutoff MechanismHelloCourtesy of Siemens Industrial Turbomachinery AB21Copyright Peter FritzsonDevelopedby MathCorefor SiemenspelabModelica –The Next GenerationModeling Language22Copyright Peter Fritzsonpelab

Stored KnowledgeModel knowledge is stored in books and humanminds which computers cannot access“The change of motion is proportionalto the motive force impressed “– Newton23Copyright Peter FritzsonpelabThe Form – Equations Equations were used in the third millennium B.C. Equality sign was introduced by Robert Recorde in 1557Newton still wrote text (Principia, vol. 1, 1686)“The change of motion is proportional to the motive force impressed ”CSSL (1967) introduced a special form of “equation”:variable expressionv INTEG(F)/mProgramming languages usually do not allow equations!24Copyright Peter Fritzsonpelab

Modelica – The Next Generation ModelingLanguageDeclarative languageEquations and mathematical functions allow acausal modeling,high level specification, increased correctnessMulti-domain modelingCombine electrical, mechanical, thermodynamic, hydraulic,biological, control, event, real-time, etc.Everything is a classStrongly typed object-oriented language with a general classconcept, Java & MATLAB-like syntaxVisual component programmingHierarchical system architecture capabilitiesEfficient, non-proprietaryEfficiency comparable to C; advanced equation compilation,e.g. 300 000 equations, 150 000 lines on standard PC25Copyright Peter FritzsonpelabModelica – The Next Generation ModelingLanguageHigh level languageMATLAB-style array operations; Functional style; iterators,constructors, object orientation, equations, etc.MATLAB similaritiesMATLAB-like array and scalar arithmetic, but strongly typed andefficiency comparable to C.Non-Proprietary Open Language Standard Both Open-Source and Commercial implementationsFlexible and powerful external function facility LAPACK interface effort started26Copyright Peter Fritzsonpelab

Modelica Language Properties Declarative and Object-Oriented Equation-based; continuous and discrete equations Parallel process modeling of real-time applications,according to synchronous data flow principle Functions with algorithms without global side-effects(but local data updates allowed) Type system inspired by Abadi/Cardelli Everything is a class – Real, Integer, models,functions, packages, parameterized classes.27Copyright Peter FritzsonpelabObject OrientedMathematical Modeling with Modelica The static declarative structure of a mathematicalmodel is emphasized OO is primarily used as a structuring concept OO is not viewed as dynamic object creation andsending messages Dynamic model properties are expressed in adeclarative way through equations. Acausal classes supports better reuse of modelingand design knowledge than traditional classes28Copyright Peter Fritzsonpelab

Brief Modelica History First Modelica design group meeting in fall 1996 International group of people with expert knowledgein both language design and physical modeling Industry and academia Modelica Versions 1.0 released September 1997 2.0 released March 2002 Latest version, 2.2 released March 2005 Modelica Association established 2000 Open, non-profit organization29Copyright Peter FritzsonpelabModelica Conferences The 1st International Modelica conference October,2000 The 2nd International Modelica conference March 1819, 2002 The 3rd International Modelica conference November5-6, 2003 in Linköping, Sweden The 4th International Modelica conference March 6-7,2005 in Hamburg, Germany The 5th International Modelica conference plannedSeptember 4-5, 2006 in Vienna, Austria30Copyright Peter Fritzsonpelab

Modelica Classes andInheritance1pelabCopyright Peter FritzsonSimplest Model – Hello World!A Modelica “Hello World” modelEquation: x’ - xInitial condition: x(0) 1class HelloWorld "A simple equation"Real x(start 1);equationder(x) -x;end HelloWorld;Simulation in OpenModelica environment1simulate(HelloWorld, stopTime 2)plot(x)0.80.60.40.20.521Copyright Peter Fritzson1.52pelab

Another ExampleInclude algebraic equationAlgebraic equations containno derivativesclass DAEexampleReal x(start 0.9);Real y;equationder(y) (1 0.5*sin(y))*der(x) sin(time);x - y exp(-0.9*x)*cos(y);end DAEexample;Simulation in OpenModelica environment1.20simulate(DAEexample, stopTime pelabCopyright Peter FritzsonExample class: Van der Pol Oscillatorclass VanDerPol "Van der Pol oscillator model"Real x(start 1) "Descriptive string for x"; //Real y(start 1) "y coordinate";//parameter Real lambda 0.3;equationder(x) y;// This is theder(y) -x lambda*(1 - x*x)*y; /* This is theend VanDerPol;x starts at 1y starts at 11st diff equation //2nd diff equation */2simulate(VanDerPol,stopTime 25)plotParametric(x,y)1-2-112-1-24Copyright Peter Fritzsonpelab

Small Exercise Locate the HelloWorld model in DrModelica usingOMNotebook! Simulate and plot the example. Do a slight change inthe model, re-simulate and re-plot.class HelloWorld "A simple equation"Real x(start 1);equationder(x) -x;end HelloWorld;simulate(HelloWorld, stopTime 2)plot(x) Locate the VanDerPol model in DrModelica and try it!5Copyright Peter FritzsonpelabVariables and ConstantsBuilt-in primitive data typesBooleantrue or falseIntegerInteger value, e.g. 42 or –3RealFloating point value, e.g. 2.4e-6StringString, e.g. “Hello world”Enumeration Enumeration literal e.g. ShirtSize.Medium6Copyright Peter Fritzsonpelab

Variables and Constants cont’ Names indicate meaning of constantEasier to maintain codeParameters are constant during simulationTwo types of constants in Modelica constant ingIntegerRealPI 3.141592653589793;redcolor "red";one 1;mass 22.5;pelabCopyright Peter FritzsonComments in Modelica1) Declaration comments, e.g. Real x "state variable";class VanDerPol "Van der Pol oscillator model"Real x(start 1) "Descriptive string for x”; //Real y(start 1) "y coordinate”;//parameter Real lambda 0.3;equationder(x) y;// This is theder(y) -x lambda*(1 - x*x)*y; /* This is theend VanDerPol;x starts at 1y starts at 11st diff equation //2nd diff equation */2) Source code comments, disregarded by compiler2a) C style, e.g. /* This is a C style comment */2b) C style, e.g. // Comment to the end of the line 8Copyright Peter Fritzsonpelab

A Simple Rocket Modelapollo13thrustaltitude′ velocityvelocity ′ accelerationmgnew modelparameters (changeablebefore the simulation)floating pointtypedifferentiation withregards to time9thrust mass gravitymassmass ′ massLossRate abs ( thrust )acceleration Rocketclass Rocket "rocket class"parameter String name;Real mass(start 1038.358);Real altitude(start 59404);Real velocity(start -2003);Real acceleration;Real thrust; // Thrust force on rocketReal gravity; // Gravity forcefieldparameter Real massLossRate 0.000277;equation(thrust-mass*gravity)/mass acceleration;der(mass) -massLossRate * abs(thrust);der(altitude) velocity;der(velocity) acceleration;end Rocket;declarationcommentstart valuename default valuemathematicalequation (acausal)pelabCopyright Peter FritzsonCelestial Body ClassA class declaration creates a type name in Modelicaclass CelestialBodyconstant Realparameter Realparameter Stringparameter Realend CelestialBody;g 6.672e-11;radius;name;mass;An instance of the class can bedeclared by prefixing the typename to a variable name.CelestialBody moon;.The declaration states that moon is a variablecontaining an object of type CelestialBody10Copyright Peter Fritzsonpelab

Moon LandingRocketapollo13thrustapollo. gravity mgaltitudeCelestialBodyonly accessinside the classaccess by dotnotation outsidethe class11moon. g moon.mass(apollo.altitude moon.radius )2class MoonLandingparameter Real force1 36350;parameter Real force2 1308;protectedparameter Real thrustEndTime 210;parameter Real thrustDecreaseTime 43.2;publicRocketapollo(name "apollo13");CelestialBodymoon(name "moon",mass 7.382e22,radius 1.738e6);equationapollo.thrust if (time thrustDecreaseTime) then force1else if (time thrustEndTime) then force2else 0;apollo.gravity moon.g*moon.mass/(apollo.altitude moon.radius) 2;end MoonLanding;pelabCopyright Peter FritzsonSimulation of Moon Landingsimulate(MoonLanding, stopTime 230)plot(apollo.altitude, xrange {0,208})plot(apollo.velocity, xrange 00-3005000-40050100150200It starts at an altitude of 59404(not shown in the diagram) attime zero, gradually reducing ituntil touchdown at the lunarsurface when the altitude is zero12Copyright Peter FritzsonThe rocket initially has a highnegative velocity when approachingthe lunar surface. This is reduced tozero at touchdown, giving a smoothlandingpelab

Restricted Class Keywords The class keyword can be replaced by other keywords, e.g.: model,record, block, connector, function, . Classes declared with such keywords have restrictions Restrictions apply to the contents of restricted classes Example: A model is a class that cannot be used as a connector class Example: A record is a class that only contains data, with no equations Example: A block is a class with fixed input-output causalitymodel CelestialBodyconstant Realparameter Realparameter Stringparameter Realend CelestialBody;13g 6.672e-11;radius;name;mass;pelabCopyright Peter FritzsonModelica Functions Modelica Functions can be viewed as a specialkind of restricted class with some extensions A function can be called with arguments, and isinstantiated dynamically when called More on functions and algorithms later inLecture 4function suminput Real arg1;input Real arg2;output Real result;algorithmresult : arg1 arg2;end sum;14Copyright Peter Fritzsonpelab

Inheritanceparent class to Colorrestricted kindof class withoutequationschild class orsubclasskeyworddenotinginheritancerecord ColorDataparameter Real red 0.2;parameter Real blue 0.6;Realgreen;end ColorData;class Colorextends ColorData;equationred blue green 1;end Color;class ExpandedColorparameter Real red 0.2;parameter Real blue 0.6;Real green;equationred blue green 1;end ExpandedColor;Data and behavior: field declarations, equations, andcertain other contents are copied into the subclass15pelabCopyright Peter FritzsonInheriting definitionsrecord ColorDataparameter Real red 0.2;parameter Real blue 0.6;Realgreen;end ColorData;class ErrorColorextends ColorData;parameter Real blue 0.6;parameter Real red 0.3;equationred blue green 1;end ErrorColor;16Copyright Peter FritzsonLegal!Identical to theinherited field blueIllegal!Same name, butdifferent valueInheriting multipleidenticaldefinitions resultsin only onedefinitionInheritingmultiple differentdefinitions of thesame item is anerrorpelab

Inheritance of Equationsclass Colorparameter Real red 0.2;parameter Real blue 0.6;Real green;equationred blue green 1;end Color;Color is identical to Color2Same equation twice leavesone copy when inheritingclass Color2 // OK!extends Color;equationred blue green 1;end Color2;class Color3 // Error!extends Color;equationred blue green 1.0;// also inherited: red blue green 1;end Color3;17Color3 is overdeterminedDifferent equations meanstwo equations!pelabCopyright Peter FritzsonMultiple InheritanceMultiple Inheritance is fine – inheriting both geometry and colorclass Colorparameter Real red 0.2;parameter Real blue 0.6;Real green;equationred blue green 1;end Color;class PointReal x;Real y,z;end Point;multiple inheritanceclass ColoredPointWithoutInheritanceReal x;Real y, z;parameter Real red 0.2;parameter Real blue 0.6;Real green;equationred blue green 1;end ColoredPointWithoutInheritance;18Copyright Peter Fritzsonclass ColoredPointextends Point;extends Color;end ColoredPoint;Equivalent topelab

Multiple Inheritance cont’Only one copy of multiply inherited class Point is keptclass PointReal x;Real y;end Point;class VerticalLineextends Point;Real vlength;end VerticalLine;Diamond Inheritanceclass HorizontalLineextends Point;Real hlength;end HorizontalLine;class Rectangleextends VerticalLine;extends HorizontalLine;end Rectangle;19pelabCopyright Peter FritzsonSimple Class Definition –Shorthand Case of Inheritance Example:class SameColor Color;Equivalent to:inheritance20class SameColorextends Color;end SameColor;Copyright Peter Fritzson Often used forintroducing newnames of types:type Resistor Real;connector MyPin Pin;pelab

Inheritance Through Modification Modification is a concise way of combininginheritance with declaration of classes orinstances A modifier modifies a declaration equation in theinherited class Example: The class Real is inherited, modifiedwith a different start value equation, andinstantiated as an altitude variable:.Real altitude(start 59404);.21pelabCopyright Peter FritzsonThe Moon LandingExample Using Bodymodel Body "generic body"Realmass;String name;end Body;model CelestialBodyextends Body;constant Real g 6.672e-11;parameter Real radius;end CelestialBody;22Copyright Peter Fritzsonmodel Rocket "generic rocket class"extends Body;parameter Real massLossRate 0.000277;Real altitude(start 59404);Real velocity(start -2003);Real acceleration;Real thrust;Real gravity;equationthrust-mass*gravity mass*acceleration;der(mass) -massLossRate*abs(thrust);der(altitude) velocity;der(velocity) acceleration;end Rocket;pelab

The Moon LandingExample using Inheritance cont’inheritedparametersmodel MoonLandingparameter Real force1 36350;parameter Real force2 1308;parameter Real thrustEndTime 210;parameter Real thrustDecreaseTime 43.2;Rocketapollo(name "apollo13", mass(start 1038.358) );CelestialBodymoon(mass 7.382e22,radius 1.738e6,name "moon");equationapollo.thrust if (time thrustDecreaseTime) then force1else if (time thrustEndTime) then force2else 0;apollo.gravity moon.g*moon.mass/(apollo.altitude moon.radius) 2;end Landing;23pelabCopyright Peter FritzsonInheritance of Protected ElementsIf an extends-clause is preceded by the protected keyword,all inherited elements from the superclass become protectedelements of the subclassclass PointReal x;Real y,z;end Point;class ColorReal red;Real blue;Real green;equationred blue green 1;end Color;The inherited fields from Point keeptheir protection status since thatextends-clause is preceded bypublicA protected element cannot beaccessed via dot notation!24Copyright Peter Fritzsonclass ColoredPointprotectedextends Color;publicextends Point;end ColoredPoint;Equivalent toclass ColoredPointWithoutInheritanceReal x;Real y,z;protected Real red;protected Real blue;protected Real green;equationred blue green 1;end ColoredPointWithoutInheritance;pelab

Advanced Topic Class parameterization25pelabCopyright Peter FritzsonGeneric Classes with Type Parametersclass Creplaceable class ColoredClass GreenClass;ColoredClassobj1(p1 5);replaceable YellowClass obj2;ColoredClassobj3;RedClassobj4;equationend C;Formal class parameters arereplaceable variable or typedeclarations within the class (usually)marked with the prefix replaceableActual arguments to classes aremodifiers, which when containingwhole variable declarations ortypes are preceded by the tobj1GreenClassobj3A yellowobjectColoredClassA redobjectobj226class C2 C(redeclare class ColoredClass BlueClass);Copyright Peter Fritzsonobj4Equivalent toclass C2BlueClassYellowClassBlueClassRedClassequationend C2;obj1(p1 5);obj2;obj3;obj4;pelab

Class Parameterization when Class Parametersare ComponentsR1ACR2L12The class ElectricalCircuit has beenconverted into a parameterized genericclass GenericElectricalCircuit withthree formal class parameters R1, R2, R3,marked by the keyword replaceableR3GClassparameterizationclass ElectricalCircuitResistor R1(R 100);Resistor R2(R 200);Resistor R3(R 300);Inductor L1;SineVoltage AC;Groung nnect(R1.n,R3.n);connect(R1.p,AC.p);.end ElectricalCircuit;27class GenericElectricalCircuitreplaceable Resistor R1(R 100);replaceable Resistor R2(R 200);replaceable Resistor R3(R 300);Inductor L1;SineVoltage AC;Groung nnect(R1.n,R3.n);connect(R1.p,AC.p);.end GenericElectricalCircuit;pelabCopyright Peter FritzsonClass Parameterization when Class Parametersare Components - cont’R1ACA more specialized class TemperatureElectricalCircuit iscreated by changing the types of R1, R3, to TempResistorR2L12R3class TemperatureElectricalCircuit GenericElectricalCircuit (redeclare TempResistor R1redeclare TempResistor R3);GWe add a temperature variable Temp forclass TemperatureElectricalCircuitthe temperature of the resistor circuitparameter Real Temp 20;and modifiers for R1 and R3 which areextends GenericElectricalCircuit(now TempRes

The tutorial presents an object-oriented component-based approach to computer supported mathematical modeling and simulation through the powerful Modelica language and its associated technology. Modelica can be viewed as an almost universal approach to high level computational