Modelica Assignment
|
Practical Information
GoalsIn this assignment, you will use the Modelica Language to first create a model of a Cyber-Physical System (CPS) and then create a controller for optimal control of the CPS. You will learn:
You are discouraged but allowed to make use of any GenAI tool in solving the assignment or writing the report (for example, to correct grammatical mistakes) as long as you adhere to the UA Guidelines for students on responsible use of GenAI.
You are required to cite any use of GenAI and describe what portions of the assignment you used it for. Note that a significant part of demonstrating that the learning goals have been achieved, includes being able to
This will be evaluated in a short (~15 minute) oral evaluation, which will be conducted in the week following the deadline of every assignment. OpenModelicaYou will use OpenModelica to perform all the tasks. You can install the latest stable version of OpenModelica on your systems by following the directions by going to the OpenModelica website > Download > Windows/Linux/Mac (based on your OS). Choose the 'Official Release' package. Installing OpenModelica installs a number of applications in your system: OMEditThe OpenModelica Connection Editor (OMEdit) is the standard graphical user interface that is used for graphical Modelica model creation and editing. We will use OMEdit for all the tasks. Launch instructions and other features of OMEdit are described on the OMEdit website. OMEdit has 4 different views but we are only interested in the Modelling and Plotting views. We will primarily use OMEdit to design the model. Information about the other OpenModelica applications are just given for information. Modelica Standard LibraryA major advantage of using Modelica is the availability of a wide-variety of Modelica libraries, making it easier to re-use blocks and classes from these libraries. For the assignment, you should ensure, once you have installed OpenModelica, that the Modelica Standard Library (MSL) package is also correctly downloaded, and automatically loaded when you start OMEdit. To do so, go to File > Manage Libraries > Install Library > select Modelica with Version 4.0.0 > OK. The Modelica Standard Library should be visible when you restart OMEdit. OMNotebookOMNotebook is a notebook-like tool to learn the usage of OpenModelica and construct more-readable documentation which incorporates code-windows in between text. Think of Jupyter Notebooks. OMShellOMShell is an interactive session handler that parses and interprets commands and Modelica expressions for evaluation, simulation, plotting, etc. The session handler also contains simple history facilities, and completion of file names and certain identifiers in commands. We will not use OMShell because we want to learn and visualize graphically the models that we are building. Hence we will only use OMEdit. We will use Python because we can then directly use the data obtained from simulation for analysis through a number of data analysis packages available in Python. One thing to note is that a Modelica model needs to be compiled only once. Once compiled, the parameters can be changed in subsequent executions/simulation runs without having to re-compile the model. This is advantageous since compilation can prove to be a significant overhead if we are optimising for a number of different parameters and ranges (read: the number of simulation runs could go into the thousands or more, as I'm doing in my research, but that is the beauty of it). BasicsWhile the Modelica language and its capabilities of object-oriented acausal modeling of the multi-physics have already been described in the lectures, what follows is a 'how-to' to get started building your own Modelica models for the assignment using OMEdit. On the left of the OMEdit window, is the Libraries pane which displays all the libraries that have been loaded in the current Modelica session. Modelica models are organised in Packages which can contain other packages and Modelica classes. Create a Modelica Package![]() Figure 1: Example package creation. Go to File > New > New Modelica Class > in the Create New Modelica Class dialog box > enter a valid package name > for Specialization, select Package, this is also shown in Fig.1 > OK. You should now see your Modelica package in the Libraries pane. You should save it before proceeding further by clicking on the corresponding icon in the menu bar or going to File > Save. If you have already created and saved a package, you can load it in the current session by going to File > Open Model/Library Files, and choosing the corresponding file in the file browser. Create your first Modelica ModelRight click on your Modelica package in the Libraries window > in the drop-down menu > select New Modelica Class > in the create New Modelica Class dialog box > enter a valid class name > for Specialization, select Model > for Insert in class ensure the textbox specifies the Modelica package within which you want to create your Modelica model > OK. You have created your first Modelica model! You should save it before proceeding further by clicking on the corresponding icon in the menu bar or going to File > Save. Modelica classes can extend other Modelica classes, i.e. inherit the declarations from the extended class. They may also simply re-use components defined in other Modelica classes. Build/Edit your Modelica ModelDouble click on the Modelica model you want to edit. This takes you to the Modeling view. In the top right corner of the Modeling view are 3 buttons to toggle between different editing interfaces. The 2nd button is to open the graphical editor and the 3rd button is to open the textual editor. ![]() Figure 2: Buttons to change editor views. The Icon view is only used to arrange connector points for a block. The diagram view can only be used in case the model consists of blocks with causal/acausal connections between them. Look at the Modelica By Example website for simple introductory examples of Modelica models based on simple Ordinary Differential Equations of physics. If you are making a component-based model. You can add components to the model by dragging them from the Libraries pane onto the graphical editor. You will be prompted to give the component a unique name. You can draw connections between the interfaces of components by holding the left mouse button while simultaneously moving it from one interface ot the other. This highly intuitive. You can modify parameters of the components by double-clicking on them, which will open the Element Parameters box. Simulate your Modelica Model in OMEdit![]() Figure 3: 'Check Model' and 'Simulation' buttons in OMEdit. Once you have defined a complete and correct Modelica model, you can now simulate it. To do so, you should click on the S icon in the menu bar. This opens the Simulation Setup dialog box. You can set simulation parameters in this dialog box. Make sure that you have verified the simulation start time, stop time, step-size/number of intervals, solver method (DASSL is preferred), and tolerance (the default 1e-6 is good enough, as low as possible is preferred ideally). You can also set the output format to output the data to a file. However, we do not need to do so, since we will later perform simulations through Python where we will handle the simulation output directly. This is just for visualization and initial validation of the model. Click OK to begin simulation. Note: You can also 'check' the model by clicking on the tick-mark icon in the menu bar. The output from this can be observed in the message browser. The message browser will tell you if something is missing in the model, or if there are inconsistencies in the model. Visualize simulation traceClicking OK in the Simulation Setup ideally takes you to the Plotting view. If not, you can go to the plotting view through the corresponding tab in the bottom-right corner. On the right you will see the variable browser. You can select any variable/s to plot them in the pane and observe their values over the simulation. The values indicated in the variables pane is the value of that variable at the end of the simulation. Parametrizing simulation quantities in OMEditTo define a parameter you simply have to use the 'parameter' keyword followed by its unit name and default value in this syntax: parameter <unit> <name> = <default value> ;If you want to parametrize a quantity which is a parameter of a block in your model. Simply double-click on the block in the graphical editor and change the parameter value to the parameter name. This value need not be a numeric quantity, but it can be a reference to the name of the parameter within the model, or a function of the parameter as well. Once you have changed the value in the block, go to the textual editor of your model (not of the block!), and use the same syntax as above to define a parameter. Note that the name of this parameter should correspond to the name of the parameter you have defined in the value of the block. Look at the following image for an example: ![]() Figure 4: Parametrizing the values of the block-parameters of the blocks in your model. Multiple simulations and analyses of your Modelica modelThe example Python file contained in the zip file describes how to use Python to simulate and visualize data from an example Modelica model which will be introduced in the tutorial as well. We will perform multiple simulations by generating the executable through OMEdit. You should make sure that the executable is generated and not deleted in the right directory by:
To generate these files, once the settings mentioned above are correctly configured, you should simulate the model in OMEdit at least once. To re-simulate your model, but not from OMEdit, you can simply use the terminal command to execute the executable which is in a subdirectory of the working directory as described above. This subdirectory is named 'package_name.model_name' and the executable in this subdirectory is executed with the command './model_name' (in Linux). For the example, it will be './NewtonCooling'. Note that you should change the current directory of the terminal session to the example/NewtonCooling/ directory before doing so. This cannot be done from within the example/ directory. The simulation results will be stored in the same directory as the executable. By default, it is a MAT-file, and you should try to use the same because it is the most efficient (compared to CSV, etc.). At the end of each simulation you should read the MAT-file, and record the variables that you are interested in before performing the next simulation, because this file will be overwritten during re-simulation. You can read the MAT-files generated by OpenModelica using the read_mat_file() function in the example code! To re-simulate the model, but with different parameters, you can use command line as well. You simply have to structure your command using the -override flag, as the following './model_name -override parameter1=value, parameter2=value ..'.This is also described and demonstrated in the example code. To implement a loop over the parameter values, you will have to write a Python script. You can execute shell commands using the os package as demonstrated in the example. Take special note that os.changeDir function is used to change the working directory of the virtual shell to the results directory. Assignment Overview
This assignment consists of four main parts:
Each part is aligned with one of the learning goals Problem StatementA hot water storage tank is an indispensable component in many household and industrial heating systems. It serves as a buffer between the heater and the point of demand (e.g. tap water or heating circuits). The role of the tank is to ensure a steady supply of water at a sufficiently high temperature, even when demand fluctuates. The operation of such a system can be described in the following simplified steps:
![]() Figure 5: Simplified illustration of a hot-water heating, storage and distribution system for a building. While this diagram shows multiple outlet valves (imagine each source of water in a building), in the assignment, we will only consider one outlet valve for simplicity. Traditionally, simple thermostat control (on-off) is used to operate such water heaters. However, in more demanding applications, this is not sufficient - it can lead to temperature oscillations, slow responses, or excessive energy use. As can be deduced from the list of steps above, the operation of a water-heating system involves many steps, each of which has complexities of its own. In this assignment, we will instead explore the use of two different controllers :
The goal in this assignment is to design suitable controllers for the water heating system such that:
Plant Model CreationYou are the engineer and the designer/scientist/client has given you the information below. Your task is to model the whole system using the information given below, in Modelica. Special care should be taken to parametrize the model correctly. The first step will always be to make an appropriately named Modelica package. This will serve as the package for your entire Modelica assignment. You SHOULD create NEW models ONLY within this package, for each part of the entire assignment. Task 1: Modelling the hydronic systemYou will first model the fluid transport network which serves as the backbone for the entire system. To do this you should use the Modelica.Fluid package from the Modelica Standard Library. TIP: Have a look at the documentation and the examples section in the Modelica.Fluid package to learn how to use the different components. This is important to understand how to set the parameters for the different components. The ambient conditions are as follows:
The design parameters are set as follows:
Implement the system described above, as a Modelica model, using the graphical editor in OMEdit, and blocks from the Modelica.Fluid library. To simulate and test your model, do the following:
![]() Figure 6: Trace of valve opening through an average day, as described by the above table. Report your model, and graph the traces of the tank level, flow through outlet valve, and valve opening signal. Re-simulate your model for 4 hours. Do you run into a problem? What do you think is the solution (that we will eventually implement)? Task 2: Modelling the electrical heating systemNow you will model the electrical heating system. To do this you should use the Modelica.Electrical.Analog and Modelica.Thermal.HeatTransfer packages from the Modelica Standard Library. TIP: Have a look at the documentation and the examples section in the Modelica.Thermal.HeatTransfer package to learn how to use the different components. This is important to understand how to set the parameters for the different components. The heating is provided by a circuit modelled as a simple resistor across a voltage source: ![]() Figure 7: Diagram of electrical heating circuit.
To implement the system as described above:
Report your model graphically and textually; you will simulate it in the next section. BEWARE: Often customer requirements will be in multiple units as is done above. It is your task to unify and express them all in a single unitary system so that your solution is numerically correct. The recommended way is to use SI units in all cases. BONUS: for giving meaningful names to all blocks and elements in your model/s. NOTE: This is a highly simplified model of a heating circuit. In practice, there is a network of many resistors to distribute power dissipation, and there are complex high power electronics components. Plant Model CalibrationYou have successfully created an abstract model of the water heating system, however it is not complete. Remember the value of the thermal conductance of the conduction of heat from the tank to the ambient? This is a parameter that cannot be estimated from design alone. How will you decide the value of this parameter so that your model truly represents reality? This is done through parameter calibration. The idea is that, we try (combinations of) different parameters, and compare the output of the simulation of the Modelica model, with real-life data. The parameters, which give the least error between the two traces are said to be the best fit, and are chosen accordingly. An exhaustive way of finding optimal parameter values is to loop over possible values for the parameters to find the one that gives the closest match mentioned above. This is known as a parameter sweep. Experimental setupIn the real-world experiment, the same tank as described above was half-filled with water at 50°C, with no inlet or outlet port for the fluid to move. The ambient temperature was constant at 17°C. The evolution of the temperature was measured, as the water in the tank cooled down. The real life-data from the experiment is provided in this csv file. This data represents the temperature of the water in the tank sampled every minute, for one day, in Kelvins. ![]() Figure 8: Evolution of temperature of the water in the tank, in the real-life calibration experiment. Task 1: Calibrate thermal conductance parameterThe main purpose of this part of the assignment is finding the coefficient of conductance in the conduction of heat from the tank to the ambient air, based on experimental data (i.e., observations/measurements on the real system).
Task 2: Simulate plant modelNow that you have estimated a value for G, you can now simulate the plant model that you created in task 2 of the previous section:
Controller Model CreationBased on the description of the problem statement, we want to model the control system as shown below: ![]() Figure 9: Architecture of the complete control system. To do so, you will create three blocks, one each for the plant, bang-bang controller, and PID controller. Task 1: Plant block
Task 2: Bang-bang controllerA bang-bang controller is one of the simplest controllers to control a plant that accepts binary input i.e. something that is completely on or completely off. A bang-bang controller is usually used to keep some process variable within minimum and maximum limits. In our example, this process variable is the height of the medium in the heating tank. Recall from the problem statement that we want to keep the water level between 80% and 95% of the tank's capacity. Also recall the modelling of discontinuous behavior in Modelica using the 'when' statement, that you learnt in the theory lectures. Here is a reference to the syntax.
BONUS: for parametrizing the different values moderating the behavior of the bang-bang controller block. Create a new Modelica model of this assignment, lets call it the "heating control system":
Recall that when you first tested the hydronic model, you were not able to simulate it for 4 hours. Was the simulation successful now? What made the difference? Report the traces of the tank level, bang bang controller output, outlet valve opening, and temperature of the medium in the tank. Is the temperature of the tank unnecessarily high? Recall, that the problem statement only asks for minimum 50°C. Task 3: PID ControllerA PID (Proportional-Integral-Derivative) controller is widely used in practice to drive the output of the plant towards a set-point. This set-point could change in time. We will however, consider the set-point is constant. In our example, the set-point represents the desired temperature of the medium in the tank. The control output from the PID controller, i.e. $u(t)$ drives the plant / process. The plant produces an output i.e. $T(t)$. The difference between the measured output $T(t)$ and the desired output $r(t)$ (a.k.a the set-point) is called the error $e(t)$. This error value is processed in the PID controller in three different ways as shown in the figure: ![]() Figure 10: PID control loop (adapted from Wikipedia).
Hence, the output from the PID controller $u(t)$ is given by: $$u(t) = (K_p \cdot e(t)) + (K_i \cdot \int_0^t e(t) dt) + (K_d \cdot \dfrac{d e(t)}{dt}) $$The gains $K_p$, $K_i$, and $K_d$ modulate the behavior of the PID controller. You may read more about a PID controller online. The essential point is that three signals are summed, which forms the PID control output $u(t)$. So, to sum up, in our case:
Hence, the equation for implementing the control is: $$ e(t) = r - T(t) $$ coupled with the equations above.Note: In our simple case, the set-point is constant
Note: The PID control output should not be negative. A negative output from the PID controller indicates that it wants the instrument to cool the plant. However, a negative voltage will still result in dissipation of heat from the resistive element. Hence, we simply set negative signals to zero by using a limiter block. Once you have created the PID control block, add it to the "heating control system" model, and connect it as shown in Figure 8. Add a constant input of 50 (in °C, or the equivalent in Kelvin) as the set point to the PID control block. Simulate the water heating system with $K_p = 3$, $K_i = 0.5$, and $K_d = 0.2$ for 24 hours with a step-size of 1 second. Report the trace of the temperature and the PID output. Do you think this is an optimal controller? Why or why not? Note: Do not model any part of the PID control loop using textual equations. In this task of the assignment you should use the graphical view to model the PID equations. Only use the textual syntax to define the parameters and interfaces of your model. Controller Model TuningSimilar to the calibration of the plant parameters (recall that we calibrated the thermal conductance), the controller also needs to be tuned for the most ideal control outcome. However, we do not directly have reference data to compare the simulation output to like we had in parameter calibration. Instead, the designer (you) should come up with a cost function to ascertain if the plant behaves as required. Task 1: Design of the cost function
Task 2: Tune PID controller
Task 3: Stricter cost functionLet's say the requirement became stricter, and we want the temperature of the water to be as close to 50°C as possible, at all times. This will affect the cost function. The new cost function will be: $$ J = \sum_{i=1}^{N} | T_{\text{setpoint}} - T_i | $$ Where,
Implement this cost function, and re-run the parameter tuning script with the new cost function. Is there a change in the optimal parameters? Why or why not? Congratulations! You have successfully modeled a physical system and an optimal controller for it in Modelica! Practical Issues
|
Maintained by Hans Vangheluwe. | Last Modified: 2025/10/09 15:21:33. |