diff --git a/usersguide-sphinx/source/fmi.rst b/usersguide-sphinx/source/fmi.rst new file mode 100644 index 00000000000..94459668247 --- /dev/null +++ b/usersguide-sphinx/source/fmi.rst @@ -0,0 +1,497 @@ +Functional Mock-up Interface - FMI +================================== + +The new standard for model exchange and co-simulation with Functional +Mockup Interface (FMI) allows export of pre-compiled models, i.e., +C-code or binary code, from a tool for import in another tool, and vice +versa. The FMI standard is Modelica independent. Import and export works +both between different Modelica tools, or between certain non-Modelica +tools. OpenModelica supports FMI 1.0 & 2.0, + +- Model Exchange + +- Co-Simulation (under development) + + 1. .. rubric:: FMI Import + :name: fmi-import + +To import the FMU package use the OpenModelica command importFMU, + +function importFMU + +input String filename "the fmu file name"; + +input String workdir = "" "The output directory for imported +FMU files. will put the files to current working directory."; + +input Integer loglevel = 3 +"loglevel\_nothing=0;loglevel\_fatal=1;loglevel\_error=2;loglevel\_warning=3;loglevel\_info=4;loglevel\_verbose=5;loglevel\_debug=6"; + +input Boolean fullPath = false "When true the full output path is +returned otherwise only the file name."; + +input Boolean debugLogging = false "When true the FMU's debug output is +printed."; + +input Boolean generateInputConnectors = true "When true creates the +input connector pins."; + +input Boolean generateOutputConnectors = true "When true creates the +output connector pins."; + +output String generatedFileName "Returns the full path of the generated +file."; + +end importFMU; + +The command could be used from command line interface, OMShell, +OMNotebook or MDT. The importFMU command is also integrated with OMEdit. +Select FMI > Import FMU the FMU package is extracted in the directory +specified by workdir, since the workdir parameter is optional so if its +not specified then the current directory of omc is used. You can use the +cd() command to see the current location. + +The implementation supports FMI for Model Exchange 1.0 & 2.0 and FMI for +Co-Simulation 1.0 stand-alone. The support for FMI Co-Simulation is +still under development. + +The FMI Import is currently a prototype. The prototype has been tested +in OpenModelica with several examples. It has also been tested with +example FMUs from FMUSDK and Dymola. A more fullfleged version for FMI +Import will be released in the near future. + +**Figure** \ **5**\ 40: Example of FMU Import in OpenModelica where a +bouncing ball model is imported. + +FMI Export +---------- + +To export the FMU use the OpenModelica command +translateModelFMU(ModelName) from command line interface, OMShell, +OMNotebook or MDT. The export FMU command is also integrated with +OMEdit. Select FMI > Export FMU the FMU package is generated in the +current directory of omc. You can use the cd() command to see the +current location. You can set which version of FMI to export through +OMEdit settings, see section 2.9.13. + +After the command execution is complete you will see that a file +ModelName.fmu has been created. As depicted in Figure 6-2, we first +changed the current directory to C:/OpenModelica1.7.0/bin , then we +loaded a Modelica file with BouncingBall example model and finally +created an FMU for it using the translateModelFMU call. + +**Figure** \ **5**\ 41: OMShell screenshot for creating an FMU + +A log file for FMU creation is also generated named ModelName\_FMU.log. +If there are some errors while creating FMU they will be shown in the +command line window and logged in this log file as well. + +Modelica Performance Analyzer +============================= + +A common problem when simulating models in an equation-based language +like Modelica is that the model may contain non-linear equation systems. +These are solved in each time-step by extrapolating an initial guess and +running a non-linear system solver. If the simulation takes too long to +simulate, it is useful to run the performance analysis tool. The tool +has around 5~25% overhead, which is very low compared to +instruction-level profilers (30x-100x overhead). Due to being based on a +single simulation run, the report may contain spikes in the charts. + +When running a simulation for performance analysis, execution times of +user-defined functions as well as linear, non-linear and mixed equation +systems are recorded. + +To start a simulation in this mode, just use the measureTime flag of the +simulate command. + +simulate(modelname, measureTime = true) + +The generated report is in HTML format (with images in the SVG format), +stored in a file modelname\_prof.html, but the XML database and measured +times that generated the report and graphs are also available if you +want to customize the report for comparison with other tools. + +Below we use the performance profiler on the simple model A: + +**model** A + +**function** f + +**input** Real r; + +**output** Real o := sin(r); + +**end** f; + +String s = "abc"; + +Real x = f(x) "This is x"; + +Real y(start=1); + +Real z1 = cos(z2); + +Real z2 = sin(z1); + +**equation** + +der(y) = time; + +**end** A; + +We simulate as usual, but set measureTime=true to activate the +profiling: + +simulate(A, measureTime = true) + +// // record SimulationResult + +// resultFile = "A\_res.mat", + +// messages = "Time measurements are stored in A\_prof.html +(human-readable) and A\_prof.xml (for XSL transforms or more details)" + +// end SimulationResult; + +1. .. rubric:: Example Report Generated for the A Model + :name: example-report-generated-for-the-a-model + + 1. .. rubric:: Information + :name: information + +All times are measured using a real-time wall clock. This means context +switching produces bad worst-case execution times (max times) for +blocks. If you want better results, use a CPU-time clock or run the +command using real-time priviliges (avoiding context switches). + +Note that for blocks where the individual execution time is close to the +accuracy of the real-time clock, the maximum measured time may deviate a +lot from the average. + +For more details, see the generated file +`*A\_prof.xml* `__, +shown in Section 8.1.7 below. + +Settings +-------- + +The settings for the simulation are summarized in the table below: + ++--------------------------+-----------------------------------------------------------------------------+ +| **Name** | **Value** | ++--------------------------+-----------------------------------------------------------------------------+ +| Integration method | euler | ++--------------------------+-----------------------------------------------------------------------------+ +| Output format | mat | ++--------------------------+-----------------------------------------------------------------------------+ +| Output name | `*A\_res.mat* `__ | ++--------------------------+-----------------------------------------------------------------------------+ +| Output size | 24.0 kB | ++--------------------------+-----------------------------------------------------------------------------+ +| Profiling data | `*A\_prof.data* `__ | ++--------------------------+-----------------------------------------------------------------------------+ +| Profiling size | 27.3 kB | ++--------------------------+-----------------------------------------------------------------------------+ + +Summary +------- + +Execution times for different activities: + ++-----------------------------+----------------+--------------------+ +| **Task** | **Time** | **Fraction** | ++-----------------------------+----------------+--------------------+ +| Pre-Initialization | 0.000401 | 19.17% | ++-----------------------------+----------------+--------------------+ +| Initialization | 0.000046 | 2.20% | ++-----------------------------+----------------+--------------------+ +| Event-handling | 0.000036 | 1.72% | ++-----------------------------+----------------+--------------------+ +| Creating output file | 0.000264 | 12.62% | ++-----------------------------+----------------+--------------------+ +| Linearization | 0.000000 | 0.00% | ++-----------------------------+----------------+--------------------+ +| Time steps | 0.001067 | 51.00% | ++-----------------------------+----------------+--------------------+ +| Overhead | 0.000273 | 13.05% | ++-----------------------------+----------------+--------------------+ +| Unknown | 0.000406 | 0.24% | ++-----------------------------+----------------+--------------------+ +| Total simulation time | 0.002092 | 100.00% | ++-----------------------------+----------------+--------------------+ + +Global Steps +------------ + ++-------------+-------------+------------------+----------------+------------------------+----------------+-----------------+ +| ** ** | **Steps** | **Total Time** | **Fraction** | **Average Time** | **Max Time** | **Deviation** | ++-------------+-------------+------------------+----------------+------------------------+----------------+-----------------+ +| |image39| | 499 | 0.001067 | 51.00% | 2.13827655310621e-06 | 0.000006611 | 2.09x | ++-------------+-------------+------------------+----------------+------------------------+----------------+-----------------+ + +Measured Function Calls +----------------------- + ++------------------------+------------+-------------+---------------+----------------+----------------+-----------------+ +| ** ** | **Name** | **Calls** | **Time** | **Fraction** | **Max Time** | **Deviation** | ++------------------------+------------+-------------+---------------+----------------+----------------+-----------------+ +| |image40|\ |image41| | *A.f* | 1506 | 0.000092990 | 4.45% | 0.000000448 | 6.26x | ++------------------------+------------+-------------+---------------+----------------+----------------+-----------------+ + +Measured Blocks +--------------- + ++------------------------+-------------------+-------------+---------------+----------------+----------------+-----------------+ +| ** ** | **Name** | **Calls** | **Time** | **Fraction** | **Max Time** | **Deviation** | ++------------------------+-------------------+-------------+---------------+----------------+----------------+-----------------+ +| |image42|\ |image43| | *residualFunc3* | 2018 | 0.000521137 | 24.91% | 0.000035456 | 136.30x | ++------------------------+-------------------+-------------+---------------+----------------+----------------+-----------------+ +| |image44|\ |image45| | *residualFunc1* | 1506 | 0.000393709 | 18.82% | 0.000002735 | 9.46x | ++------------------------+-------------------+-------------+---------------+----------------+----------------+-----------------+ + +Equations +~~~~~~~~~ + ++-------------------------+-----------------+ +| **Name** | **Variables** | ++-------------------------+-----------------+ +| SES\_ALGORITHM 0 |   | ++-------------------------+-----------------+ +| SES\_SIMPLE\_ASSIGN 1 | *der(y)* | ++-------------------------+-----------------+ +| residualFunc3 | *z2*, *z1* | ++-------------------------+-----------------+ +| residualFunc1 | *x* | ++-------------------------+-----------------+ + +Variables +~~~~~~~~~ + ++--------------+---------------+ +| **Name** | **Comment** | ++--------------+---------------+ +| \ *y* |   | ++--------------+---------------+ +| \ *der(y)* |   | ++--------------+---------------+ +| \ *x* | This is x | ++--------------+---------------+ +| \ *z1* |   | ++--------------+---------------+ +| \ *z2* |   | ++--------------+---------------+ +| \ *s* |   | ++--------------+---------------+ + +Genenerated XML for the Example +------------------------------- + + + +- + +- + +A + +A + +2011-03-07 12:55:53 + +euler + +mat + +A\_res.mat + +24617 + +0.000273 + +0.000401 + +0.000046 + +0.000036 + +0.000264 + +0.000000 + +0.002092 + +0.001067 + +499 + +0.000006611 + + + +- + +A\_prof.data + +28000 + +- + +step + +time + +cpu time + +A.f (calls) + +residualFunc3 (calls) + +residualFunc1 (calls) + +A.f (cpu time) + +residualFunc3 (cpu time) + +residualFunc1 (cpu time) + + + + + +- + +- + + + + + +- + + + + + +- + + + + + +- + + + + + +- + + + + + +- + + + + + + + +- + +- + +A.f + +1506 + + + +0.000000448 + + + + + + + +- + +- + + + + + +- + +- + + + + + + + +- + +- + + + + + + + + + +- + +- + + + + + + + + + +- + +- + + + +2018 + + + +0.000035456 + + + +- + + + +1506 + + + +0.000002735 + + + + + + diff --git a/usersguide-sphinx/source/index.rst b/usersguide-sphinx/source/index.rst index c0c1155e765..5071ca4944e 100644 --- a/usersguide-sphinx/source/index.rst +++ b/usersguide-sphinx/source/index.rst @@ -13,6 +13,11 @@ Contents: introduction chapter2 + omedit + plotting + omnotebook + fmi + optimization test conclusion diff --git a/usersguide-sphinx/source/omedit.rst b/usersguide-sphinx/source/omedit.rst new file mode 100644 index 00000000000..9fb5fe53f47 --- /dev/null +++ b/usersguide-sphinx/source/omedit.rst @@ -0,0 +1,1001 @@ +OMEdit – OpenModelica Connection Editor +======================================= + +OMEdit – OpenModelica Connection Editor is the new Graphical User +Interface for graphical model editing in OpenModelica. It is implemented +in C++ using the Qt 4.8 graphical user interface library and supports +the Modelica Standard Library version 3.1 that is included in the latest +OpenModelica installation. This chapter gives a brief introduction to +OMEdit and also demonstrates how to create a DCMotor model using the +editor. + +OMEdit provides several user friendly features for creating, browsing, +editing, and simulating models: + +- *Modeling* – Easy model creation for Modelica models. + +- *Pre-defined models* – Browsing the Modelica Standard library to + access the provided models. + +- *User defined models* – Users can create their own models for + immediate usage and later reuse. + +- *Component interfaces* – Smart connection editing for drawing and + editing connections between model interfaces. + +- *Simulation* – Subsystem for running simulations and specifying + simulation parameters start and stop time, etc. + +- *Plotting* – Interface to plot variables from simulated models. + + 1. .. rubric:: Starting OMEdit + :name: starting-omedit + + 1. .. rubric:: Microsoft Windows + :name: microsoft-windows + +OMEdit can be launched using the executable placed in +OpenModelicaInstallationDirectory/bin/OMEdit/OMEdit.exe. Alternately, +choose OpenModelica > OpenModelica Connection Editor from the start menu +in Windows. A splash screen similar to the one shown in Figure 2 -2 will +appear indicating that it is starting OMEdit. + +Linux +----- + +Start OMEdit by either selecting the corresponding menu application item +or typing “\ **OMEdit**\ ” at the shell or command prompt. + +Mac OS X +-------- + +?? fill in + +|image1| + +Figure 22: **OMEdit Splash Screen.** + +MainWindow & Browsers +--------------------- + +The MainWindow contains several dockable browsers, + +- Search Browser + +- Libraries Browser + +- Documentation Browser + +- Variables Browser + +- Messages Browser + +Figure 2 -3 shows the MainWindow and browsers. + +|image2| + +Figure 23: **OMEdit MainWindow and Browsers.** + +The default location of the browsers are shown in Figure 2 -3. All +browsers except for Message Browser can be docked into left or right +column. The Messages Browser can be docked into left,right or bottom +areas. If you want OMEdit to remember the new docked position of the +browsers then you must enable Preserve User's GUI Customizations option, +see section 2.9.1. + +Search Browser +~~~~~~~~~~~~~~ + +|image3| + +Figure 24: **Search Browser.** + +To view the Search Browser click Edit->Search Browser or press keyboard +shortcut Ctrl+Shift+F. The loaded Modelica classes can be searched by +typing any part of the class name. It is also possible to search the +Modelica class if one knows the text string that is used within it but +Within Modelica text checkbox should be checked for this feature to +work. + +Libraries Browser +~~~~~~~~~~~~~~~~~ + +To view the Libraries Browser click View->Windows->Libraries Browser. +Shows the list of loaded Modelica classes. Each item of the Libraries +Browser has right click menu for easy manipulation and usage of the +class. The classes are shown in a tree structure with name and icon. The +protected classes are not shown by default. If you want to see the +protected classes then you must enable the Show Protected Classes +option, see section 2.9.1. + +|image4| + +Figure 25: **Libraries Browser.** + +Documentation Browser +~~~~~~~~~~~~~~~~~~~~~ + +Displays the HTML documentation of Modelica classes. It contains the +navigation buttons for moving forward and backward. To see documentation +of any class, right click the Modelica class in Libraries Browser and +choose View Documentation. + +|image5| + +Figure 26: **Documentation Browser.** + +Variables Browser +~~~~~~~~~~~~~~~~~ + +The class variables are structured in the form of the tree and are +displayed in the Variables Browser. Each variable has a checkbox. +Ticking the checkbox will plot the variable values. There is a find box +on the top for filtering the variable in the tree. The filtering can be +done using Regular Expression, Wildcard and Fixed String. The complete +Variables Browser can be collapsed and expanded using the Collapse All +and Expand All buttons. + +The browser allows manipulation of changeable parameters for +re-simulation. See section 2.7. It also displays the unit and +description of the variable. + +|image6| + +Figure 27: **Variables Browser.** + +Messages Browser +~~~~~~~~~~~~~~~~ + +Shows the list of errors. Following kinds of error can occur, + +- Syntax + +- Grammar + +- Translation + +- Symbolic + +- Simulation + +- Scripting + +See section 2.9.6 for Messages Browser options. + +Perspectives +------------ + +The perspective tabs are loacted at the bottom right of the MainWindow, + +- Welcome Perspective + +- Modeling Perspective + +- Plotting Perspective + + 1. .. rubric:: Welcome Perspective + :name: welcome-perspective + +|image7| + +Figure 28: **OMEdit Welcome Perspective.** + +The Welcome Perspective shows the list of recent files and the list of +latest news from `*openmodelica.org* `__. +See Figure 2 -8. The orientation of recent files and latest news can be +horizontal or vertical. User is allowed to show/hide the latest news. +See section 2.9.1. + +Modeling Perspective +~~~~~~~~~~~~~~~~~~~~ + +The Modeling Perpective provides the interface where user can create and +design their models. See Figure 2 -9. + +|image8| + +Figure 29: **OMEdit Modeling Perspective.** + +The Modeling Perspective interface can be viewed in two different modes, +the tabbed view and subwindow view, see section 2.9.1. + +Plotting Perspective +~~~~~~~~~~~~~~~~~~~~ + +The Plotting Perspective shows the simulation results of the models. +Plotting Perspective will automatically become active when the +simulation of the model is finished successfully. It will also become +active when user opens any of the OpenModelica’s supported result file. +Similar to Modeling Perspective this perspective can also be viewed in +two different modes, the tabbed view and subwindow view, see section +2.9.1. + +|image9| + +Figure 210: **OMEdit Plotting Perspective.** + +1. .. rubric:: Modeling a Model + :name: modeling-a-model + + 1. .. rubric:: Creating a New Modelica class + :name: creating-a-new-modelica-class + +Creating a new Modelica class in OMEdit is rather straightforward. +Choose any of the following methods, + +- Select File > New Modelica Class from the menu. + +- Click on New Modelica Class toolbar button. + +- Click on the Create New Modelica Class button available at the left + bottom of Welcome Perspective. + +- Press Ctrl+N. + + 1. .. rubric:: Opening a Modelica File + :name: opening-a-modelica-file + +Choose any of the following methods to open a Modelica file, + +- Select File > Open Model/Library File(s) from the menu. + +- Click on Open Model/Library File(s) toolbar button. + +- Click on the Open Model/Library File(s) button available at the right + bottom of Welcome Perspective. + +- Press Ctrl+O. + + 1. .. rubric:: Opening a Modelica File with Encoding + :name: opening-a-modelica-file-with-encoding + +Select File > Open/Convert Modelica File(s) With Encoding from the menu. +It is also possible to convert files to UTF-8. + +Model Widget +~~~~~~~~~~~~ + +For each Modelica class one Model Widget is created. It has a statusbar +and a view area. The statusbar contains buttons for navigation between +the views and labels for information. The view area is used to display +the icon, diagram and text layers of Modelica class. See Figure 2 -11. + +|image10| + +Figure 211: **Model Widget showing the Diagram View.** + +Adding Component Models +~~~~~~~~~~~~~~~~~~~~~~~ + +Drag the models from the Libraries Browser and drop them on either +Diagram or Icon View of Model Widget. + +Making Connections +~~~~~~~~~~~~~~~~~~ + +In order to connect one component model to another the user first needs +to enable the connect mode from the toolbar. See Figure 2 -12. + +|image11| + +Figure 212: **Connect/Unconnect Mode toolbar button. ** + +Simulating a Model +------------------ + +The OMEdit Simulation Dialog can be launched by, + +- Selecting Simulation > Simulation Setup from the menu. (requires a + model to be active in ModelWidget) + +- Clicking on the Simulation Setup toolbar button. (requires a model to + be active in ModelWidget) + +- Right clicking the model from the Libraries Browser and choosing + Simulation Setup. + + 1. .. rubric:: General Tab + :name: general-tab + +- *Start Time* – the simulation start time. + +- *Stop Time* – the simulation stop time. + +- *Method* – the simulation solver. See Appendix C for solver details. + +- *Tolerance* – the simulation tolerance. + +- *Compiler Flags (Optional)* – the optional C compiler flags. + +- *Number of Processors* – the number of processors used to build the + simulation. + +- *Launch Transformational Debugger* – launches the transformational + debugger. + +- *Launch Algorithmic Debugger* – launches the algorithmic debugger. + + 1. .. rubric:: Output Tab + :name: output-tab + +- *Number of Intervals* – the simulation number of intervals. + +- *Output Format* – the simulation result file output format. + +- *File Name (Optional)* – the simulation result file name. + +- *Variable Filter (Optional).* + +- *Protecetd Variables –* adds the protected variables in result file. + +- *Store Variables at Events –* adds the variables at time events. + +- *Show Generated File* – displays the generated files in a dialog box. + + 1. .. rubric:: Simulation Flags Tab + :name: simulation-flags-tab + +- *Model Setup File (Optional)* – specifies a new setup XML file to the + generated simulation code. + +- *Initialization Method (Optional)* – specifies the initialization + method. + +- *Equation System Initialization File (Optional)* – specifies an + external file for the initialization of the model. + +- *Equation System Initialization Time (Optional)* – specifies a time + for the initialization of the model. + +- *Clock (Optional)* – the type of clock to use. + +- *Linear Solver (Optional)* – specifies the linear solver method. + +- *Non Linear Solver (Optional)* – specifies the nonlinear solver. + +- *Linearization Time (Optional)* – specifies a time where the + linearization of the model should be performed. + +- *Output Variables (Optional)* – outputs the variables a, b and c at + the end of the simulation to the standard output. + +- *Profiling* – creates a profiling HTML file. + +- *CPU Time* – dumps the cpu-time into the result file. + +- *Enable All Warnings* – outputs all warnings. + +- *Logging (Optional)* + +- *DASSL Solver Information* – prints additional information about + dassl solver. + +- *Debug* – prints additional debug information. + +- *Dynamic State Selection Information* – outputs information about + dynamic state selection. + +- *Jacobians Dynamic State Selection Information* – outputs jacobain of + the dynamic state selection. + +- *Event Iteration* – additional information during event iteration. + +- *Verbose Event System* – verbose logging of event system. + +- *Initialization* – prints additional information during + initialization. + +- *Jacobians Matrix* – outputs the jacobian matrix used by dassl. + +- *Non Linear Systems* – logging for nonlinear systems. + +- *Verbose Non Linear Systems* – verbose logging of nonlinear systems. + +- *Jacobians Non Linear Systems* – outputs the jacobian of nonlinear + systems. + +- *Initialization Residuals* – outputs residuals of the initialization. + +- *Simulation Process* – additional information about simulation + process. + +- *Solver Process* – additional information about solver process. + +- *Final Initialization Solution* – final solution of the + initialization. + +- *Timer/Event/Solver Statistics* – additional statistics about + timer/events/solver. + +- *Util*. + +- *Zero Crossings* – additional information about the zerocrossings. + +- *Additional Simulation Flags (Optional)* – specify any other + simulation flag. + + 1. .. rubric:: Plotting the Simulation Results + :name: plotting-the-simulation-results + +Successful simulation of model produces the result file which contains +the instance variables that are candidate for plotting. Variables +Browser will show the list of such instance variables. Each variable has +a checkbox, checking it will plot the variable. See Figure 2 -10. + +Types of Plotting +~~~~~~~~~~~~~~~~~ + +The plotting type depends on the active Plot Window. By default the +plotting type is Time Plot. + +Time Plot +^^^^^^^^^ + +Plots the variable over the simulation time. You can have multiple Time +Plot windows by clicking on New Plot Window toolbar button. See Figure 2 +-13. + +|image12| + +Figure 213: **New Plot Window toolbar button.** + +Plot Parametric +^^^^^^^^^^^^^^^ + +Draws a two-dimensional parametric diagram, between variables x and y, +with *y* as a function of *x*. You can have multiple Plot Parametric +windows by clicking on the New Plot Parametric toolbar button. See +Figure 2 -14. + +|image13| + +Figure 214: **New Plot Parametric toolbar button.** + +Re-simulating a Model +--------------------- + +The Variables Browser allows manipulation of changeable parameters for +re-simulation as shown in Figure 2 -7. After changing the parameter +values user can click on the Re-simulate toolbar button, , or right +click the model in Variables Browser and choose Re-simulate from the +menu. + +|image14| + +Figure 215: **Re-simulate toolbar button.** + +How to Create User Defined Shapes – Icons +----------------------------------------- + +Users can create shapes of their own by using the shape creation tools +available in OMEdit. + +- *Line Tool* – Draws a line. A line is created with a minimum of two + points. In order to create a line, the user first selects the + line tool from the toolbar and then click on the Icon/Diagram + View; this will start creating a line. If a user clicks again on + the Icon/Diagram View a new line point is created. In order to + finish the line creation, user has to double click on the + Icon/Diagram View. + +- *Polygon Tool* – Draws a polygon. A polygon is created in a similar + fashion as a line is created. The only difference between a line + and a polygon is that, if a polygon contains two points it will + look like a line and if a polygon contains more than two points + it will become a closed polygon shape. + +- *Rectangle Tool* – Draws a rectangle. The rectangle only contains two + points where first point indicates the starting point and the + second point indicates the ending the point. In order to create + rectangle, the user has to select the rectangle tool from the + toolbar and then click on the Icon/Diagram View, this click will + become the first point of rectangle. In order to finish the + rectangle creation, the user has to click again on the + Icon/Diagram View where he/she wants to finish the rectangle. The + second click will become the second point of rectangle. + +- *Ellipse Tool* – Draws an ellipse. The ellipse is created in a + similar way as a rectangle is created. + +- *Text Tool* – Draws a text label. + +- *Bitmap Tool* – Draws a bitmap container. + +The shape tools are located in the toolbar. See Figure 2 -16. + +Figure 216: **User defined shapes.** + +The user can select any of the shape tools and start drawing on the +Icon/Diagram View. The shapes created on the Diagram View of Model +Widget are part of the diagram and the shapes created on the Icon View +will become the icon representation of the model. + +For example, if a user creates a model with name testModel and add a +rectangle using the rectangle tool and a polygon using the polygon tool, +in the Icon View of the model. The model’s Modelica Text will appear as +follows: + +**model** testModel + +annotation(Icon(graphics = {Rectangle(rotation = 0, lineColor = +{0,0,255}, fillColor = {0,0,255}, pattern = LinePattern.Solid, +fillPattern = FillPattern.None, lineThickness = 0.25, extent = {{ +-64.5,88},{63, -22.5}}),Polygon(points = {{ -47.5, -29.5},{52.5, +-29.5},{4.5, -86},{ -47.5, -29.5}}, rotation = 0, lineColor = {0,0,255}, +fillColor = {0,0,255}, pattern = LinePattern.Solid, fillPattern = +FillPattern.None, lineThickness = 0.25)})); + +**end** testModel; + +In the above code snippet of testModel, the rectangle and a polygon are +added to the icon annotation of the model. Similarly, any user defined +shape drawn on a Diagram View of the model will be added to the diagram +annotation of the model. + +Settings +-------- + +OMEdit allows users to save several settings which will be remembered +across different sessions of OMEdit. The Options Dialog can be used for +reading and writing the settings. + +General +~~~~~~~ + +- General + +- *Language* – Sets the application language. + +- *Working Directory* – Sets the application working directory. + +- *Toolbar Icon Size* – Sets the size for toolbar icons. + +- *Preserve User’s GUI Customizations* – If true then OMEdit will + remember its windows and toolbars positions and sizes. + +- Libraries Browser + +- *Library Icon Size* – Sets the size for library icons. + +- *Show Protected Classes* – Sets the application language. + +- Modeling View Mode + +- *Tabbed View/SubWindow View* – Sets the view mode for modeling. + +- Plotting View Mode + +- *Tabbed View/SubWindow View* – Sets the view mode for plotting. + +- Default View + +- *Icon View/DiagramView/Modelica Text View/Documentation View* – If no + preferredView annotation is defined then this setting is used to show + the respective view when user double clicks on the class in the + Libraries Browser. + +- Enable Auto Save + +- *Auto Save interval* – Sets the auto save interval value. The minimum + possible interval value is 60 seconds. + +- *Enable Auto Save for single classes* – Enables the auto save for one + class saved in one file. + +- *Enable Auto Save for one file packages* – Enables the auto save for + packages saved in one file. + +- Welcome Page + +- *Horizontal View/Vertical View* – Sets the view mode for welcome + page. + +- *Show Latest News –* if true then displays the latest news. + + 1. .. rubric:: Libraries + :name: libraries + +- *System Libraries* – The list of system libraries that should be + loaded every time OMEdit starts. + +- *Force loading of Modelica Standard Library* – If true then Modelica + and ModelicaReference will always load even if user has removed + them from the list of system libraries. + +- *User Libraries* – The list of user libraries/files that should be + loaded every time OMEdit starts. + + 1. .. rubric:: Modelica Text Editor + :name: modelica-text-editor + +- General + +- *Enable Syntax Highlighting* – Enable/Disable the syntax highlighting + for the Modelica Text Widget. + +- *Enable Line Wrapping* – Enable/Disable the line wrapping for the + Modelica Text Widget. + +- Fonts and Colors + +- *Font Family* – Contains the names list of available fonts. + +- *Font Size* – Sets the font size. + +- *Items* – List of categories used of syntax highlighting the code. + +- *Item Color* – Sets the color for the selected item. + +- *Preview* – Shows the demo of the syntax highlighting. + + 1. .. rubric:: Graphical Views + :name: graphical-views + +- Extent + +- *Left* – Defines the left extent point for the view. + +- *Bottom* – Defines the bottom extent point for the view. + +- *Right* – Defines the right extent point for the view. + +- *Top* – Defines the top extent point for the view. + +- Grid + +- *Horizontal* – Defines the horizontal size of the view grid. + +- *Vertical* – Defines the vertical size of the view grid. + +- Component + +- *Scale factor* – Defines the initial scale factor for the component + dragged on the view. + +- *Preserve aspect ratio* – If true then the component’s aspect ratio + is preserved while scaling. + + 1. .. rubric:: Simulation + :name: simulation + +- Simulation + +- *Matching Algorithm* – sets the matching algorithm for simulation. + +- *Index Reduction Method* – sets the index reduction method for + simulation. + +- *OMC Flags* – sets the omc flags for simulation. + +- *Save class before simulation* – if ture then always saves the class + before running the simulation. + +- Output + +- *Structured –* Shows the simulation output in the form of tree + structure. + +- *Formatted Text –* Shows the simulation output in the form of + formatted text. + + 1. .. rubric:: Messages + :name: messages + +- General + +- *Output Size* - Specifies the maximum number of rows the Messages + Browser may have. If there are more rows then the rows are removed + from the beginning. + +- *Reset messages number before simulation* – Resets the messages + counter before starting the simulation. + +- Font and Colors + +- *Font Family* – Sets the font for the messages. + +- *Font Size –* Sets the font size for the messages. + +- *Notification Color* – Sets the text color for notification messages. + +- *Warning Color* – Sets the text color for warning messages. + +- *Error Color* – Sets the text color for error messages. + + 1. .. rubric:: Notifications + :name: notifications + +- Notifications + +- *Always quit without prompt* – If true then OMEdit will quit without + prompting the user. + +- *Show item dropped on itself message* – If true then a message will + pop-up when a class is dragged and dropped on itself. + +- *Show model is defined as partial and component will be added as + replaceable message* – If true then a message will pop-up when a + partial class is added to another class. + +- *Show component is declared as inner message* – If true then a + message will pop-up when an inner component is added to another + class. + +- *Show save model for bitmap insertion message* – If true then a + message will pop-up when user tries to insert a bitmap from a local + directory to an unsaved class. + + 1. .. rubric:: Line Style + :name: line-style + +- Line Style + +- *Color* – Sets the line color. + +- *Pattern* – Sets the line pattern. + +- *Thickness* – Sets the line thickness. + +- *Start Arrow* – Sets the line start arrow. + +- *End Arrow* – Sets the line end arrow. + +- *Arrow Size* – Sets the start and end arrow size. + +- *Smooth* – If true then the line is drawn as a Bezier curve. + + 1. .. rubric:: Fill Style + :name: fill-style + +- Fill Style + +- *Color* – Sets the fill color. + +- *Pattern* – Sets the fill pattern. + + 1. .. rubric:: Curve Style + :name: curve-style + +- Curve Style + +- *Pattern* – Sets the curve pattern. + +- *Thickness* – Sets the curve thickness. + + 1. .. rubric:: Figaro + :name: figaro + +- Figaro + +- *Figaro Database File* – the Figaro database file path. + +- *Figaro Mode* – + +- *Figaro Options File* – the Figaro options file path. + +- *Figaro Process* – the Figaro process location. + + 1. .. rubric:: Debugger + :name: debugger + +- Algorithmic Debugger + +- *GDB Path* – the gnu debugger path + +- *GDB Command Timeout* – timeout for gdb commands. + +- *Display C frames* – if true then shows the C stack frames. + +- *Display unknown frames* – if true then shows the unknown stack + frames. Unknown stack frames means frames whose file path is unknown. + +- *Clear old output on a new run* – if true then clears the output + window on new run. + +- *Clear old log on new run* – if true then clears the log window on + new run. + +- Transformational Debugger + +- *Always show Transformational Debugger after compilation* – if true + then always open the Transformational Debugger window after model + compilation. + +- *Generate operations in the info xml* – if true then adds the + operations information in the info xml file. + + 1. .. rubric:: FMI + :name: fmi + +- Export + +- *Version 1.0* – Sets the FMI export version to 1.0 + +- *Version 2.0* – Sets the FMI export version to 2.0 + + 1. .. rubric:: The Equation-based Debugger + :name: the-equation-based-debugger + +This section gives a short description how to get started using the +equation-based debugger in OMEdit. + +Enable Tracing Symbolic Transformations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This enables tracing symbolic transformations of equations. It is +optional but strongly recommended in order to fully use the debugger. +The compilation time overhead from having this tracing on is less than +1%, however, in addition to that, some time is needed for the system to +write the xml file containing the transformation tracing information. + +Enable +d=infoXmlOperations in Tools->Options->Simulation (see section +2.9.5) OR alternatively click on the checkbox *Generate operations in +the info xml* in Tools->Options->Debugger (see section 2.9.12) which +performs the same thing. + +This adds all the transformations performed by OpenModelica on the +equations and variables stored in the model\_info.xml file. This is +necessary for the debugger to be able to show the whole path from the +source equation(s) to the position of the bug. + +Load a Model to Debug +~~~~~~~~~~~~~~~~~~~~~ + +Load an interesting model. We will use the package +`*https://openmodelica.org/svn/OpenModelica/trunk/testsuite/openmodelica/debugging/Debugging.mo* `__ +since it contains suitable, broken models to demonstrate common errors. + +Simulate and Start the Debugger +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Select and simulate the model as usual. For example, if using the +Debugging package, select the model +Debugging.Chattering.ChatteringEvents1. If there is an error, you will +get a clickable link that starts the debugger. If the user interface is +unresponsive or the running simulation uses too much processing power, +click cancel simulation first. + +Figure 217. **Simulating the model.** + +Use the Transformation Debugger for Browsing +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the transformation debugger. It opens on the equation where the +error was found. You can browse through the dependencies (variables that +are defined by the equation, or the equation is dependent on), and +similar for variables. The equations and variables form a bipartite +graph that you can walk. + +If the +d=infoXmlOperations was used or you clicked the “generate +operations” button, the operations performed on the equations and +variables can be viewed. In the example package, there are not a lot of +operations because the models are small. + +Try some larger models, e.g. in the MultiBody library or some other +library, to see more operations with several transformation steps +between different versions of the relevant equation(s). If you do not +trigger any errors in a model, you can still open the debugger, using +File->Open Transformations File (model\_info.xml). + +Figure 218. **Transfomation Debugger.** + +The Algorithmic Debugger +------------------------ + +This section gives a short description how to get started using the +algorithmic debugger in OMEdit. See section 2.9.12 for further details +of debugger options/settings. The Algorithmic Debugger window can be +launched from Tools->Windows->Algorithmic Debugger. + +Adding Breakpoints +~~~~~~~~~~~~~~~~~~ + +There are two ways to add the breakpoints, + +- Click directly on the line number in Text View, a red circle is + created indicating a breakpoint as shown in Figure 2 -19. + +- Open the Algorithmic Debugger window and add a breakpoint using the + right click menu of Breakpoints Browser window. + +|image15| + +Figure 219: **Adding breakpoint in Text View.** + +Start the Algorithmic Debugger +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You should add breakpoints before starting the debugger because +sometimes the simulation finishes quickly and you won’t get any chance +to add the breakpoints. + +There are four ways to start the debugger, + +- Open the Simulation Setup and click on Launch Algorithmic Debugger + before pressing Simulate. + +- Right click the model in Libraries Browser and select Simulate with + Algorithmic Debugger. + +- Open the Algorithmic Debugger window and from menu select + Debug->Debug Configurations (see section 2.11.3). + +- Open the Algorithmic Debugger window and from menu select + Debug->Attach to Running Process (see section 2.11.4). + + 1. .. rubric:: Debug Configurations + :name: debug-configurations + +If you already have a simulation executable with debugging symbols +outside of OMEdit then you can use the Debug->Debug Configurations +option to load it. + +The debugger also supports MetaModelica data structures so one can debug +omc executable. Select omc executable as program and write the name of +the mos script file in Arguments. + +|image16| + +Figure 220: **Debug Configurations.** + +Attach to Running Process +~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you already have a running simulation executable with debugging +symbols outside of OMEdit then you can use the Debug->Attach to Running +Process option to attach the debugger with it. Figure 2 -21 shows the +Attach to Running Process dialog. The dialog shows the list of processes +running on the machine. The user selects the program that he/she wish to +debug. OMEdit debugger attaches to the process. + +|image17| + +Figure 221: **Attach to Running Process.** + +Using the Algorithmic Debugger Window +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Figure 2 -22 shows the Algorithmic Debugger window. The window contains +the following browsers, + +- *Stack Frames Browser* – shows the list of frames. It contains the + program context buttons like resume, interrupt, exit, step over, + step in, step return. It also contains a threads drop down which + allows switching between different threads. + +- *BreakPoints Browser* – shows the list of breakpoints. Allows + adding/editing/removing breakpoints. + +- *Locals Browser* – Shows the list of local variables with values. + Select the variable and the value will be shown in the bottom + right window. This is just for convenience because some variables + might have long values. + +- *Debugger CLI* – shows the commands sent to gdb and their responses. + This is for advanced users who want to have more control of the + debugger. It allows sending commands to gdb. + +- *Output Browser* – shows the output of the debugged executable. + +|image18| + +Figure 222: **Algorithmic Debugger.** + +.. |image1| image:: media/image8.png +.. |image2| image:: media/image9.png +.. |image3| image:: media/image10.png +.. |image4| image:: media/image11.png +.. |image5| image:: media/image12.png +.. |image6| image:: media/image13.png +.. |image7| image:: media/image14.png +.. |image8| image:: media/image15.png +.. |image9| image:: media/image16.png +.. |image10| image:: media/image17.png +.. |image11| image:: media/image18.png +.. |image12| image:: media/image19.png +.. |image13| image:: media/image20.png +.. |image14| image:: media/image21.png +.. |image15| image:: media/image25.png +.. |image16| image:: media/image26.png +.. |image17| image:: media/image27.png +.. |image18| image:: media/image28.png diff --git a/usersguide-sphinx/source/omnotebook.rst b/usersguide-sphinx/source/omnotebook.rst new file mode 100644 index 00000000000..c942fd76472 --- /dev/null +++ b/usersguide-sphinx/source/omnotebook.rst @@ -0,0 +1,810 @@ +OMNotebook with DrModelica and DrControl +======================================== + +This chapter covers the OpenModelica electronic notebook subsystem, +called OMNotebook, together with the DrModelica tutoring system for +teaching Modelica, and DrControl for teaching control together with +Modelica. Both are using such notebooks. + +Interactive Notebooks with Literate Programming +----------------------------------------------- + +Interactive Electronic Notebooks are active documents that may contain +technical computations and text, as well as graphics. Hence, these +documents are suitable to be used for teaching and experimentation, +simulation scripting, model documentation and storage, etc. + +Mathematica Notebooks +~~~~~~~~~~~~~~~~~~~~~ + +(?? Reference section )Literate Programming (Knuth 1984) is a form of +programming where programs are integrated with documentation in the same +document. Mathematica notebooks (Wolfram 1997) is one of the first +WYSIWYG (What-You-See-Is-What-You-Get) systems that support Literate +Programming. Such notebooks are used, e.g., in the MathModelica modeling +and simulation environment, e.g. see Figure 4 -25below and Chapter 19 in +:cite:`openmodelica.org:fritzson:2004`. + +OMNotebook +~~~~~~~~~~ + +(?? Reference section ) The OMNotebook software (Axelsson 2005, +Fernström 2006) is a new open source free software that gives an +interactive WYSIWYG (What-You-See-Is-What-You-Get) realization of +Literate Programming, a form of programming where programs are +integrated with documentation in the same document. + +(?? Reference section ) The OMNotebook facility is actually an +interactive WYSIWYG (What-You-See-Is-What-You-Get) realization of +Literate Programming, a form of programming where programs are +integrated with documentation in the same document. OMNotebook is a +simple open-source software tool for an electronic notebook supporting +Modelica. + +A more advanced electronic notebook tool, also supporting mathematical +typesetting and many other facilities, is provided by Mathematica +notebooks in the MathModelica environment, see Figure 4 -25. + +Figure 425. **Examples of Mathematica notebooks in the MathModelica +modeling and simulation environment.** + +Traditional documents, e.g. books and reports, essentially always have a +hierarchical structure. They are divided into sections, subsections, +paragraphs, etc. Both the document itself and its sections usually have +headings as labels for easier navigation. This kind of structure is also +reflected in electronic notebooks. Every notebook corresponds to one +document (one file) and contains a tree structure of cells. A cell can +have different kinds of contents, and can even contain other cells. The +notebook hierarchy of cells thus reflects the hierarchy of sections and +subsections in a traditional document such as a book. + +DrModelica Tutoring System – an Application of OMNotebook +--------------------------------------------------------- + +Understanding programs is hard, especially code written by someone else. +For educational purposes it is essential to be able to show the source +code and to give an explanation of it at the same time. + +Moreover, it is important to show the result of the source code’s +execution. In modeling and simulation it is also important to have the +source code, the documentation about the source code, the execution +results of the simulation model, and the documentation of the simulation +results in the same document. The reason is that the problem solving +process in computational simulation is an iterative process that often +requires a modification of the original mathematical model and its +software implementation after the interpretation and validation of the +computed results corresponding to an initial model. + +Most of the environments associated with equation-based modeling +languages focus more on providing efficient numerical algorithms rather +than giving attention to the aspects that should facilitate the learning +and teaching of the language. There is a need for an environment +facilitating the learning and understanding of Modelica. These are the +reasons for developing the DrModelica teaching material for Modelica and +for teaching modeling and simulation. + +An earlier version of DrModelica was developed using the MathModelica +(now Wolfram SystemModeler) environment. The rest of this chapter is +concerned with the OMNotebook version of DrModelica and on the +OMNotebook tool itself. + +DrModelica has a hierarchical structure represented as notebooks. The +front-page notebook is similar to a table of contents that holds all +other notebooks together by providing links to them. This particular +notebook is the first page the user will see (Figure 4 -26). + +Figure 426. **The front-page notebook of the OMNotebook version of the +DrModelica tutoring system.** + +In each chapter of DrModelica the user is presented a short summary of +the corresponding chapter of the book “Principles of Object-Oriented +Modeling and Simulation with Modelica 2.1” by Peter Fritzson. The +summary introduces some *keywords*, being hyperlinks that will lead the +user to other notebooks describing the keywords in detail. + +\ |image19| + +Figure 427. **The** HelloWorld **class simulated and plotted using the +OMNotebook version of DrModelica.** + +Now, let us consider that the link “\ *HelloWorld*\ ” in DrModelica +Section is clicked by the user. The new HelloWorld notebook (see Figure +4 -27), to which the user is being linked, is not only a textual +description but also contains one or more examples explaining the +specific keyword. In this class, HelloWorld, a differential equation is +specified. + +No information in a notebook is fixed, which implies that the user can +add, change, or remove anything in a notebook. Alternatively, the user +can create an entirely new notebook in order to write his/her own +programs or copy examples from other notebooks. This new notebook can be +linked from existing notebooks. + +Figure 428. **DrModelica Chapter on Algorithms and Functions in the main +page of the OMNotebook version of DrModelica.** + +When a class has been successfully evaluated the user can simulate and +plot the result, as previously depicted in Figure 4 -27 for the simple +HelloWorld example model. + +After reading a chapter in DrModelica the user can immediately practice +the newly acquired information by doing the exercises that concern the +specific chapter. Exercises have been written in order to elucidate +language constructs step by step based on the pedagogical assumption +that a student learns better “\ *using the strategy of learning by +doing*\ ”. The exercises consist of either theoretical questions or +practical programming assignments. All exercises provide answers in +order to give the user immediate feedback. + +Figure 4 -28 shows part of Chapter 9 of the DrModelica teaching +material. Here the user can read about language constructs, like +algorithm sections, when-statements, and reinit equations, and then +practice these constructs by solving the exercises corresponding to the +recently studied section. + +|image20| + +Figure 429. **Exercise 1 in Chapter 9 of DrModelica** + +Exercise 1 from Chapter 9 is shown in Figure 4 -29. In this exercise the +user has the opportunity to practice different language constructs and +then compare the solution to the answer for the exercise. Notice that +the answer is not visible until the *Answer* section is expanded. The +answer is shown in Figure 4 -30. + +Figure 430. \ **The answer section to Exercise 1 in Chapter 9 of +DrModelica.** + +DrControl Tutorial for Teaching Control Theory +---------------------------------------------- + +DrControl is an interactive OMNotebook document aimed at teaching +control theory. It is included in the OpenModelica distribution and +appears under the directory OpenModelica1.9.2/share/ +omnotebook/drcontrol. + +The front-page of DrControl resembles a linked table of content that can +be used as a navigation center. The content list contains topics like: + +- Getting started + +- The control problem in ordinary life + +- Feedback loop + +- Mathematical modeling + +- Transfer function + +- Stability + +- Example of controlling a DC-motor + +- Feedforward compensation + +- State-space form + +- State observation + +- Closed loop control system. + +- Reconstructed system + +- Linear quadratic optimization + +- Linearization + +Each entry in this list leads to a new notebook page where either the +theory is explained with Modelica examples or an exercise with a +solution is provided to illustrate the background theory. Below we show +a few sections of DrControl. + +Feedback Loop +~~~~~~~~~~~~~ + +One of the basic concepts of control theory is using feedback loops +either for neutralizing the disturbances from the surroundings or a +desire for a smoother output. + +In Figure 4 -31, control of a simple car model is illustrated where the +car velocity on a road is controlled, first with an open loop control, +and then compared to a closed loop system with a feedback loop. The car +has a mass m, velocity y, and aerodynamic coefficient α. The θ is the +road slope, which in this case can be regarded as noise. + +Figure 431. **Feedback loop** + +Lets look at the Modelica model for the open loop controlled car: + +.. math:: + m \dot y = u - \alpha y - m g * sin(\theta) + +.. code-block:: modelica + + model noFeedback + import SI = Modelica.SIunits; + SI.Velocity y; // output signal without noise, theta = 0 -> v(t) = 0 + SI.Velocity yNoise; // output signal with noise, theta <> 0 -> v(t) <> 0 + parameter SI.Mass m = 1500; + parameter Real alpha = 200; + parameter SI.Angle theta = 5*3.141592/180; + parameter SI.Acceleration g = 9.82; + SI.Force u; + SI.Velocity r=20; + equation + m*der(y)=u-alpha*y; // signal without noise + m*der(yNoise)=u-alpha*yNoise-m*g*sin(theta); // with noise + u = 250*r; + end noFeedback; + +By applying a road slope angle different from zero the car velocity is +influenced which can be regarded as noise in this model. The output +signal in Figure 4 -32 is stable but an overshoot can be observed +compared to the reference signal. Naturally the overshoot is not desired +and the student will in the next exercise learn how to get rid of this +undesired behavior of the system. + +Figure 432. **Open loop control example.** + +The closed car model with a proportional regulator is shown below: + +.. math:: + u = K*(r-y) + +.. code-block:: modelica + + model withFeedback + import SI = Modelica.SIunits; + SI.Velocity y; // output signal with feedback link and without noise, theta = 0 -> v(t) = 0 + SI.Velocity yNoise; // output signal with feedback link and noise, theta <> 0 -> v(t) <> 0 + parameter SI.Mass m = 1500; + parameter Real alpha = 250; + parameter SI.Angle theta = 5*3.141592/180; + parameter SI.Acceleration g = 9.82; + SI.Force u; + SI.Force uNoise; + SI.Velocity r=20; + equation + m*der(y)=u-alpha*y; + m*der(yNoise)=uNoise-alpha*yNoise-m*g*sin(theta); + u = 5000*(r-y); + uNoise = 5000*(r-yNoise); + end withFeedback; + +By using the information about the current level of the output signal +and re-tune the regulator the output quantity can be controlled towards +the reference signal smoothly and without an overshoot, as shown in +Figure 4 -33. + +In the above simple example the flat modeling approach was adopted since +it was the fastest one to quickly obtain a working model. However, one +could use the object oriented approach and encapsulate the car and +regulator models in separate classes with the Modelica connector +mechanism in between. + +Figure 433. **Closed loop control example.** + +Mathematical Modeling with Characteristic Equations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In most systems the relation between the inputs and outputs can be +described by a linear differential equation. Tearing apart the solution +of the differential equation into homogenous and particular parts is an +important technique taught to the students in engineering courses, also +illustrated in Figure 4 -34. + +|image23| + +Now let us examine a second order system: + +|image24| + +**model** NegRoots + +Real y; + +Real der\_y; + +**parameter** Real a1 = 3; + +**parameter** Real a2 = 2; + +**equation** + +der\_y = **der**\ (y); + +**der**\ (der\_y) + a1\*der\_y + a2\*y = 1; + +**end** NegRoots; + +Choosing different values for a\ :sub:`1` and a\ :sub:`2` leads to +different behavior as shown in Figure 4 -35 and Figure 4 -36. + +|image25| + +Figure 434. **Mathematical modeling with characteristic equation.** + +In the first example the values of a\ :sub:`1` and a\ :sub:`2` are +chosen in such way that the characteristic equation has negative real +roots and thereby a stable output response, see Figure 4 -35. + +Figure 435. **Characteristic eq. with real negative roots.** + +The importance of the sign of the roots in the characteristic equation +is illustrated in Figure 4 -35 and Figure 4 -36, e.g., a stable system +with negative real roots and an unstable system with positive imaginary +roots resulting in oscillations. + +**model** NegRoots + +Real y; + +Real der\_y; + +**parameter** Real a1 = -2; + +**parameter** Real a2 = 10; + +**equation** + +der\_y = **der**\ (y); + +**der**\ (der\_y) + a1\*der\_y + a2\*y = 1; + +**end** NegRoots; + +Figure 436. **Characteristic eq. with positive imaginary roots.** + +Figure 437. **Step and pulse (weight function) response.** + +The theory and application of Kalman filters is also explained in the +interactive course material. + +Figure 438. **Theory background about Kalman filter.** + +In reality noise is present in almost every physical system under study +and therefore the concept of noise is also introduced in the course +material, which is purely Modelica based. + +Figure 439. Comparison of a noisy system with feedback link i\ **n +DrControl.** + +OpenModelica Notebook Commands +------------------------------ + +OMNotebook currently supports the commands and concepts that are +described in this section. + +Cells +~~~~~ + +Everything inside an OMNotebook document is made out of cells. A cell +basically contains a chunk of data. That data can be text, images, or +other cells. OMNotebook has four types of cells: headercell, textcell, +inputcell, and groupcell. Cells are ordered in a tree structure, where +one cell can be a parent to one or more additional cells. A tree view is +available close to the right border in the notebook window to display +the relation between the cells. + +- *Textcell* – This cell type is used to display ordinary text and + images. Each textcell has a style that specifies how text is + displayed. The cell´s style can be changed in the menu + Format->Styles, example of different styles are: Text, Title, and + Subtitle. The Textcell type also has support for following links + to other notebook documents. + +- *Inputcell* – This cell type has support for syntax highlighting and + evaluation. It is intended to be used for writing program code, + e.g. Modelica code. Evaluation is done by pressing the key + combination Shift+Return or Shift+Enter. All the text in the cell + is sent to OMC (OpenModelica Compiler/interpreter), where the + text is evaluated and the result is displayed below the + inputcell. By double-clicking on the cell marker in the tree + view, the inputcell can be collapsed causing the result to be + hidden. + +- *Groupcell* – This cell type is used to group together other cell. A + groupcell can be opened or closed. When a groupcell is opened all + the cells inside the groupcell are visible, but when the + groupcell is closed only the first cell inside the groupcell is + visible. The state of the groupcell is changed by the user + double-clicking on the cell marker in the tree view. When the + groupcell is closed the marker is changed and the marker has an + arrow at the bottom. + + 1. .. rubric:: Cursors + :name: cursors + +An OMNotebook document contains cells which in turn contain text. Thus, +two kinds of cursors are needed for positioning, text cursor and cell +cursor: + +- *Textcursor* – A cursor between characters in a cell, appearing as a + small vertical line. Position the cursor by clicking on the text + or using the arrow buttons. + +- *Cellcursor* – This cursor shows which cell currently has the input + focus. It consists of two parts. The main cellcursor is basically + just a thin black horizontal line below the cell with input + focus. The cellcursor is positioned by clicking on a cell, + clicking between cells, or using the menu item Cell->Next Cell or + Cell->Previous Cell. The cursor can also be moved with the key + combination Ctrl+Up or Ctrl+Down. The dynamic cellcursor is a + short blinking horizontal line. To make this visible, you must + click once more on the main cellcursor (the long horizontal + line). NOTE: In order to paste cells at the cellcursor, the + *dynamic cellcursor must be made active* by clicking on the main + cellcursor (the horizontal line). + + 1. .. rubric:: Selection of Text or Cells + :name: selection-of-text-or-cells + +To perform operations on text or cells we often need to select a range +of characters or cells. + +- *Select characters* – There are several ways of selecting characters, + e.g. double-clicking on a word, clicking and dragging the mouse, + or click followed by a shift-click at an adjacent positioin + selects the text between the previous click and the position of + the most recent shift-click. + +- *Select cells* – Cells can be selected by clicking on them. Holding + down Ctrl and clicking on the cell markers in the tree view + allows several cells to be selected, one at a time. Several cells + can be selected at once in the tree view by holding down the + Shift key. Holding down Shift selects all cells between last + selected cell and the cell clicked on. This only works if both + cells belong to the same groupcell. + + 1. .. rubric:: File Menu + :name: file-menu + +The following file related operations are available in the file menu: + +- *Create a new noteboo*\ k – A new notebook can be created using the + menu File->New or the key combination Ctrl+N. A new document + window will then open, with a new document inside. + +- *Open a notebook* – To open a notebook use File->Open in the menu or + the key combination Ctrl+O. Only files of the type .onb or .nb + can be opened. If a file does not follow the OMNotebook format or + the FullForm Mathematica Notebook format, a message box is + displayed telling the user what is wrong. Mathematica Notebooks + must be converted to fullform before they can be opened in + OMNotebook. + +- *Save a notebook* – To save a notebook use the menu item File->Save + or File->Save As. If the notebook has not been saved before the + save as dialog is shown and a filename can be selected. + OMNotebook can only save in xml format and the saved file is not + compatible with Mathematica. Key combination for save is Ctrl+S + and for save as Ctrl+Shift+S. The saved file by default obtains + the file extension .onb. + +- *Print* – Printing a document to a printer is done by pressing the + key combination Ctrl+P or using the menu item File->Print. A + normal print dialog is displayed where the usually properties can + be changed. + +- *Import old document* – Old documents, saved with the old version of + OMNotebook where a different file format was used, can be opened + using the menu item File->Import->Old OMNotebook file. Old + documents have the extension .xml. + +- *Export text* – The text inside a document can be exported to a text + document. The text is exported to this document without almost + any structure saved. The only structure that is saved is the cell + structure. Each paragraph in the text document will contain text + from one cell. To use the export function, use menu item + File->Export->Pure Text. + +- *Close a notebook window* – A notebook window can be closed using the + menu item File->Close or the key combination Ctrl+F4. Any unsaved + changes in the document are lost when the notebook window is + closed. + +- *Quitting OMNotebook* – To quit OMNotebook, use menu item File->Quit + or the key combination Crtl+Q. This closes all notebook windows; + users will have the option of closing OMC also. OMC will not + automatically shutdown because other programs may still use it. + Evaluating the command quit() has the same result as exiting + OMNotebook. + + 1. .. rubric:: Edit Menu + :name: edit-menu + +- *Editing cell text* – Cells have a set of of basic editing functions. + The key combination for these are: Undo (Ctrl+Z), Redo (Ctrl+Y), + Cut (Ctrl+X), Copy (Ctrl+C) and Paste (Ctrl+V). These functions + can also be accessed from the edit menu; Undo (Edit->Undo), Redo + (Edit->Redo), Cut (Edit->Cut), Copy (Edit->Copy) and Paste + (Edit->Paste). Selection of text is done in the usual way by + double-clicking, triple-clicking (select a paragraph), dragging + the mouse, or using (Ctrl+A) to select all text within the cell. + +- *Cut cell* – Cells can be cut from a document with the menu item + Edit->Cut or the key combination Ctrl+X. The cut function will + always cut cells if cells have been selected in the tree view, + otherwise the cut function cuts text. + +- *Copy cell* – Cells can be copied from a document with the menu item + Edit->Copy or the key combination Ctrl+C. The copy function will + always copy cells if cells have been selected in the tree view, + otherwise the copy function copy text. + +- *Paste cell* – To paste copied or cut cells the cell cursor must be + selected in the location where the cells should be pasted. This + is done by clicking on the cell cursor. Pasteing cells is done + from the menu Edit->Paste or the key combination Ctrl+V. If the + cell cursor is selected the paste function will always paste + cells. OMNotebook share the same application-wide clipboard. + Therefore cells that have been copied from one document can be + pasted into another document. Only pointers to the copied or cut + cells are added to the clipboard, thus the cell that should be + pasted must still exist. Consequently a cell can not be pasted + from a document that has been closed. + +- *Find* – Find text string in the current notebook, with the options + match full word, match cell, search within closed cells. Short + command Ctrl+F. + +- *Replace –* Find and replace text string in the current notebook, + with the options match full word, match cell, search+replace + within closed cells. Short command Ctrl+H. + +- *View expression* – Text in a cell is stored internally as a subset + of HTML code and the menu item Edit->View Expression let the user + switch between viewing the text or the internal HTML + representation. Changes made to the HTML code will affect how the + text is displayed. + + 1. .. rubric:: Cell Menu + :name: cell-menu + +- *Add textcell* – A new textcell is added with the menu item Cell->Add + Cell (previous cell style) or the key combination Alt+Enter. The + new textcell gets the same style as the previous selected cell + had. + +- *Add inputcell* – A new inputcell is added with the menu item + Cell->Add Inputcell or the key combination Ctrl+Shift+I. + +- *Add groupcell* – A new groupcell is inserted with the menu item + Cell->Groupcell or the key combination Ctrl+Shift+G. The selected + cell will then become the first cell inside the groupcell. + +- *Ungroup groupcell* – A groupcell can be ungrouped by selecting it in + the tree view and using the menu item Cell->Ungroup Groupcell or + by using the key combination Ctrl+Shift+U. Only one groupcell at + a time can be ungrouped. + +- *Split cell* – Spliting a cell is done with the menu item Cell->Split + cell or the key combination Ctrl+Shift+P. The cell is splited at + the position of the text cursor. + +- *Delete cell* – The menu item Cell->Delete Cell will delete all cells + that have been selected in the tree view. If no cell is selected + this action will delete the cell that have been selected by the + cellcursor. This action can also be called with the key + combination Ctrl+Shift+D or the key Del (only works when cells + have been selected in the tree view). + +- *Cellcursor* – This cell type is a special type that shows which cell + that currently has the focus. The cell is basically just a thin + black line. The cellcursor is moved by clicking on a cell or + using the menu item Cell->Next Cell or Cell->Previous Cell. The + cursor can also be moved with the key combination Ctrl+Up or + Ctrl+Down. + + 1. .. rubric:: Format Menu + :name: format-menu + +- *Textcell* – This cell type is used to display ordinary text and + images. Each textcell has a style that specifies how text is + displayed. The cells style can be changed in the menu + Format->Styles, examples of different styles are: Text, Title, + and Subtitle. The Textcell type also have support for following + links to other notebook documents. + +- *Text manipulation* – There are a number of different text + manipulations that can be done to change the appearance of the + text. These manipulations include operations like: changing font, + changing color and make text bold, but also operations like: + changing the alignment of the text and the margin inside the + cell. All text manipulations inside a cell can be done on single + letters, words or the entire text. Text settings are found in the + Format menu. The following text manipulations are available in + OMNotebook: + +> Font family + +> Font face (Plain, Bold, Italic, Underline) + +> Font size + +> Font stretch + +> Font color + +> Text horizontal alignment + +> Text vertical alignment + +> Border thickness + +> Margin (outside the border) + +> Padding (inside the border) + +Insert Menu +~~~~~~~~~~~ + +- *Insert image* – Images are added to a document with the menu item + Insert->Image or the key combination Ctrl+Shift+M. After an image + has been selected a dialog appears, where the size of the image + can be chosen. The images actual size is the default value of the + image. OMNotebook stretches the image accordantly to the selected + size. All images are saved in the same file as the rest of the + document. + +- *Insert link* – A document can contain links to other OMNotebook file + or Mathematica notebook and to add a new link a piece of text + must first be selected. The selected text make up the part of the + link that the user can click on. Inserting a link is done from + the menu Insert->Link or with the key combination Ctrl+Shift+L. A + dialog window, much like the one used to open documents, allows + the user to choose the file that the link refers to. All links + are saved in the document with a relative file path so documents + that belong together easily can be moved from one place to + another without the links failing. + + 1. .. rubric:: Window Menu + :name: window-menu + +- *Change window* – Each opened document has its own document window. + To switch between those use the Window menu. The window menu + lists all titles of the open documents, in the same order as they + were opened. To switch to another document, simple click on the + title of that document. + + 1. .. rubric:: Help Menu + :name: help-menu + +- *About OMNotebook* – Accessing the about message box for OMNotebook + is done from the menu Help->About OMNotebook. + +- *About Qt* – To access the message box for Qt, use the menu + Help->About Qt. + +- *Help Text* – Opening the help text (document OMNotebookHelp.onb) for + OMNotebook can be done in the same way as any OMNotebook document + is opened or with the menu Help->Help Text. The menu item can + also be triggered with the key F1. + + 1. .. rubric:: Additional Features + :name: additional-features + +- *Links* – By clicking on a link, OMNotebook will open the document + that is referred to in the link. + +- *Update link* – All links are stored with relative file path. + Therefore OMNotebook has functions that automatically updating + links if a document is resaved in another folder. Every time a + document is saved, OMNotebook checks if the document is saved in + the same folder as last time. If the folder has changed, the + links are updated. + +- \ *Evaluate several cells* – Several inputcells can be evaluated at + the same time by selecting them in the treeview and then pressing + the key combination Shift+Enter or Shift+Return. The cells are + evaluated in the same order as they have been selected. If a + groupcell is selected all inputcells in that groupcell are + evaluated, in the order they are located in the groupcell. + +- *Command completion* – Inputcells have command completion support, + which checks if the user is typing a command (or any keyword + defined in the file commands.xml) and finish the command. If the + user types the first two or three letters in a command, the + command completion function fills in the rest. To use command + completion, press the key combination Ctrl+Space or Shift+Tab. + The first command that matches the letters written will then + appear. Holding down Shift and pressing Tab (alternative holding + down Ctrl and pressing Space) again will display the second + command that matches. Repeated request to use command completion + will loop through all commands that match the letters written. + When a command is displayed by the command completion + functionality any field inside the command that should be edited + by the user is automatically selected. Some commands can have + several of these fields and by pressing the key combination + Ctrl+Tab, the next field will be selected inside the command. > + Active Command completion: Ctrl+Space / Shift+Tab > Next command: + Ctrl+Space / Shift+Tab > Next field in command: Ctrl+Tab’ + +- *Generated plot* – When plotting a simulation result, OMC uses the + program Ptplot to create a plot. From Ptplot OMNotebook gets an + image of the plot and automatically adds that image to the output + part of an inputcell. Like all other images in a document, the + plot is saved in the document file when the document is saved. + +- *Stylesheet* –OMNotebook follows the style settings defined in + stylesheet.xml and the correct style is applied to a cell when + the cell is created. + +- *Automatic Chapter Numbering* – OMNotebook automatically numbers + different chapter, subchapter, section and other styles. The user + can specify which styles should have chapter numbers and which + level the style should have. This is done in the stylesheet.xml + file. Every style can have a tag that specifies + the chapter level. Level 0 or no tag at all, means that the style + should not have any chapter numbering. + +- *Scrollarea* – Scrolling through a document can be done by using the + mouse wheel. A document can also be scrolled by moving the cell + cursor up or down. + +- *Syntax highlighter* – The syntax highlighter runs in a separated + thread which speeds up the loading of large document that + contains many Modelica code cells. The syntax highlighter only + highlights when letters are added, not when they are removed. The + color settings for the different types of keywords are stored in + the file modelicacolors.xml. Besides defining the text color and + background color of keywords, whether or not the keywords should + be bold or/and italic can be defined. + +- *Change indicator* – A star (\*) will appear behind the filename in + the title of notebook window if the document has been changed and + needs saving. When the user closes a document that has some + unsaved change, OMNotebook asks the user if he/she wants to save + the document before closing. If the document never has been saved + before, the save-as dialog appears so that a filename can be + choosen for the new document. + +- *Update menus* – All menus are constantly updated so that only menu + items that are linked to actions that can be performed on the + currently selected cell is enabled. All other menu items will be + disabled. When a textcell is selected the Format menu is updated + so that it indicates the text settings for the text, in the + current cursor position. + + 1. .. rubric:: References + :name: references-1 + +Eric Allen, Robert Cartwright, Brian Stoler. DrJava: A lightweight +pedagogic environment for Java. In Proceedings of the 33rd ACM Technical +Symposium on Computer Science Education (SIGCSE 2002) (Northern Kentucky +– The Southern Side of Cincinnati, USA, February 27 – March 3, 2002). + +Ingemar Axelsson. OpenModelica Notebook for Interactive Structured +Modelica Documents. Final thesis, LITH-IDA-EX–05/080–SE, Linköping +University, Linköping, Sweden, October 21, 2005. + +Anders Fernström, Ingemar Axelsson, Peter Fritzson, Anders Sandholm, +Adrian Pop. OMNotebook – Interactive WYSIWYG Book Software for Teaching +Programming. In Proc. of the Workshop on Developing Computer Science +Education – How Can It Be Done?. Linköping University, Dept. Computer & +Inf. Science, Linköping, Sweden, March 10, 2006. + +Anders Fernström. Extending OMNotebook – An Interactive Notebook for +Structured Modelica Documents. Final thesis, LITH-IDA-EX--06/057—SE, +Dept. Computer and Information Science, Linköping University, Sweden, +September 4, 2006. + +Knuth, Donald E. Literate Programming. The Computer Journal, NO27(2), +pp. 97–111, May 1984. + +Eva-Lena Lengquist-Sandelin, Susanna Monemar, Peter Fritzson, and Peter +Bunus. DrModelica – A Web-Based Teaching Environment for Modelica. In +Proceedings of the 44th Scandinavian Conference on Simulation and +Modeling (SIMS’2003), available at www.scan-sims.org. Västerås, Sweden. +September 18-19, 2003. + +The Modelica Association. The Modelica Language Specification Version +3.0, Sept 2007. http://www.modelica.org. + +Stephen Wolfram. The Mathematica Book. Wolfram Media Inc, 1997. + +.. |image19| image:: media/image33.png +.. |image20| image:: media/image35.png +.. |image23| image:: media/image42.png +.. |image24| image:: media/image43.png +.. |image25| image:: media/image44.png diff --git a/usersguide-sphinx/source/optimization.rst b/usersguide-sphinx/source/optimization.rst new file mode 100644 index 00000000000..d06d2d0e1f3 --- /dev/null +++ b/usersguide-sphinx/source/optimization.rst @@ -0,0 +1,1264 @@ +Optimization with OpenModelica +============================== + +The following facilities for model-based optimization are provided with +OpenModelica: + +- Builtin dynamic optimization with OpenModelica and IpOpt using + dynamic optimization, Section 6.1 This is the recommended way of + performing dynamic optimization with OpenModelica. + +- Dynamic optimization with OpenModelica by automatic export of the + problem to CasADi, Section 6.2. Use this if you want to employ + the CasADi tool for dynamic optimization. + +- Classical parameter sweep based design optimization, Section 6.3. Use + this if you have a static optimization problem. + + 1. .. rubric:: Builtin Dynamic Optimization with OpenModelica and + IpOpt + :name: builtin-dynamic-optimization-with-openmodelica-and-ipopt + +*Note: this is a very short preliminary decription which soon will be +considerably improved.* + +OpenModelica provides builtin dynamic optimization of models by using +the powerful symbolic machinery of the OpenModelica compiler for more +efficient and automatic solution of dynamic optimization problems. + +The builtin dynamic optimization allows users to define optimal control +problems (OCP) using the Modelica language for the model and the +optimization language extension called Optimica (currently partially +supported) for the optimization part of the problem. This is used to +solve the underlying dynamic optimization model formulation using +collocation methods, using a single execution instead of multiple +simulations as in the parameter-sweep optimization described in Section +6.3. + +For more detailed information regarding background and methods, see the +papers: + +- Bernhard Bachmann, Lennart Ochel, Vitalij Ruge, Mahder Gebremedhin, + Peter Fritzson, Vaheed Nezhadali, Lars Eriksson, Martin + Sivertsson. Parallel Multiple-Shooting and Collocation + Optimization with OpenModelica. In Proceedings of the 9th + International Modelica Conference (Modelica'2012), Munich, + Germany, Sept.3-5, 2012. + +- Vitalij Ruge, Willi Braun, Bernhard Bachmann, Andrea Walther and + Kshitij Kulshreshtha. Efficient Implementation of Collocation + Methods for Optimization using OpenModelica and ADOL–C. In + Proceedings of the 10th International Modelica Conference + (Modelica'2014), Munich, Germany, March.10-12, 2014. + +|image26| + +Figure 642: **OMNotebook screenshot for dynamic optimization.** + +Compiling the Modelica code +--------------------------- + +Before starting the optimization the model should be symbolically +instantiated by the compiler in order to get a single flat system of +equations. The model variables should also be scalarized. The compiler +frontend performs this, including syntax checking, semantics and type +checking, simplification and constant evaluation etc. are applied. Then +the complete flattened model can be used for initialization, simulation +and last but not least for model-based dynamic optimization. + +The OpenModelica command optimize(ModelName) from OMShell, OMNotebook or +MDT runs immediately the optimization. The generated result file can be +read in and visualized with OMEdit or within OMNotebook. + +// name: BatchReactor.mos + +setCommandLineOptions("+g=Optimica"); + +getErrorString(); + +loadFile("BatchReactor.mo"); + +getErrorString(); + +optimize(nmpcBatchReactor, numberOfIntervals=16, stopTime=1, +tolerance=1e-8); + +getErrorString(); + +An Example +---------- + +In this section, a simple optimal control problem will be solved. When +formulating the optimization problems, models are expressed in the +Modelica language and optimization specifications. The optimization +language specification allows users to formulate dynamic optimization +problems to be solved by a numerical algorithm. It includes several +constructs including a new specialized class optimization, a constraint +section, startTime, finalTime etc. See the optimal control problem for +batch reactor model below. + +**optimization** BatchReactor(objective=-x2(finalTime), + +startTime = 0, finalTime =1) + +Real x1(start =1, fixed=true, min=0, max=1); + +Real x2(start =0, fixed=true, min=0, max=1); + +**input** Real u(min=0, max=5); + +**equation** + +**der**\ (x1) = -(u+u^2/2)\*x1; + +**der**\ (x2) = u\*x1; + +**end** BatchReactor; + +Create a new file named BatchReactor.mo and save it in you working +directory. Notice that this model contains both the dynamic system to be +optimized and the optimization specification. + +Once we have formulated the undelying optimal control problems, we can +run the optimization by using OMShell, OMNotebook , MDT, OMEdit or +command line terminals similar as described in Figure 6 -42. + +The control and state trajectories of the optimization results are shown +in Figure 6 -43. + +|image27| + +|image28| + +Figure 643: **Optimization results for Batch Reactor model – state and +control variables.** + +Different Options for the Optimizer IPOPT +----------------------------------------- + +Compiler options + ++-----------------------+-------------------------+-------------------------+ +| numberOfIntervals | | collocation intervals | ++-----------------------+-------------------------+-------------------------+ +| startTime, stopTime | | time horizon | ++-----------------------+-------------------------+-------------------------+ +| tolerance = 1e-8 | e.g. 1e-8 | solver tolerance | ++-----------------------+-------------------------+-------------------------+ +| simflags | all run/debug options | ++-----------------------+-------------------------+-------------------------+ + +Run/debug options + ++---------------------+------------------+-----------------------------------------+ +| -lv | LOG\_IPOPT | console output | ++---------------------+------------------+-----------------------------------------+ +| -ipopt\_hesse | CONST,BFGS,NUM | hessian approximation | ++---------------------+------------------+-----------------------------------------+ +| -ipopt\_max\_iter | number e.g. 10 | maximal number of iteration for ipopt | ++---------------------+------------------+-----------------------------------------+ +| externalInput.csv | | input guess | ++---------------------+------------------+-----------------------------------------+ + +Figure 644: **Compiler options for IpOpt.** + +Dynamic Optimization with OpenModelica and CasADi +------------------------------------------------- + +OpenModelica coupling with CasADi supports dynamic optimization of +models by OpenModelica exporting the optimization problem to CasADi +which performs the optimization. In order to convey the dynamic system +model information between Modelica and CasADi, we use an XML-based model +exchange format for differential-algebraic equations (DAE). OpenModelica +supports export of models written in Modelica and the Optimization +language extension using this XML format, while CasADi supports import +of models represented in this format. This allows users to define +optimal control problems (OCP) using Modelica and Optimization language +specifications, and solve the underlying model formulation using a range +of optimization methods, including direct collocation and direct +multiple shooting. + +Compiling the Modelica code +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Before exporting a model to XML, the model should be symbolically +instantiated by the compiler in order to get a single flat system of +equations. The model variables should also be scalarized. The compiler +frontend performs this, including syntax checking, semantics and type +checking, simplification and constant evaluation etc. are applied. Then +the complete flattened model is exported to XML code. The exported XML +document can then be imported to CasADi for model-based dynamic +optimization. + +The OpenModelica command translateModelXML(ModelName) from OMShell, +OMNotebook or MDT exports the XML. The export XML command is also +integrated with OMEdit. Select XML > Export XML the XML document is +generated in the current directory of omc. You can use the cd() command +to see the current location. After the command execution is complete you +will see that a file ModelName.xml has been exported. As depicted in +Figure 6 -45, we first changed the current directory to +C:/OpenModelica1.9.2/bin, and then we loaded a Modelica file with +BatchReactor example model and finally exported an XML for it using the +translateModelXML call. + +Assuming that the model is defined in the modelName.mo, the model can +also be exported to an XML code using the following steps from the +terminal window: + +- Go to the path where your model file found(C:/<%path to modelName .mo + file%>). + +- Go to omc path (<%path to omc%>/omc) and write the flag +s + +g=Optimica +simCodeTarget=XML <%your.mo file name%>.mo> + +|image29| + +Figure 645: **OMShell screenshot for exporting an XML.** + +An example +~~~~~~~~~~ + +In this section, a simple optimal control problem will be solved. When +formulating the optimization problems, models are expressed in the +Modelica language and optimization specifications. The optimization +language specification allows users to formulate dynamic optimization +problems to be solved by a numerical algorithm. It includes several +constructs including a new specialized class optimization, a constraint +section, startTime, finalTime etc. See the optimal control problem for +batch reactor model below. + +**optimization** BatchReactor(objective=-x2(finalTime), + +startTime = 0, finalTime =1) + +Real x1(start =1, fixed=true, min=0, max=1); + +Real x2(start =0, fixed=true, min=0, max=1); + +input Real u(min=0, max=5); + +**equation** + +der(x1) = -(u+u^2/2)\*x1; + +der(x2) = u\*x1; + +**end** BatchReactor; + +Create a new file named BatchReactor.mo and save it in you working +directory. Notice that this model contains both the dynamic system to be +optimized and the optimization specification. + +One we have formulated the undelying optimal control problems, we can +export the XML by using OMShell, OMNotebook , MDT, OMEdit or command +line terminals which are described in Section 6.2.4 . + +To export XML using terminals as depicted in Figure 6 -46, we first +changed the current directory to C:/TestCases, and run command +../Dev/OpenModleica/build/bin omc +s +g=Optimica +simCodeTarget=XML +BatchReactor.mo. This will generate an XML file under C:/TestCases +directory named BatchReactor.xml shown in Section 6.2.3 that contains a +symbolic representation of the optimal control problem and can be +inspected in a standard XML editor. + +|image30| + +Figure 646: **Terminal screenshot for exporting an XML.** + +Generated XML for Example +~~~~~~~~~~~~~~~~~~~~~~~~~ + + + + + + + + + + + + + + + + + + + + + + + + + +true + + + + + + + +independentParameter + + + + + + + + + + + + + +true + + + + + + + +independentParameter + + + + + + + + + + + + + +state + + + + + + + + + + + + + +state + + + + + + + + + + + + + +derivative + + + + + + + + + + + + + +derivative + + + + + + + + + + + + + +algebraic + + + + + + + + + + + + + + + + + +0 + + + + + + + + + + + + + + + +1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +2.0 + + + + + +2.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +1.0 + + + + + + + + + + + + + + + +0.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +0.0 + +false + +0.0 + + + + + +1.0 + +false + +1.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +XML Import to CasADi via OpenModelica Python Script +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The symbolic optimal control problem representation (or just model +description) contained in BatchReactor.xml can be imported into CasADi +in the form of the SymbolicOCP class via OpenModelica python script. + +The SymbolicOCP class contains symbolic representation of the optimal +control problem designed to be general and allow manipulation. For a +more detailed description of this class and its functionalities, we +refer to the API documentation of CasADi. + +The following step compiles the model to an XML format, imports to +CasADi and solves an optimization problem in windows PowerShell: + +1. Create a new file named BatchReactor.mo and save it in you working + directory. + + E.g. C:\\OpenModelica1.9.2\\share\\casadi\\testmodel + +1. Perform compilation and generate the XML file + + a. Go to your working directory + + E.g. cd C:\\OpenModelica1.9.2\\share\\casadi\\testmodel + +a. Go to omc path from working directory and run the following command + + E.g. ..\\..\\..\\bin\\omc +s +g=Optimica +simCodeTarget=XML + BatchReactor.mo + +3. Run defaultStart.py python script from OpenModelica optimization +directory + +E.g. Python.exe ..\\share\\casadi\\scripts defaultStart.py +BatchReactor.xml + +The control and state trajectories of the optimization results are shown +in Figure 6 -47. + +|image31| + +|image32| + +Figure 647: **Optimization results for Batch Reactor model – state and +control variables.** + +Parameter Sweep Optimization using OMOptim +------------------------------------------ + +OMOptim is a tool for parameter sweep design optimization of Modelica +models. By optimization, one should understand a procedure which +minimizes/maximizes one or more objective functions by adjusting one or +more parameters. This is done by the optimization algorithm performing a +parameter swep, i.e., systematically adjusting values of selected +parameters and running a number of simulations for different parameter +combinations to find a parameter setting that gives an optimal value of +the goal function. + +OMOptim 0.9 contains meta-heuristic optimization algorithms which allow +optimizing all sorts of models with following functionalities: + +- One or several objectives optimized simultaneously + +- One or several parameters (integer or real variables) + +However, the user must be aware of the large number of simulations an +optimization might require. + +Preparing the Model +~~~~~~~~~~~~~~~~~~~ + +Before launching OMOptim, one must prepare the model in order to +optimize it. + +Parameters +^^^^^^^^^^ + +An optimization parameter is picked up from all model variables. The +choice of parameters can be done using the OMOptim interface. + +For all intended parameters, please note that: + +- The corresponding variable is **constant** during all simulations. + The OMOptim optimization in version 0.9 only concerns static + parameters’ optimization *i.e.* values found for these parameters + will be constant during all simulation time. + +- The corresponding variable should play an **input** role in the model + *i.e.* its modification influences model simulation results. + + 1. .. rubric:: Constraints + :name: constraints + +If some constraints should be respected during optimization, they must +be defined in the Modelica model itself. + +For instance, if mechanical stress must be less than 5 N.m\ :sup:`-2`, +one should write in the model: + +assert( mechanicalStress < 5, “Mechanical stress too high”); + +If during simulation, the variable *mechanicalStress* exceeds 5 +N.m\ :sup:`-2`, the simulation will stop and be considered as a failure. + +Objectives +^^^^^^^^^^ + +As parameters, objectives are picked up from model variables. +Objectives’ values are considered by the optimizer at the *final time*. + +1. .. rubric:: Set problem in OMOptim + :name: set-problem-in-omoptim + + 1. .. rubric:: Launch OMOptim + :name: launch-omoptim + +OMOptim can be launched using the executable placed in +OpenModelicaInstallationDirectory/bin/ OMOptim/OMOptim.exe. Alternately, +choose OpenModelica > OMOptim from the start menu. + +Create a new project +^^^^^^^^^^^^^^^^^^^^ + +To create a new project, click on menu File -> New project + +Then set a name to the project and save it in a dedicated folder. The +created file created has a .min extension. It will contain information +regarding model, problems, and results loaded. + +Load models +^^^^^^^^^^^ + +First, you need to load the model(s) you want to optimize. To do so, +click on *Add .mo* button on main window or select menu *Model -> Load +Mo file…* + +When selecting a model, the file will be loaded in OpenModelica which +runs in the background. + +While OpenModelica is loading the model, you could have a frozen +interface. This is due to multi-threading limitation but the delay +should be short (few seconds). + +You can load as many models as you want. + +If an error occurs (indicated in log window), this might be because: + +- Dependencies have not been loaded before (e.g. modelica library) + +- Model use syntax incompatible with OpenModelica. + +**Dependencies** + +OMOptim should detect dependencies and load corresponding files. +However, it some errors occur, please load by yourself dependencies. You +can also load Modelica library using Model->Load Modelica library. + +When the model correctly loaded, you should see a window similar to +Figure 6 -48. + +|image33| + +Figure 648. **OMOptim window after having loaded model.** + +Create a new optimization problem +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Problem->Add Problem->Optimization + +A dialog should appear. Select the model you want to optimize. Only +Model can be selected (no Package, Component, Block…). + +A new form will be displayed. This form has two tabs. One is called +Variables, the other is called Optimization. + +|image34| Figure 649. **Forms for defining a new optimization problem.** + +**List of Variables is Empty** + +If variables are not displayed, right click on model name in model +hierarchy, and select *Read variables*. + +|image35| + +Figure 650. **Selecting read variables, set parameters, and selecting +simulator.** + +Select Optimized Variables +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To set optimization, we first have to define the variables the optimizer +will consider as free *i.e.* those that it should find best values of. +To do this, select in the left list, the variables concerned. Then, add +them to *Optimized variables* by clicking on corresponding button +(|image36|). + +For each variable, you must set minimum and maximum values it can take. +This can be done in the *Optimized variables* table. + +Select objectives +^^^^^^^^^^^^^^^^^ + +Objectives correspond to the final values of chosen variables. To select +these last, select in left list variables concerned and click |image37| +button of *Optimization objectives* table. + +For each objective, you must: + +- Set minimum and maximum values it can take. If a configuration does + not respect these values, this configuration won’t be considered. + You also can set minimum and maximum equals to “-“ : it will then + +- Define whether objective should be minimized or maximized. + +This can be done in the *Optimized variables* table. + +Select and configure algorithm +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +After having selected variables and objectives, you should now select +and configure optimization algorithm. To do this, click on +*Optimization* tab. + +Here, you can select optimization algorithm you want to use. In version +0.9, OMOptim offers three different genetic algorithms. Let’s for +example choose SPEA2Adapt which is an auto-adaptative genetic algorithm. + +By clicking on *parameters*\ … button, a dialog is opened allowing +defining parameters. These are: + +- *Population size*: this is the number of configurations kept after a + generation. If it is set to 50, your final result can’t contain + more than 50 different points. + +- *Off spring rate*: this is the number of children per adult obtained + after combination process. If it is set to 3, each generation + will contain 150 individual (considering population size is 50). + +- *Max generations*: this number defines the number of generations + after which optimization should stop. In our case, each + generation corresponds to 150 simulations. Note that you can + still stop optimization while it is running by clicking on *stop* + button (which will appear once optimization is launched). + Therefore, you can set a really high number and still stop + optimization when you want without losing results obtained until + there. + +- *Save frequency*: during optimization, best configurations can be + regularly saved. It allows to analyze evolution of best + configurations but also to restart an optimization from + previously obtained results. A Save Frequency parameter set to 3 + means that after three generations, a file is automatically + created containing best configurations. These files are named + iteraion1.sav, iteration2.sav and are store in *Temp* directory, + and moved to *SolvedProblems* directory when optimization is + finished. + +- *ReinitStdDev*: this is a specific parameter of EAAdapt1. It defines + whether standard deviation of variables should be reinitialized. + It is used only if you start optimization from previously + obtained configurations (using *Use start file* option). Setting + it to yes (1) will, in most of cases, lead to a spread research + of optimized configurations, forgetting parameters’ variations’ + reduction obtained in previous optimization. + +**Use start file** + +As indicated before, it is possible to pursue an optimization finished +or stopped. To do this, you must enable *Use start file* option and +select file from which optimization should be started. This file is an +*iteration\_.sav* file created in previous optimization. It is stored in +corresponding *SolvedProblems* folder (*iteration10.sav* corresponds to +the tenth generation of previous optimization). + +***Note that this functionality can only work with same variables and +objectives*.** However, minimum, maximum of variables and objectives can +be changed before pursuing an optimization. + +Launch +^^^^^^ + +You can now launch Optimization by clicking *Launch* button. + +Stopping Optimization +^^^^^^^^^^^^^^^^^^^^^ + +Optimization will be stopped when the generation counter will reach the +generation number defined in parameters. However, you can still stop the +optimization while it is running without loosing obtained results. To do +this, click on *Stop* button. Note that this will not immediately stop +optimization: it will first finish the current generation. + +This stop function is especially useful when optimum points do not vary +any more between generations. This can be easily observed since at each +generation, the optimum objectives values and corresponding parameters +are displayed in log window. + +Results +~~~~~~~ + +The result tab appear when the optimization is finished. It consists of +two parts: a table where variables are displayed and a plot region. + +Obtaining all Variable Values +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +During optimization, the values of optimized variables and objectives +are memorized. The others are not. To get these last, you must +recomputed corresponding points. To achieve this, select one or several +points in point’s list region and click on *recompute*. + +For each point, it will simulate model setting input parameters to point +corresponding values. All values of this point (including those which +are not optimization parameters neither objectives). + +Window Regions in OMOptim GUI +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +|image38| + +Figure 651. **Window regions in OMOptim GUI.** + +1. .. rubric:: + MDT – The OpenModelica Development Tooling Eclipse Plugin + :name: mdt-the-openmodelica-development-tooling-eclipse-plugin + + 1. .. rubric:: Introduction + :name: introduction-1 + +The Modelica Development Tooling (MDT) Eclipse Plugin as part of OMDev – +The OpenModelica Development Environment integrates the OpenModelica +compiler with Eclipse. MDT, together with the OpenModelica compiler, +provides an environment for working with Modelica and MetaModelica +development projects. This plugin is primarily intended for tool +developers rather than application Modelica modelers. + +The following features are available: + +- Browsing support for Modelica projects, packages, and classes + +- Wizards for creating Modelica projects, packages, and classes + +- Syntax color highlighting + +- Syntax checking + +- Browsing of the Modelica Standard Library or other libraries + +- Code completion for class names and function argument lists + +- Goto definition for classes, types, and functions + +- Displaying type information when hovering the mouse over an + identifier. + + 1. .. rubric:: Installation + :name: installation + +The installation of MDT is accomplished by following the below +installation instructions. These instructions assume that you have +successfully downloaded and installed Eclipse (http://www.eclipse.org). + +1. Start Eclipse + +2. Select Help->Software Updates->Find and Install.\ **..** from the + menu + +3. Select ‘Search for new features to install’ and click ‘Next’ + +4. Select ‘New Remote Site...’ + +5. Enter ‘MDT’ as name and + ‘\ `*http://www.ida.liu.se/labs/pelab/modelica/OpenModelica/MDT* `__\ ’ + as URL and click ‘OK’ + +6. Make sure ‘MDT’ is selected and click ‘Finish’ + +7. In the updates dialog select the ‘MDT’ feature and click ‘Next’ + +8. Read through the license agreement, select ‘I accept...’ and click + ‘Next’ + +9. Click ‘Finish’ to install MDT + + 1. .. rubric:: Getting Started + :name: getting-started + + 1. .. rubric:: Configuring the OpenModelica Compiler + :name: configuring-the-openmodelica-compiler + +MDT needs to be able to locate the binary of the compiler. It uses the +environment variable OPENMODELICAHOME to do so. + +If you have problems using MDT, make sure that OPENMODELICAHOME is +pointing to the folder where the Open Modelica Compiler is installed. In +other words, OPENMODELICAHOME must point to the folder that contains the +Open Modelica Compiler (OMC) binary. On the Windows platform it’s called +omc.exe and on Unix platforms it’s called omc. + +Using the Modelica Perspective +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The most convenient way to work with Modelica projects is to use to the +Modelica perspective. To switch to the Modelica perspective, choose the +Window menu item, pick Open Perspective followed by Other\ **...** +Select the Modelica option from the dialog presented and click OK.. + +Selecting a Workspace Folder +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Eclipse stores your projects in a folder called a workspace. You need to +choose a workspace folder for this session, see Figure 5- 7 -52 + +Figure 5752. **Eclipse Setup – Switching Workspace.** + +Creating one or more Modelica Projects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To start a new project, use the New Modelica Project Wizard. It is +accessible through File->New-> Modelica Project or by right-clicking in +the Modelica Projects view and selecting New->Modelica Project. + +Figure 5753. **Eclipse Setup – creating a Modelica project in the +workspace.** + +You need to disable automatic build for the project(s) (Figure 5- 7 +-54). + +Figure 5754. Eclipse Setup – disable automatic build for the +projects\ **.** + +Repeat the procedure for all the projects you need, e.g. for the +exercises described in the MetaModelica users guide: 01\_experiment, +02a\_exp1, 02b\_exp2, 03\_assignment, 04a\_assigntwotype, etc. + +NOTE: Leave open only the projects you are working on! Close all the +others! + +Building and Running a Project +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +After having created a project, you eventually need to build the project +(Figure 7 -55). + +Figure 755. **Eclipse MDT – Building a project.** + +There are several options: building, building from scratch (clean), +running, see Figure 7 -56. + +Figure 756. **Eclipse – building and running a project.** + +You may also open additional views, e.g as in Figure 7 -57. + +Figure 757. Eclipse – Opening views\ **.** + +Switching to Another Perspective +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you need, you can (temporarily) switch to another perspective, e.g. +to the Java perspective for working with an OpenModelica Java client as +in Figure 7 -58. + +Figure 758. Eclipse – Switching to another perspective – e.g. the Java +Perspective\ **.** + +Creating a Package +~~~~~~~~~~~~~~~~~~ + +To create a new package inside a Modelica project, select +File->New->Modelica Package\ **.** Enter the desired name of the package +and a description of what it contains. Note: for the exercises we +already have existing packages. + +Figure 759. **Creating a new Modelica package.** + +Creating a Class +~~~~~~~~~~~~~~~~ + +To create a new Modelica class, select where in the hierarchy that you +want to add your new class and select File->New->Modelica Class. When +creating a Modelica class you can add different restrictions on what the +class can contain. These can for example be model, connector, block, +record, or function. When you have selected your desired class type, you +can select modifiers that add code blocks to the generated code. +‘Include initial code block’ will for example add the line ‘initial +equation’ to the class. + +Figure 760. **Creating a new Modelica class.** + +Syntax Checking +~~~~~~~~~~~~~~~ + +Whenever a build command is given to the MDT environment, modified and +saved Modelica (.mo) files are checked for syntactical errors. Any +errors that are found are added to the Problems view and also marked in +the source code editor. Errors are marked in the editor as a red circle +with a white cross, a squiggly red line under the problematic construct, +and as a red marker in the right-hand side of the editor. If you want to +reach the problem, you can either click the item in the Problems view or +select the red box in the right-hand side of the editor. + +Figure 761. **Syntax checking.** + +Automatic Indentation Support +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +MDT currently has support for automatic indentation. When typing the +Return (Enter) key, the next line is indented correctly. You can also +correct indentation of the current line or a range selection using +CTRL+I or “Correct Indentation” action on the toolbar or in the Edit +menu. + +Code Completion +~~~~~~~~~~~~~~~ + +MDT supports Code Completion in two variants. The first variant, code +completion when typing a dot after a class (package) name, shows +alternatives in a menu. Besides the alternatives, Modelica documentation +from comments is shown if is available. This makes the selection easyer. + +Figure 762. **Code completion when typing a dot.** + +The second variant is useful when typing a call to a function. It shows +the function signature (formal parameter names and types) in a popup +when typing the parenthesis after the function name, here the signature +Real sin(SI.Angle u) of the sin function: + +Figure 763. **Code completion at a function call when typing left +parenthesis.** + +Code Assistance on Identifiers when Hovering +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When hovering with the mouse over an identifier a popup with information +about the identifier is displayed. If the text is too long, the user can +press F2 to focus the popup dialog and scroll up and down to examine all +the text. As one can see the information in the popup dialog is +syntax-highlighted. + +Figure 764. **Displaying information for identifiers on hovering** + +Go to Definition Support +~~~~~~~~~~~~~~~~~~~~~~~~ + +Besides hovering information the user can press CTRL+click to go to the +definition of the identifier. When pressing CTRL the identifier will be +presented as a link and when pressing mouse click the editor will go to +the definition of the identifier. + +Code Assistance on Writing Records +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When writing records, the same functionality as for function calls is +used. This is useful especially in MetaModelica when writing cases in +match constructs. + +Figure 765. **Code assistance when writing cases with records in +MetaModelica.** + +Using the MDT Console for Plotting +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Figure 766. **Activate the MDT Console** + +Figure 767. **Simulation from MDT Console** + +.. |image26| image:: media/image52.png +.. |image27| image:: media/image53.png +.. |image28| image:: media/image54.png +.. |image29| image:: media/image55.png +.. |image30| image:: media/image56.png +.. |image31| image:: media/image57.png +.. |image32| image:: media/image58.png +.. |image33| image:: media/image59.png +.. |image34| image:: media/image60.png +.. |image35| image:: media/image61.png +.. |image36| image:: media/image62.png +.. |image37| image:: media/image63.png +.. |image38| image:: media/image64.png diff --git a/usersguide-sphinx/source/plotting.rst b/usersguide-sphinx/source/plotting.rst new file mode 100644 index 00000000000..13a77a6cd4b --- /dev/null +++ b/usersguide-sphinx/source/plotting.rst @@ -0,0 +1,112 @@ +2D Plotting +=========== + +This chapter covers the 2D plotting available in OpenModelica via +OMNotebook, OMShell and command line script. The plotting is based on +OMPlot application. + +Example +------- + +class HelloWorld + +Real x(start = 1); + +parameter Real a = 1; + +equation + +der(x) = - a \* x; + +end HelloWorld; + +To create a simple time plot the above model HelloWorld is simulated. To +reduce the amount of simulation data in this example the number of +intervals is limited with the argument numberOfIntervals=10. The +simulation is started with the command below. + +simulate(HelloWorld, startTime=0, stopTime=4, numberOfIntervals=10); + +When the simulation is finished the file HelloWorld res.plt contains the +simulation data. The contents of the file is the following (some +formatting has been applied). + +0 1 + +4.440892098500626e-013 0.9999999999995559 + +0.4444444444444444 0.6411803884299349 + +0.8888888888888888 0.411112290507163 + +1.333333333333333 0.2635971381157249 + +1.777777777777778 0.1690133154060587 + +2.222222222222222 0.1083680232218813 + +2.666666666666667 0.06948345122279623 + +3.111111111111112 0.04455142624447787 + +3.555555555555556 0.02856550078454138 + +4 0.01831563888872685 + +Diagrams are now created with the new OMPlot program by using the +following command. + +plot(x); + +seems to correspond well with the data. + +Figure 323: **Simple 2D plot of the HelloWorld example.** + +By re-simulating and saving results at many more points, e.g. using the +default 500 intervals, a much smoother plot can be obtained. + +simulate(HelloWorld, startTime=0, stopTime=4, numberOfIntervals=500); + +plot(x); + +Figure 324: **Simple 2D plot of the HelloWorld example with larger +number of points.** + +Plotting Commands and their Options +----------------------------------- + +All of these commands can have any number of optional arguments to +further customize the the resulting diagram. The available options and +their allowed values are listed below. + ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| **Option ** | **Default value** | **Description** | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| fileName | The result of the last simulation | The name of the result-file containing the variables to plot | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| grid | true | Determines whether or not a grid is shown in the diagram. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| title | “” | This text will be used as the diagram title. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| logX | false | Determines whether or not the horizontal axis is logarithmically scaled. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| logY | false | Determines whether or not the vertical axis is logarithmically scaled. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| xLabel | “time” | This text will be used as the horizontal label in the diagram. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| yLabel | “” | This text will be used as the vertical label in the diagram. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| xRange | {0, 0} | Determines the horizontal interval that is visible in the diagram. {0, 0} will select a suitable range. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| yRange | {0, 0} | Determines the vertical interval that is visible in the diagram. {0, 0} will select a suitable range. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| curveWidth | 1.0 | Defines the width of the curve. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| curveStyle | 1 | Defines the style of the curve. | +| | | | +| | | SolidLine=1, DashLine=2, DotLine=3, DashDotLine=4, DashDotDotLine=5, Sticks=6, Steps=7. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| legendPosition | “top” | Defines the position of the legend in the diagram. Possible values are left, right, top, bottom and none. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+ +| externalWindow | false | Opens a new OMPlot window if set to true otherwise update the current opened window. | ++------------------+-------------------------------------+-------------------------------------------------------------------------------------------------------------+