Tools and Methods for Analysis, Debugging, and Performance Improvement of Equation-Based Models - PDF

Please download to get full document.

View again

of 125
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Information Report
Category:

Small Business & Entrepreneurship

Published:

Views: 2 | Pages: 125

Extension: PDF | Download: 0

Share
Related documents
Description
Linköping Studies in Science and Technology Dissertations. No Tools and Methods for Analysis, Debugging, and Performance Improvement of Equation-Based Models by Martin Sjölund Department of Computer
Transcript
Linköping Studies in Science and Technology Dissertations. No Tools and Methods for Analysis, Debugging, and Performance Improvement of Equation-Based Models by Martin Sjölund Department of Computer and Information Science Linköping University SE Linköping, Sweden Linköping 2015 Copyright c 2015 Martin Sjölund ISBN ISSN Printed by LiU Tryck 2015 URL: Abstract Equation-based object-oriented (EOO) modeling languages such as Modelica provide a convenient, declarative method for describing models of cyber-physical systems. Because of the ease of use of EOO languages, large and complex models can be built with limited effort. However, current state-of-the-art tools do not provide the user with enough information when errors appear or simulation results are wrong. It is of paramount importance that such tools should give the user enough information to correct errors or understand where the problems that lead to wrong simulation results are located. However, understanding the model translation process of an EOO compiler is a daunting task that not only requires knowledge of the numerical algorithms that the tool executes during simulation, but also the complex symbolic transformations being performed. As part of this work, methods have been developed and explored where the EOO tool, an enhanced Modelica compiler, records the transformations during the translation process in order to provide better diagnostics, explanations, and analysis. This information is used to generate better error-messages during translation. It is also used to provide better debugging for a simulation that produces unexpected results or where numerical methods fail. Meeting deadlines is particularly important for real-time applications. It is usually essential to identify possible bottlenecks and either simplify the model or give hints to the compiler that enable it to generate faster code. When profiling and measuring execution times of parts of the model the recorded information can also be used to find out why a particular system model executes slowly. Combined with debugging information, it is possible to find out why this system of equations is slow to solve, which helps understanding what can be done to simplify the model. A tool with a graphical user interface has been developed to make debugging and performance profiling easier. Both debugging and profiling have been combined into a single view so that performance metrics are mapped to equations, which are mapped to debugging information. The algorithmic part of Modelica was extended with meta-modeling constructs (MetaModelica) for language modeling. In this context a quite general approach to debugging and compilation from (extended) Modelica to C code was developed. That makes it possible to use the same executable format for simulation executables as for compiler bootstrapping when the compiler written in MetaModelica compiles itself. Finally, a method and tool prototype suitable for speeding up simulations has been developed. It works by partitioning the model at appropriate places and compiling a simulation executable for a suitable parallel platform. Populärvetenskaplig sammanfattning Som ingenjör lär man sig att förstå världen genom ekvationer. För att beskriva eller modellera ett fysikaliskt system, till exempel vid utveckling av en produkt, vill ingenjören använda sig av de ekvationer som han eller hon lärt sig från böcker eller föreläsningar. Vid produktutveckling kan ett av målen med modellen vara att hitta de bästa parametrarna för att få den snabbaste, mest hållfasta eller billigaste lösningen. Man vill således använda en dator för att göra en simulering av modellen, men de instruktioner en dator tar körs i sekvens och gör i grund och botten bara en massa beräkningar och tilldelningar till olika minnespositioner. De klassiska programmeringsparadigmerna, exempelvis imperativ programmering, fungerar på liknande sätt man skriver en algoritm som körs på uppifrån och ner. Den här avhandlingen fokuserar på ekvationsbaserade programmeringsspråk. I ekvationsbaserade programmeringsspråk, till exempel Modelica, översätts ekvationer till imperativ kod, som lätt kan översättas till maskinkod. Detta gör alltså att en ingenjör som är duktig på modellering och ekvationer kan simulera sina modeller på ett effektivt sätt utan att vara datavetare och ha en djup kunskap om programmering. Problemet är att man vid översättning från ekvationer till maskinkod tappar en massa användbar information. Om ett fel inträffar vid simulering av modellen så vill man få reda på var felet kommer ifrån. Tidigare har detta varit inte varit möjligt, men i avhandlingen introduceras en metod som sparar tillräckligt med information för att visa vilken ekvation felet inträffade i och alla de symboliska operationer som utförts på ekvationen. Informationen kan sedan visas i en grafisk debugger. För att kunna simulera i realtid, till exempel en körsimulator där en människa kör en simulerad bil, så måste datorn kunna lösa ekvationer runt 100 gånger i sekunden för att illusionen av att det är en simulering inte ska förstöras. Om ett ekvationssystem är alldeles för detaljerat så tar det för lång tid att köra det. I avhandlingen kombineras möjligheten att mäta körtid av ekvationer med den grafiska debuggern. Då ser man inte enbart vilka ekvationer som tar lång tid att köra, utan även varför de tar lång tid att köra. Ekvationerna kan sedan förenklas för att kunna köra simuleringen i realtid. Acknowledgements Thank you everyone who helped make this thesis come true. The list of everyone involved would be very long indeed. Without my supervisor, Peter Fritzson, this thesis would never have seen the light of day. Peter not only guided me to some interesting topics of research, he also obtained the funding and managed those projects. Most of my travels resulted in something useful, rather than sitting through meaningless meetings. This meant I had time to work on projects I enjoy, although some of this took place during the slower parts of meetings. Thanks to all my former and present colleagues at IDA. Especially to PELAB for being there during all those coffee breaks. Relaxing a few minutes a day makes all the difference in the world. I would like to thank everyone who contributed to the OpenModelica project. I would like to especially thank the people providing bug fixes and improved the parts of the OpenModelica kernel I most often use: Adrian Pop, Per Östlund, Jens Frenkel, Willi Braun, Lennart Ochel, and Mahder Gebremedhin. Adeel Asghar for developing the graphical user interfaces, in particular for helping develop the user interface for the debuggers presented in the thesis. My work was strongly dependent on everything working together as well as it did. Francesco Casella, thanks for providing the many examples and problems that eventually led me to start working on the Modelica debugger. As we are mostly concerned with compiler construction and the development environment at PELAB it helped to have someone around who used Modelica for modeling. Thanks to Bodil Mattsson Kihlström, Åsa Kärrman, Eva Pelayo Danils, and Liselotte Lundberg. You all did a great job as PELAB administrators, mostly making sure I actually signed all those travel expense reports and attached everything that should be there (back when paperword was not sent directly to the payroll department). Anne Moe, thank you for dealing with all the paperwork and tracking my progress as well as making sure I took all my courses, signed all the papers, and did all the work required to get a doctorate. It was not always easy since I was enrolled in multiple graduate schools and had multiple employers. My family deserves my thanks for making me the man I am today. While most of you do not understand precisely what I do, you have still always supported me. Finally, Peter and Adrian are mentioned above. Thanks for helping me put together my thesis and getting all the pieces to fall into place. Lili Zhu, thanks for constantly reminding me when I was not working on the thesis. This work has been supported by Vinnova in the RTSIM and ITEA2 OPENPROD and MODRIO projects, the Swedish Strategic Research Foundation (SSF) in the Proviking HIPo and EDOP projects, the National Graduate School of Computer Science (CUGS). The Open Source Modelica Consortium supports the OpenModelica project. Martin Sjölund Linköping, April 7, 2015 Contents 1 Introduction Motivation Contributions Structure Background Modelica Modelica Association Modelica Standard Library OpenModelica MetaModelica Pattern Matching Semantics Pattern Matching Fail Semantics Data Types Lists Tuples Option Types MetaModelica Array Types Union Types An Expression Interpreter Compiler Bootstrapping Symbolic Manipulation Variable-Equation Dependencies Sorting and Matching Block Lower Triangular Matrix Tearing of Nonlinear Systems of Equations.. 38 i ii CONTENTS 3 Debugging Background Comparison with Traditional Debugging Sources of Errors and Faults Over- and Under-constrained Systems Errors in the Evaluation of Expressions Assertion Violations in Models Errors in the Solution of Implicit Algebraic Equations Errors in the Integration of the ODEs Common Symbolic Operations Variable Aliasing Known Variables Equation Solving Expression Simplification Equation System Simplification Differentiation Index Reduction Function Inlining Scalarization Debugging Equation-based Models Bookkeeping of Operations Variable Substitution Equation Solving Expression Simplification Equation System Simplification Differentiation Index Reduction Function Inlining Scalarization Display of Operations Simulation Runtime Implementation Results JSON Schema Algorithmic Code Debugger Algorithmic Code Debugger Implementation Summary and Discussion CONTENTS iii 4 Profiling Standard Profiling Tools gprof Valgrind Connection to Debugging Implementation Using Profiling Data Summary and Discussion Graphical User Interface and Usage Examples Introducing a Runtime Error Using the Profiler Inspecting Transformations Use Case: Common Subexpression Elimination Use Case: Finding Bugs in the Compiler Using the Algorithmic Code Debugger Combining the Algorithmic Code Debugger and Transformations Browser Summary and Discussion Compiler Bootstrapping Introduction Specification of Language Constructs Vision Extensible Tools Motivation for Compiler Bootstrapping Stages of Bootstrapping OMC Implementation Compiler Platform Availability Language Feature Implementations Pattern Matching Implementation Type Design and Implementations Polymorphism Runtime System Data Layout Foreign Function Interface Built-in MetaModelica Functions Garbage Collection Issues MMC Problems iv CONTENTS OpenModelica Issues Modelica Problems Separate Compilation Implementation Steps in detail Performance Performance Benchmarks Comparison with Old Benchmarks Comparison with Latest OMC Version Algorithmic Code Debugger Related Work Summary and Discussion Parallel Simulation by TLM-Style Decoupling Background Related Work Transmission Line Element Method Hopsan Hopsan-Modelica Differences Example Model: Pressure Relief Valve TLM in an Equation-based Language Partitioning Algorithm Distributed Solver Parallel Performance Thread Safety Summary and Discussion Modelica-based Approach FMI-based Approach Stand-alone TLM Simulator Conclusion Future Work A Flat Modelica 173 B Translated Code 179 C Generated Code Fragments 191 CONTENTS v D Transformations Browser JSON Schema 195 E Debugging Package 199 F MetaModelica Example: Expression Interpreter 211 G TLM Example 217 References 223 vi CONTENTS List of Figures 2.1 Simple RC circuit Simple RC circuit simulation with input square wave pv.v, capacitor voltage c.v, and resistor voltage r.v OpenModelica Connection Editor (OMEdit) displaying an example model from the Modelica Standard Library (MSL). The libraries browser (left), the diagram view (middle), and the documentation view (right) OpenModelica compiler workflow Dependencies as a bipartite graph Bipartite graph using adjacency matrix representation Bipartite graphs using biadjacency matrix representation A lower triangular matrix is also a BLT matrix BLT matrix representation. E0 and E3 (V0 and V1) is a strongly connected component that needs to be solved simultaneously as a linear or nonlinear system of equations Figure 2.9 after collapsing strongly connected components Using information from the translation in subsequent phases The number of symbolic operations performed on each equation in the EngineV6 model OpenModelica trace (redacted for brevity) Algorithmic code debugger flow of control vii viii LIST OF FIGURES 4.1 KCachegrind graph when examining eqfunction 564, showing clock cycles of the Virtual Machine (VM) spent calling each function as well as its call count. The residual function is called 2,387,425 times for 3,917 calls to the function solving the equation block. This means the nonlinear solver is calling the residual function on average 609 times in order to solve this strongly connected component in the BLT matrix Number of calls to the function per time step Runtime error message from model with chattering behavior Transformations browser opened for runtime error message from model with chattering behavior. When opened using the link from the simulation warning, the problematic equation is selected Setting up the simulation to use the equation profiler is as simple as selecting which class of equations should be profiled. Choosing all will profile all equations and functions. Choosing blocks will profile only strongly connected components and functions Profiling results of the Modelica standard library DoublePendulum example, sorted by execution time Inspecting the operations (transformations) performed on a single equation in the Modelica standard library DoublePendulum example. The diff before-after is color-coded (red is replaced text, green is new text) Debugger showing the most expensive equations to calculate when simulating CISESim The most expensive nonlinear system has been expanded and the figure cropped to focus only on this part Debugger showing the most expensive equations to calculate when simulating CISESim when applying CSE. The most expensive nonlinear system has been expanded and the figure cropped to focus only on this part. Applying the Common Subexpression Elimination (CSE) optimization has reduced the time taken for this nonlinear system compared to Figure LIST OF FIGURES ix 5.8 Clicking on the variable cse43 in CISESim displays which equations the variable is defined in (assigned to) as well as which equations use the variable. Equation 1542 (from Figure 5.7) uses this equation and it is through that equation variable cse43 was clicked. The variable is defined in equation 1498, and clicking it shows the equation and symbolic operations performed on this equation. Note that the execution count of the equation is much lower than it is for the equations in the nonlinear system shown in Figure Runtime domain error from EngineV6 model with a compiler generating bad code The debug view of the new efficient algorithmic code debugger in the MDT Eclipse plugin A preview of the upcoming OMEdit version of the algorithmic code debugger The stack frames view of the debugger The variables view of the new debugger Adding record information to the data structure to simplify the work of the debugger with small memory overhead (marked with a circle) Transmission line components calculate wave propagation through a line using a physically correct separation in time The example system consists of a volume and a pressure relief valve. Boundary conditions are represented by a constant flow source and a constant pressure source A pressure relief valve is designed to protect a hydraulic system by opening at a specified maximum pressure Pressure increases until the reference pressure of 10 MPa is reached, at which the relief valve opens Comparison of spool position using different TLM implementations. The curves for delay, der, and sample overlap almost completely. The Hopsan model is slightly different from the Modelica model, which causes the curves to also be slightly different x LIST OF FIGURES 7.6 Comparison of system pressure using different TLM implementations. The curves for delay, der, and sample overlap almost completely. The Hopsan model is slightly different from the Modelica model, which causes the curves to also be slightly different Comparison of spool position in OpenModelica and Dymola. The curves overlap almost completely. The markers are in different positions because OpenModelica does not round or interpolate the output points in the results file Adjacency matrices in lower triangular form Speedup graph for parallelization using static scheduling Comparison of spool position using a volume split into more segments Comparison of system pressure using a volume split into more segments. There is a numerical error that is amplified by splitting the volume into several segments. 164 List of Tables 3.1 Mean overhead cost of adding debug information Overhead cost of comparing expressions Variables introduced by common subexpressions used in the analyzed nonlinear system of CISESim shown in Figure 5.7. Each of these variables introduced an additional equation somewhere in the model that can be found by searching for the variable and listing the equations that assign to the variable. The variable cse20 is defined in an equation that is part of the nonlinear system; because the equation is part of the nonlinear system it will be executed multiple times in each evaluation of the system. The other uses of CSE variables come from outside the nonlinear system, which means they should be executed fewer times than without CSE (since the function call would still be part of the system) Sizes of OMC compiler phases, lines of code Sizes of OMC parser and runtime Total compile-times of files with different file sizes Compiler performance, parsing of MSL Compiler performance, checkmodel() on the large HumMod and analytic EngineV6 models, time spent and memory consumption Compiler performance, OpenModelica test suite, run in parallel. The fast version of the test suite is comprised of 1,622 simple tests, with the full version having 2,499 tests xi xii LIST OF TABLES 6.7 Running the new build script for compiling OpenModelica Compiling the OpenModelica source code with the old build system (MMC) and the new one (OMC) Compiler performance, checkmodel() on the large HumMod and analytic EngineV6 models, parsing of Modelica Standard Library (MSL) as multiple files, time spent and memory consumption. Comparing with the latest OMC version Performance comparison of methods for performing transmission line modeling in Modelica Performance of parallelization on a four-core machine. 162 Listings 2.1 Simple RC circuit A simple electrical pin in Modelica is a connector A simple electrical component with two pins MetaModelica example showing subpattern matching Expression interpreter: Exp1.mo List mapping in current MetaModelica is built into the language List mapping in MetaModelica 1.0 requires writing auxiliary functions Matching Sorting Example of minimum and maximum attributes in Modelica Data type for symbolic operations Alias model with poor scaling Toy example Runtime Error Corresponding equation information to runtime error Corresponding variable information Equation information for equation solving for x Modelica nonlinear system JSON Schema; before-after operations Modelica Code: HelloWorld.mo Generated C source code, HelloWorld.c, before postprocessing line directives Generated C source code, HelloWorld.c, after postprocessing line directives to standard C Profiling metadata for DoublePendulum Simple nonlinear equation Binding equation is an array xiii xiv LISTINGS 5.1 Model with chat
Recommended
View more...
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks