The post P, PI, PID tuning for controlling physical models appeared first on Claytex.

]]>This article is about practical aspects of tuning linear controllers in models and maintaining awareness of the physical implications of the results, without delving into the theory. We’ll look at a well-behaved model, which nonetheless illustrates a few features available in the MSL, such as:

- A PID block with and output limiter: MSL.Blocks.Continuous.LimPID
- Time-tables
- Sensors

There are several aspects to take into consideration when tuning your PID gain and time constant values. These include:

- Physical feasibility in general (avoiding applying forces & currents you later realise couldn’t be used)
- Numerical problems (depending on the model, spikes, zero-crossings, and other numerical occurrences can sometimes prevent smooth operation!)
- Signal processing (the real world requires measurements to take place & some are easier than others e.g. shaft torque can be non-trivial to measure)
- Engineering specifications (making it easy to create your design without needless cost or difficulty when the modelling is over)

In this article we’ll pay attention to some of these considerations under controlled conditions.

We will use the model of a DC electric motor with heat and friction losses driving a rotational inertia. The **PID** controller will control the voltage source to try and match the desired angular velocity profile of the motor shaft that is supplied via **timeTable**. The current state of the motor shaft angular velocity is fed back to the controller via a speed sensor. The **PID** output should be limited to the maximum voltage the DC motor can work with. An internal limiter to the **PID** can be used for these purposes and parameterised via the **PID** GUI.

Figure 1: Physical model requiring PID controller tuning to match a desired reference dynamic prescribed in the time table.

As the name suggests, proportional control means the control action will be proportional to how far the measured variable has deviated from a desired state.

Physically, this is just like creating the effect of a “spring” between your target output, and the actual measured value of that output.

Exactly like a spring, making it stiffer will cause the output you’re interested in to be arrested more quickly, but depending on how the dynamics of your system work, it might cause “ringing” in the same way as a real spring would “ping” into place, but then buzz around the equilibrium position.

In this first example the PID block is set to be used as a P (k=100) controller. The I and D related control are disabled. Observing the top plot in Figure 2, we might say that the model responds well – stably, and with fast damping, to an outsize gain. This in principle could seem a pretty successful way to tune the P controller. However, if we intend to implement or process the results in practice, it may be necessary to be more aware of the energy being deployed to control the system and assess whether this is conducive to robust operation.

Figure 2. PID.k = 100. From top: 1: demand u_s (blue) vs system response u_m (red), 2: PID output signal and equal to voltage source value, 3: Motor shaft torque, 4: Derivative of motor shaft torque

For example, it can be seen that with this high gain, the torque and its derivative shown in the third to fourth plot down in Figure 2 show significant spikes at particular points in the simulation. These points correspond to controlled changes in speed of the rotating shaft. Figure 3 shows the locally highly uneven output from the PID block, which could cause problems in later modelling and lead to potentially unnecessarily (numerically) “stiff” systems. Furthermore, shocking physical systems with the kinds of rates of change of torque shown is likely to generate other difficulties like excessive mount excitation and fatigue generating effects. The target angular velocity prescribed in the table is an idealised angular velocity profile that results in discrete changes in the acceleration demand of the shaft. In practice, it will not be possible to control a physical system such as the one described in Figure 2 to perfectly match the discrete changes in angular acceleration. We should expect a smoothed speed profile in these areas.

Figure 3. Zoomed section of controller and plant variables showing the undesired torque and torque derivative ripples at the points where there is a sudden change in acceleration demand that the controller strives to meet.

As we are concerned with the physical implications of using the control block, we should also note that while we’ve directly measured torque & it’s rate of change in the model, verifying these quantities may be non-trivial in a lab test. More importantly for now, is the relative difficulty in measuring high-frequency changes in signals such as those seen above. Creating an unverifiable model can cause practical problems in itself, and so bearing in mind what measurements are likely to be possible is critical in controller modelling, from the perspectives of validation, implementation, and repeatability.

If the gain **k** is reduced from 100 to 3 for example, we find that the outputs look a little bit more familiar, and the motor shaft dynamics are still close to the demand whilst reducing the torque and torque derivative spike magnitudes. The slight mismatch we see between the demand (PID.u_s) and response (PID.u_m) in the top subplot of Figure 4 can be reduced by introducing the Integral control.

Figure 4. Plots of controller and plant model variables using a reduced P controller “k” value

Integral control is the process of using the average of the deviation from the desired result, over time, to add an additional control signal. This means that if the controlled variable is on one side of the demanded value, the controller will increase the signal, to correct the error. Integral control is expressed as a time-constant in the Dymola block, according to the expression:

By maintaining or slightly reducing the value of **k** and adding an integral control (for example: Ti = 0.5 – Note Td is still disabled) we can reduce the system response error while keeping modest gains. The effect on the torque and torque rate can be seen below with the previous attempt (k=3 with Ti disabled).

Figure 6. Effects of enabling the integral gain in the PID block. Errors in the system response vs. the demand are reduced. PI and P in the legends denote which parts of the PID block have been enabled.

Figure 7. Larger version of the top subplot in Figure 6. The plot shows the system response using a P controller (dashed line) and PI controller (solid black line) and the highlighted “setpoint” or demand (red).

Derivative control works by pushing back against rapid change in the output from which the feedback signal is coming. It’s most useful when there’s not sufficient existing tendency in the system dynamics to damp out vibrations and settle, or indeed if you’ve needed to use such a high level of integral control that it’s created oscillations.

In this case it isn’t a necessity but we will demonstrate the effects. The Td value isn’t as intuitive as Ti; a bigger effect is created as Td is increased. That tendency to take energy out of the system by tuning Td, can “soften” spikes, and prevent the controller making changes too quickly (bottom subplot in Figure 8).

If the output could be affected by sudden disturbances, derivative control is helpful, because it will start arresting the deviation caused by that immediately, before the output has gone far from the demand (k), or spent any time residing far from the demand (Ti).

Figure 8. Plot of the controller and plant model variables using a PID block with P and I enabled (blue) and P, I and D (Td = 0.1) enabled (red)

As we proceed through introducing I and D to the P control we started with, it can sometimes be useful to adjust k to a lower value (thus weakening) and increase (thus weaken) Ti to a larger value to reduce the chance of oscillations in the system’s response.

First, test the system response to following a step change or transient to inform the tuning.

**P**is enabled.**I**and**D**are turned off- Carry out tuning of
**P**until the system response is just less than oscillatory (also check energy related variable dynamics such as in this case the torque and its derivative) - Consider a slight reduction of
**k**(noting down the previous tuning as an upper limit for later fine-tuning). Introduce**I**and begin**Ti**tuning so that the error between demand and response goes to zero in a reasonable time for the system. - If you want to further improve the system response particularly in relation to derivatives you may want to introduce the derivative term
**D**- Reduce
**k**and increase**Ti**before tuning**Td**.

- Reduce

Different types of systems respond better to different **P**,**I** and **D** gain tuning. So for some systems you may just use **PD**,** PI** and for others **PID**. In most cases we deal with, **PI** controllers yield sufficient plant model control. In practice, PD control is uncommon because measuring the derivative of a measurement can be awkward (noisy, for example) while only integral control eliminates steady-state errors, that is, errors that do not diminish in time.

**Written by: Sas Harrison – Systems Engineer**

**Please get in touch if you have any questions or have got a topic in mind that you would like us to write about. You can submit your questions / topics via: Tech Blog Questions / Topic Suggestion**

The post P, PI, PID tuning for controlling physical models appeared first on Claytex.

]]>The post Coupling Modelica Automotive Libraries in Vehicle Demos appeared first on Claytex.

]]>Figure 1 – Automotive application Modelica libraries available in Dymola

There are a variety of Modelica libraries available for automotive applications from a number of developers; some of which are highlighted in Figure 1. The current 2017.4 release of Vehicle Demos includes examples that bring together the following libraries:

- VeSyMA – This provides the vehicle architecture and idealised system components
- VeSyMA-Engines – Mean value and crank angle resolved, 1-d and multibody engine models with gas dynamics
- VeSyMA-Powertrain – Multibody modelling of the transmission and driveline
- VeSyMA-Suspensions – Detailed modelling of the suspension systems, including multibody models
- Electrified Powertrains – Models of electric drive systems at various levels of complexity
- Fluid Power – For modelling hydraulic systems

The purpose of * RWDElectric* vehicle model, Figure 2, is to perform energy analysis of a battery electric vehicle. This requires a vehicle with an electric drive, battery pack and motor controller but the other vehicle systems can be idealised. This was achieved by combining components from the VeSyMA and Electrified Powertrains libraries.

Figure 2 – The Vehicle Demos * RWDElectric *vehicle model diagram (Electrified Powertrain models highlighted in red)

The components from the Electrified Powertrains library, highlighted in red in Figure 2, were integrated with the VeSyMA system interfaces to make them compatible with the VeSyMA * CarElectric *template. It was necessary to build a data dictionary to map signals on the control bus between the signal structures used by the VeSyMA and Electrified Powertrains models.

To perform an energy analysis, the * RWDElectric* vehicle was put through a New European Driving Cycle (NEDC) in the

Figure 3 – Plots of the vehicle longitudinal velocity (left) and the battery pack mean state of charge from the NEDC test of the electric vehicle

The vehicles * SmallFamilyMTHydraulicBrakes *and

*The SmallFamilyMTHydraulicBrakes* vehicle is for dynamic vehicle manoeuvre tests of the hydraulic brake system. To do this the vehicle needs to have hydraulic brake components (brake caliper pistons, master cylinder and brake lines), multibody suspension with an idealised engine, transmission and driveline. The Fluid Power hydraulic models were incorporated into the VeSyMA

Figure 4 – Animation of the split mue braking test

The * LargeOffRoad4X4HybridATHydraulicDampers *vehicle is for dynamic vehicle manoeuvre testing of the hydraulic dampers. For this the vehicle requires hydraulic damper components and multibody suspension, accompanied by a simple hybrid powertrain in this case. To build the hydraulic damper model, Fluid Power components were assembled in a damper interface compatible with the VeSyMA – Suspensions

The * RWDCarAT *vehicle was created to permit the transmission of vibration from the engine to gearbox via a dynamic torque converter to be examined. In order to be able to model these effects required a vehicle with a crank angle resolved engine model (CAREM) and a multibody transmission; this was achieved using models from VeSyMA – Engines, VeSyMA – Powertrain, VeSyMA and VeSyMA – Suspensions. Models are compatible across the VeSyMA platform so the systems models from these different libraries could be plugged straight in to the VeSyMA vehicle template together.

Figure 5 – I6 CAREM from VeSyMA – Engines used in * RWDCarAT *vehicle

To demonstrate the damping effect of the dynamic torque converter in reducing the vibration transferred from the engine to the gearset, the * RWDCarAT *vehicle was used in a straightline test. The torsional vibration in the input and output flanges of the torque converter from this experiment are shown in Figure 6, clearly illustrating the damping effect of the torque converter. The detailed combustion model in the CAREM causes the simulation to be relatively slow; the surrogate version was used to improve simulation time, where key variables calculated in cylinder_1 are distributed to the remaining engine cylinders.

Figure 6 – Plot comparing torque in the input (blue) and output (red) flanges of the dynamic torque converter, the sign of the output torque was reversed to ease comparison

The final vehicle in the Vehicle Demos library is the * RWDCarAT* model. Its purpose is to allow the forces and torques experienced in the engine, transmission and driveline during a highly aggressive pull away to be analysed for potential component failures. In order to perform this kind of analysis the vehicle needed to have a multibody, torsionally compliant driveline and elastic mounts; which was achieved using the VeSyMA, VeSyMA – Engines and VeSyMA – Powertrain libraries. This type of analysis did not require a CAREM, so a Mean Value Engine Model (MVEM) was used from VeSyMA – Engines; this is still a multibody model but simulation performance is vastly increased over a CAREM.

In the Vehicle Demos * IdiotStart* experiment the

Figure 7 – Plot showing the torques throughout the powertrain during the idiot start

Hopefully this post has given you a better idea of the joint capability of the Modelica automotive libraries available in Dymola. The Vehicle Demos Library will continue to be developed to include further examples of the automotive libraries from Figure 1 being coupled together. To take a look at the Vehicle Demos library for yourself, go to the File > Demos menu in Dymola; you will require a license for the commercial libraries used.

**Written by: Hannah Hammond-Scott – Senior Engineer**

**Please get in touch if you have any questions or have got a topic in mind that you would like us to write about. You can submit your questions / topics via: Tech Blog Questions / Topic Suggestion.**

The post Coupling Modelica Automotive Libraries in Vehicle Demos appeared first on Claytex.

]]>The post The Dymola Compilation Process in Action appeared first on Claytex.

]]>Figure 1 shows the Dymola translation and simulation process diagram in which a Modelica model passes through to generate the Simulation results.

Figure 1. Dymola translation and simulation process diagram.

Step 2 of Figure 1 depicts how the C code is built into an application file(s). This build process is the focus of this blog post.

*Please note that this blog post has used Dymola 2018 FD01 for demonstration purposes.*

Dymola converts (translates) a Modelica model into C code by using symbolic processing techniques as described in a recent blog post: ‘Exploring Translation Log Statistics’. The C code generated is stored as dsmodel.c and dsmodelext*.c files (where * represents a whole number).

There are a number of different compiler options supported in Dymola. However, the C code is built depending on the selected compiler and the translation methods.

Figure 2. Compiler options on the Dymola > Simulation > Setup…> Compiler tab

Figure 2 shows different compiler options supported in Dymola. This includes Microsoft Visual Studio (VS), Intel Parallel Studio XE and MinGW GCC compilers (see Dymola User Manual Volume 1 (Dymola 2018 FD01) page 624). The C code can also be compiled and used with DDE or OPC embedded server. Alternatively, the Dymola model can be exported as a DLL with API option (see Section 6 of Dymola User Manual Volume 2). However, this option requires a Binary Model Export or Source Code Generation licence.

Dymola models can also be exported as FMUs by using the Translate toolbar on Dymola Simulation window as shown in Figure 3. Dymola Compilation

Figure 3. Translate tab pull down option on Dymola Simulation window.

Different compiling options use appropriate batch files to build the C code. These files are available in <Dymola installation directory>\bin:

build.bat – build commands for non-godess solvers with Visual Studio and Intel compilers

builddde.bat – build commands for models built with DDE embedded server

buildfmu.bat – build commands for FMU models, this will build the <model name>.dll and package it into an fmu

buildopc.bat – build commands for models built with OPC embedded server

dsbuild.bat – build commands for models compiled with MINGW

dsbuilddll.bat – build commands to generate DLL as an output

Dymmex.bat – used for building sFunction used by DymolaBlock in Simulink

Dymmex4c.bat – used for building sFunction used by DymolaBlock in Simulink with Matlab 4

Gccbuild.bat – build commands for models built with gcc

vgodbui.bat – build commands for godess solvers

When the build process is performed, an appropriate batch file(s) is called by Dymola based on the compiler option selected in the Simulation Setup in order to build the required application file(s).

On the one hand, if a Modelica model is translated (or a build process is executed), no detailed log of the commands that were used in the build process is displayed anywhere except a brief summary of this build process is stored in a buildlog.txt file. On the other hand, for viewing the commands used in the build process in detail, some modifications can be made to the appropriate build batch files. For this editing purpose, Notepad can be used. If you do not have editing permission, then modify these files as described in https://www.nibbleguru.com/67_remove-read-only-attribute-windows-10/.

An example using VS build.bat file is provided below; Dymola Compilation

*Before proceeding the following steps, it is highly recommended to create a backup copy of the ‘<Dymola installation directory>\bin\build.bat’ file in your preferred location.*

- Open the build.bat file available in <Dymola installation directory>\bin using a Notepad.
- In the first line change “echo off” to “echo on”.
- Add “echo on” after running the VS setup batch files are called (see Figure 4).
- Add a “pause” function to the end of this build file so that the cmd window stays open after the build is complete.

Figure 4. Original and modified VS build.bat files.

Now, please go through the following steps to see Dymola compilation processes in action;

- Open a Dymola window
- Select the Modelica.Blocks.Examples.PID_Controller model in the Dymola Package Browser
- Press
**Normal**pull-down option from the Translate tab on the Dymola Simulation window as shown in Figure 3.

Once the model is translated, Windows **cmd** will appear that may look similar to Figure 5. Dymola Compilation

Figure 5. Build commands in action when translating Modelica.Blocks.Examples.PID_Controller in Dymola.

Figure 5 displays a cropped version of commands used by Dymola during translation and compilation of the C code in Windows command line. This cmd will stay open until a key is pressed.

The build process will generate a number of different files in the current working directory depending upon the build option used. A few of them are given below:

dymosim.exe | Build generated when model is translated in Dymola or with the OPC server |

dymosim.dll | DLL generated when Export with DLL and DDE server are selected. (Please note: dymosim.exe is also present with the DDE build and is used to run the dymosim.dll). |

<model name>.fmu | FMU dll generated with FMU export option, this is packaged inside the <model name>.fmu file. |

<mex files> | the mex files generated by dymmex.bat and dymmex4c.bat depend on the Matlab installation. |

**Remember to revert to the original version of the build.bat file in your ‘<Dymola installation directory>\bin folder.**

Dymola Compilation Written by: Garron Fish – Chief Engineer

**Please get in touch if you have any questions or have got a topic in mind that you would like us to write about. You can submit your questions / topics via: Tech Blog Questions / Topic Suggestion**

The post The Dymola Compilation Process in Action appeared first on Claytex.

]]>The post Modelica-based Tic and Toc Functions in Dymola appeared first on Claytex.

]]>**Keywords: **Modelica, Tic, Toc, Function, Dymola, Model, Experimentation, Estimate, Elapsed, CPU, Time.

**Software/Tool/Language used**: Dymola 2018, MSL 3.2.2

Download a copy of this article as a pdf: Modelica based Tic & Toc Functions in Dymola

For developing a reasonably accurate and efficient Modelica model in Dymola, it is important that modellers perform a model experimentation with their model(s). In other words, a model in its developing stage must go through a series of simulations to ascertain an acceptable level of accuracy and efficiency. However, there is always a trade-off between fidelity and simulation speed of a created model. Among others, there are at least two methods that can be used to improve not only the accuracy but also the efficiency of a model. (1) Understand which part of the model is consuming highest elapsed computer processing unit (CPU) time during the simulation; by using this information one can improve the efficiency of the model. (2) Run the model multiple times with various input signals (e.g., a parametric sweep study); by which to attain a stable and/or accurate model. For the former, we can use Dymola built-in function called ‘CPUtime’ [1]. This function can be activated by selecting a tick box on the Simulation > Setup…> Translation tab whilst in the Dymola Simulation Window which is shown in Figure 1 below.

*Figure 1- Translation tab of the Simulation Setup dialog box in Dymola*

With the help of this Dymola built-in feature, the Dymola user is not only able to obtain a cumulative CPU time during simulation but also identify which part of the model has a lot of iteration (also known as an EventCounter). For the latter, it is quite convenient, if we can automate the model experimentation process using either a Modelica function or by calling a script in Dymola. A methodology for automating the experimentation of Modelica models using a Modelica function in Dymola is given in a previous blog article [2]. For a parametric sweep study, especially one provided in [2], it is valuable to estimate the total elapsed CPU time of the full iteration process. The Dymola User Guide Volume 1 and 2 [1, 3] and Modelica Standard Library (MSL) [4] do not provide information on functions/features to estimate the total elapsed CPU time of repeated model experimentations either by achieving this task using a Modelica function or by a Dymola script. Therefore, this blog article is aimed to present Modelica-based simple tic and toc functions and their implementation methods in Dymola.

The methodology of this blog article has three stages; they are as follows:

- Create Modelica-based simple tic and toc functions with the help of Modelica.Utilities.System.getTime function available in MSL.
- Step-up an experimental study adopted from a previous blog article, and modified to run an extended parametric sweep study.
- Use the created tic and toc functions in Step 1 with the extended parametric sweep study in Step 2 to demonstrate the aim of this blog article.

As aforementioned, as of the latest version of Dymola 2018, there is no function/feature to estimate total elapsed CPU time of a repeated or cycled experimentation of a Modelica model within Dymola. This section of the blog article begins by describing the getTime() function available in MSL. Followed by, guiding through a procedure to utilise this function to obtain some useful results. Then, processing these results, a step-by-step procedure to create Modelica-based tic and toc functions is also explained.

The Modelica.Utilities.System.getTime is a Modelica-based function available in MSL that can be used to get the local time at the time instant this function was called. Please follow the step-by-step procedure below to get some useful results by executing this function;

- By right-clicking the Modelica.Utilities.System.getTime in MSL, then selecting Call Function, a pop-up dialog box will open, which looks like the one shown in Figure 2.

*Figure 2- Dialog box of the Modelica.Utilities.System.getTime function in Dymola *

By executing the above function at an arbitrary instance of time, a result will be shown in the command log pane of Dymola Command Window. An example of which is given below;

= 966, 22, 28, 13, 4, 12, 2017

According to the Documentation layer of this function, the above results can be interpreted as

966, 22, 28, 13, 4, 12, 2017 = Dec. 4, 2017 at 13:28 after 22.966 s

Please note that the time (13: 28) interpreted from the above result is in 24-hour clock time.

For the sake of demonstration purposes, both tic and toc functions are made very simple. It is assumed for this example that a Modelica model experimentation study neither exceeds a day nor is conducted overnight, by which the date of the experiments does not change.

After taking the above assumptions into consideration, a simple Modelica-based tic function can be coded as shown below;

function tic

“Function to record the internal time just before the experiment starts in [s]”

output Modelica.SIunits.Time tic

“Record the internal time at the execution of this (tic) function”;

algorithm

(ms_tic,sec_tic,min_tic,hour_tic,day_tic,mon_tic,year_tic) :=

Modelica.Utilities.System.getTime();

tic := (ms_tic*0.001) + (sec_tic) + (min_tic*60) + (hour_tic*3600);

Modelica.Utilities.Streams.print(“tic = ” + String(tic) + ” [s]”);

end tic;

Using the above created function, one can record the internal clock time at the execution of this function just before the model experimentation starts.

By right-clicking the above function in Dymola Package Browser, the following dialog box will open;

*Figure 3- Dialog box of a simple ‘tic’ function.*

By executing the above tic function at an arbitrary time instant, get the following output:

AutomatedModelExperimentsWithTicToC.ElapsedTime.tic;

tic = 39992.5 [s]

= 39992.532

This sub-section describes how to create a simple toc function from the lesson learned from the previous sub-section. The toc function can be coded as shown below;

function toc

“Function to record the internal time just after the experiment ends in [s]”

output Modelica.SIunits.Time toc

“Record the internal time at the execution of this (toc) function”;

algorithm

(ms_toc,sec_toc,min_toc,hour_toc,day_toc,mon_toc,year_toc) :=

Modelica.Utilities.System.getTime();

toc := (ms_toc*0.001) + (sec_toc) + (min_toc*60) + (hour_toc*3600);

Modelica.Utilities.Streams.print(“toc = “ + String(toc) + ” [s]“);

end toc;

This created ‘toc’ function is a replica of ‘tic’ function presented in the last sub-section. In the ‘toc’ function however, the output variable names of the Modelica.Utilities.System.getTime and the annotations part are altered.

By calling the created ‘toc’ function from the Dymola Package Browser, a dialog box like the one shown below appears;

*Figure 4- Dialog box of a simple ‘toc’ function.*

Again, by arbitrarily executing the above ‘toc’ function after about 10 mins, we get the following output on Dymola Command Log Window:

AutomatedModelExperimentsWithTicToC.ElapsedTime.toc;

tic = 40567.1 [s]

= 40567.075

Finally, the elapsed time between execution of these two functions (tic and toc) can be calculated with a simple calculation result in units of seconds as below,

ElapsedTime = abs(toc-tic) = abs(40567.075 -39992.532) = 574.543s = 9.58 mins ~= 10 mins

For analysing the real benefits of these created functions, in the next section, a simple Modelica model experimentations example provided in a previous blog article [2] is adopted.

This section is only intended to cover a brief overview about a Modelica package adopted from [2] and experimentation setup to demonstrate the estimation of the total elapsed CPU time. For gaining more insight into how to automate Modelica model experimentations using a Modelica function in Dymola and the discussion about the physical meaning of the simulation results that can be obtained from the present study are beyond the scope of this article. So, those who are interested, please refer to [2, 5] for further details.

For performing an automated model experimentation task, a Modelica package (*AutomatedModelExperimentsWithTicToc*) is created. It has a simple RC circuit model (*ModularRC_Modified*), a modified automated Modelica model experimentation function (*ModelExperimentWithTicTocFn)*, these are basically adopted from [2], and a separate subpackage (ElapsedTime) with the newly created tic and toc functions show in the previous section of this blog article. This modified Modelica package can be downloaded from the bottom of this article.

The experimentation studies considered in this article are provided in Table 1. There are three case studies in Table 1. However, each case study iterates 161 times with different input excitation frequencies (Vin_freqHZ). So, one can argue that there are 483 experiments in total.

It is also important to note that both Case 2 and 3 are selected herein, only to emphasise the usefulness of the created functions/method (tic-toc/estimating total elapsed CPU time) and not indented to have any physical meaning.

Table 1: Experimentation studies

Case no. | ts [s] | Vin_v [V] | Vin_freqHz |

1 | 30 | 4.2 | 0:0.01:1.6 |

2 | 300 | 4.2 | 0:0.01:1.6 |

3 | 3000 | 4.2 | 0:0.01:1.6 |

In Table 1, ts, Vin_v and Vin_freqHZ are three input parameters defined in the *ModularRC_Modified* model in *AutomatedModelExperimentsWithTicToc package*. In Table 1, Case 1, the study includes a simple RC circuit model which is simulated with a sinusoidal input voltage of 4.2V and simulation time of 30s. The excitation frequency is iterated incrementally in steps of 0.01 Hz from 0 to 1.6 Hz. The results obtained from each (total of 161) iteration are stored in individual .mat files. By making appropriate adjustment to create plot setup section of *ModelExperimentWithTicTocFn*, one can plot the simulation results of interest using the already saved .mat file in Dymola. For knowing more details about how to plot results from saved .mat files, please refer to [2] and do not repeat here. Both Case 2 and 3 experiment studies are exactly the same as Case 1 and repeated manually, with changes in Simulation Stop Time (ts) of 300s and 3000s respectively.

The three different output results obtained by executing the ModelExperiment_ModifiedWithTicTocFn() on Dymola Command Log Window are provided below;

ElapsedCPUtime = 73.636 s

ElapsedCPUtime = 345.782 s

ElapsedCPUtime = 2644.21 s

These results are also plotted using a bar chart in Figure 5.

*Figure 5- Results obtained from the three cases in Table 1 using a bar chart.*

By looking at a bar chart in Figure 5 and comparing with Table 1, it is evident that by increasing the simulation time of the experimentation study, the total elapsed CPU time also increases. In Case 1, with a ts of 30s, the total elapsed CPU time for 161 iterations is 73.636s, whereas that of Case 2 (ts=300s) and Case 3(ts=3000s) took about 345.782s and 2644.21s respectively. From this experiment, the usefulness of the above created functions can be interpreted in two-ways. On the one hand, without the help of the created tic and toc functions, it is hard to sit with a stopwatch and record the simulation time manually, especially in Case 3 study. Imagine, if someone is carrying out an experimentation study which lasts for several hours (please do take care with limitations put on the created functions), it’s hardly feasible to estimate the total elapsed CPU time accurately. On the other hand, by combining Dymola built-in function, ‘CPUtime’ mentioned in the introduction section with tic and toc functions created in this article, one can develop an enhanced Modelica function or Dymola script to improve efficiency and/or accuracy of the model in a most systematic and automated manner. It should also be worth mentioning that the getTime() function has seven outputs (please refer to Figure 2), but only four of them are used in this article. By adopting the presented tic and toc functions and utilising all seven outputs from the getTime() function, one can create a general-purpose tic and toc functions in Dymola.

This article presented Modelica-based simple tic and toc functions in Dymola. With the aid of the getTime() function from MSL, the implementation procedure for how to create simple tic and toc functions in Dymola is demonstrated. By modifying an automated Modelica model experimentation example from a previous blog article and combining this with the newly created tic and toc functions, it allows discussing benefits of the tic and toc functions using the specific example in this article. The presented example shows that using the created functions, a Dymola user is not only able to easily estimate the total elapsed CPU time of automated model experimentations but also has a potential to improve the model efficiently by understanding the model behaviour clearly in a systematic and useful manner.

The Modelica package with model and functions used in this article can be downloaded here.

- Page no. 603
*, Dymola – Dynamic modelling laboratory, User Manual Volume 1*, version 2018, Copyright © Dassault Systèmes, 1992–2017, March 2017. - Raees B. K. Parambu,
*How to Automate Modelica Models Experimentation in Dymola,*http://www.claytex.com/blog/how-to-automate-modelica-models-experimentation-in-dymola/ . (05 Dec. 17, last accessed). *Dymola – Dynamic Modelling Laboratory, User Manual Volume 2*, version 2018, Copyright © Dassault Systèmes, 1992–2017, March 2017.*Modelica language specifications version 3.3 Revision 1*, Copyright © 1998–2014 Modelica Association July 11, 2014, https://www.modelica.org/documents (03 Oct. 17, last accessed).- Raees B. K. Parambu & S. Harrisons,
*A State-Space Model of a simple RC Network in Dymola & potential Applications**,*http://www.claytex.com/blog/a-state-space-model-of-a-simple-rc-network-in-dymola-potential-applications/*(*03 Oct. 17*, last accessed).*

**Written by: Raees B. K. Parambu — Systems (Project) Engineer**

**Please get in touch if you have any questions or have got a topic in mind that you would like us to write about. You can submit your questions / topics via: Tech Blog Questions / Topic Suggestion**

The post Modelica-based Tic and Toc Functions in Dymola appeared first on Claytex.

]]>The post Race Tech Magazine Feature Claytex – Late Model Dirt Racing appeared first on Claytex.

]]>**BIG GAINS WITHOUT A BIG BUDGET**

**For** years, top tier race teams have used various levels of simulation tools to help improve their racing programmes. From basic kinematics programmes through driver-in-the-loop motion platform simulators, these mathematical representations of their racecars have helped teams develop setups, design vehicles and optimise their performance.

Often, in levels of racing with budgets smaller than those in Formula 1, NASCAR, the World Rally Championship and IndyCar, team members are thirsty for knowledge and understanding but struggle to find high-quality simulation tools to quench that thirst.

Dirt Late Models are one type of racecar that fall into this category. While many of the teams have sizeable budgets, they are lower than that required to invest fully in an engineering group like those utilised in the ‘big budget’ forms of racing.

As a case study, a multi-body vehicle dynamics model of a Late Model Dirt car and related set of simulations were created to explore the level of usefulness of simulation to a few select teams. This set of simulation tools was built in Dymola, using the VeSyMA suite of Libraries from Claytex. The Dymola models were then encapsulated into an excel spreadsheet providing the team members with access to a familiar set of parameters and results to help them quickly assess the effect of changes. Once the basic model and Excel sheet was built, a few issues quickly became apparent. **Read more**

*To access the full issue of the magazine, subscribe here.*

If you have any questions or for more information, please do not hesitate to contact us.

Telephone: +44 1926 885900 — Email: sales@claytex.com

The post Race Tech Magazine Feature Claytex – Late Model Dirt Racing appeared first on Claytex.

]]>The post Dymola 2018 FD01 Available appeared first on Claytex.

]]>**Modelling and Simulation**

- Dymola is now only available in 64 bit version but it can still use both 32 and 64 bit C compilers
- A number of new free and commercial libraries
- Highlighting connections by clicking them
- More variables displayed in the parameter dialog such as input connectors with modifiers applied
- Parameters in the parameter dialog evaluated so you can see the actual value to be used when parameters are calculated from formula
- Support for customised setup file in Modelica script format
- Improved support for sparse linear algebra
- Displaying parameter values that change between simulations in the variable browser
- Synchronising the displayed values in the variable browser with the animation time
- New event logging user interface to aid debugging
- Plot window improvements
- FMU Export: Exporting model image with an FMU

**New**** Libraries**

Free Libraries

- FTire Interface Library, version 1.0
- Testing Library, version 1.0

Commercial Libraries

- ClaRa Plus Library, version 1.0.0, for modelling thermal power plants
- Fluid Power Library, version 2017.3, for modelling hydraulic systems
- Hydrogen Library, version 1.0, for modelling PEM fuel cell stacks
- Vehicle Demos Library, version 2017.3, example models combining multiple libraries

**Updated**** Libraries**

- Battery Library, version 2.0
- Cooling Library, version 1.2
- Dymola Commands Library, version 1.4
- Electrified Powertrains Library, version 1.2
- Human Comfort Library, version 2.4.0
- HVAC (Heating, Ventilation, and Air Conditioning) Library, version 2.4.0
- Thermal Systems Library, version 1.1.0
- VeSyMA (Vehicle Systems Modelling and Analysis) Library, version 2017.3
- VeSyMA – Engines Library, version 2017.3
- VeSyMA – Powertrain Library, version 2017.3
- VeSyMA – Suspensions Library, version 2017.3

The Claytex Libraries have been tested with Dymola 2018 FD01 and are available for download.

Customers with a valid support and maintenance agreement can download the new version of Dymola and the Claytex Libraries.

Please **contact Claytex** to obtain the download links.

If you have any questions, please don’t hesitate to contact our sales or support teams.

P: +44 1926 885900

Email: sales@claytex.com – support@claytex.com

The post Dymola 2018 FD01 Available appeared first on Claytex.

]]>The post Fluid connectors in Modelica Standard Library appeared first on Claytex.

]]>Figure 1: Fluid connectors in Modelica Standard Library

All the components from Modelica.Fluid can be connected using fluid ports. A flow leaving the connector has a negative sign, while a flow entering the connector has a positive sign (see figure 2).

Figure 2: Sign convention in Modelica Standard Library fluid connectors

Connecting the components directly via connectors leads to ideal mixing, which means that the connection point has the mixing temperature and pressure of the connected components. At the connection point, mass and energy balance are fulfilled.

Figure 3: Example of a connection point with ideal mixing and mass and energy balance

Figure 4 shows the fluid connector definition, containing the **medium** package, the pressure **p** (potential variable), the mass flow rate **m_flow** (flow variable), the specific enthalpy **h_outflow**, the mass fractions **X_outflow** and the substance fraction **C_outflow** (stream variables).

Figure 4: Modelica code for Modelica.Fluid.Interfaces.FluidPort.

In the fluid connector there are three stream variables (**h_outflow**, **Xi_outflow** and **C_outflow**) associated with the flow variable **m_flow**. These variables represent the specific enthalpy, the mass fractions and the concentrations associated to m_flow <0.

To better understand the difference between potential, flow and stream variables, let’s look at a simple connector example:

Let’s imagine we have three components C1, C2 and C3, each with the connector Demo. Connecting C1 to C2 and C1 to C3, the set of equations shown below in points 1 to 3 are automatically generated:

Figure 5: Meaning of connect(c1,c2) & connect(c1,c3);

**Potential variables are identical:**

c1.potentialVariable = c2.potentialVariable;

c1.potentialVariable = c3.potentialVariable;

2.** The sum of the flow variables is zero:**

c1.flowVariable + c2.flowVariable + c3.flowVariable=0;

3.** The sum of the product of flow variables and upstream stream variables is zero:**

c1.flowVariable*actualStream(c1.h_outflow) + c2.flowVariable*actualStream(c2.h_outflow) + c3.flowVariable*actualStream(c3.h_outflow)=0;

In fluid networks, point **1** above states that the pressure is the same in all the connected ports, point **2** is the mass balance and point **3** is the energy balance:

Let’s build a simple example using Modelica Standard Library models to understand the meaning of **h_outflow**, **inStream()**, **actualStream()**:

Figure 6: Simple example

Define the following parameters:

- inlet: p=2 bar, T=70 degC
- orifice: zeta=1, diameter=0,01 m
- outlet: p=1 bar, T=5 degC
- Medium in all the components: Modelica.Media.Water.StandardWater

Simulate using the default settings (stop time= 1s, algorithm: Dassl, tolerance: 0,0001)

Plot the enthalpy of the fluid in the inlet and outlet boundaries and from the enthalpy sensors and compare these values with the variables orifice.port_a.h_outflow and orifice.port_b.h_outflow:

Figure 7: Specific enthalpy values in the model shown in figure 6

The mass flow rate being positive, the enthalpy of the flow is the one defined by the inlet boundary:

specificEnthalpy.h_out=specificEnthalpy1.h_out=orifice.port_b.h_outflow=specificEnthalpy2.h_out=inlet.medium.h

orifice.port_a.h_outflow=outlet.medium.h defines the enthalpy that the flow would have if the mass flow rate was negative, flowing from right (outlet) to the left (inlet).

With the orifice being isenthalpic, the specific enthalpy of the flow remains constant and equal to the specific enthalpy of the inlet flow:

where

is the coefficient of thermal expansion at constant pressure.

Let’s now try with a mass flow rate that changes sign during the simulation:

Figure 8: Simple example with a mass flow rate that changes sign during the simulation

Simulate again:

Figure 9 shows that all the enthalpy sensors give the same enthalpy value, and that this value switches between the enthalpy defined by the inlet and outlet boundaries. **orifice.port_b.h_outflow=inlet.medium.h**, so it represents the enthalpy that the flow would have if it was always flowing from the inlet to the outlet. **orifice.port_a.h_outflow=outlet.medium.h** and represents the enthalpy that the flow would have if it was flowing from the outlet to the inlet.

Figure 9: Specific enthalpy values in the model shown in figure 8

When plotting **h_outflow** in the connector of a flow model (a component where the momentum balance is performed) one needs to keep in mind that that is not the enthalpy of the flow at the port! The enthalpy can be measured using enthalpy sensors or from the medium in the volumes (medium.h).

For example, the flow model **Modelica.Fluid.Fittings.SimpleGenericOrifice** that we have used in this simple example is an isenthalpic component (see the code in figure 10), however **orifice.port_a.h_outflow** is different from **orifice.port_b.h_outflow**.

Figure 10: Code in Modelica.Fluid.Fittings.SimpleGenericOrifice setting the isenthalpic transformation.

The quantity on the connector always corresponds to the value close to the connection point, assuming that the fluid is flowing out of the connector, regardless of the actual direction of the flow. This helps avoid singularities when the mass flow goes through zero.

The stream properties for the other flow direction can be inquired with the built-in operator inStream(…), while the value of the stream variable corresponding to the actual flow direction can be returned through the built-in operator actualStream(…).

When using the fluid connectors from Modelica Standard Library, one needs to be aware of a fundamental approximation: the kinetic pressure is neglected, so the momentum balance and the energy balance are only fulfilled if two ports of equal diameter are connected. However, in all circuits where friction dominates, or where components such as pumps determine the flow rate, the kinetic pressure is less important.

This blog post uses Modelica 3.2.2.

References:

M. Otter, F. Casella “Overview and Rationale for Modelica Stream Connectors”, January 27, 2009

**Written by: Maura Gallarotti – Fluids Modelling Engineer**

The post Fluid connectors in Modelica Standard Library appeared first on Claytex.

]]>The post Speed up creating your system models appeared first on Claytex.

]]>The following screenshots will illustrate the shortcuts one can take to speed up replication of objects and parameterisation throughout system models by using menu shortcuts.

The multibody 4-bar linkage system model that will be built is shown in Figure 1. It is made up from:

- 4x Modelica.Mechanics.MultiBody.Parts.BodyShape
- 2x Modelica.Mechanics.MultiBody.Joints.Revolute
- 1x Modelica.Mechanics.MultiBody.Joints.RevolutePlanarLoopConstraint
- 1x Modelica.Mechanics.MultiBody.Joints.Prismatic
- 1x Modelica.MechanicslMultiBody.World

Figure 1: Fully assembled and parameterised system model of a 4-bar linkage.

The axis of rotation of the 3 **revolutes** will be identical (**n={0,1,0}**). The dimensions and centres of mass for each **bodyShape** will be identical for each **bodyShape** object. With this in mind we proceed to drag a World object into our model (required in all systems using multibody objects), followed by an instance of **bodyShape **(see Figure 2).

Figure 2: Parameterisation of the first instance of **bodyShape**.

We can parameterise this single instance of the **bodyShape** object for **r**, **r_CM** and **m**. We now have other 3 instances of **bodyShape** to create in our system model. We could repeat the process of dragging and dropping and parameterising other 3 instances of **bodyShape** but this would be inefficient and time consuming. By selecting **bodyShape** in our system model and using **Ctrl+D** we can duplicate the instance and its parameterisation 3 times to give us the remaining 3 **bodyShape** objects we require, complete with the correct parameterisation (see Figure 3).

Figure 3: Duplication of **bodyShape** via the Ctrl+D shortcut.

Next, we need to rearrange the duplicated objects to achieve the architecture layout shown in Figure 1. To move the objects we can select them and by re-clicking on them and keeping the left mouse button pressed, drag them to a suitable location in the diagram layer. Two **bodyShape** objects will require rotation and we can do this by selecting the two objects and pressing **Ctrl+R **which is an alternative to navigating the Edit menu to locate the same operator (see Figure 4). Horizontal and Vertical flipping can be achieved by pressing **“H”** or **“V”** on the keyboard whilst the object is in a selected state.

Figure 4: Rotation of **bodyShape** via the Ctrl+R shortcut.

Now we can add the multibody joints (see Figure 5):

- 2x Modelica.Mechanics.MultiBody.Joints.Revolute
- 1x Modelica.Mechanics.MultiBody.Joints.RevolutePlanarLoopConstraint
- 1x Modelica.Mechanics.MultiBody.Joints.Prismatic

…and by selecting all 3 revolutes and right clicking to select “Parameters”, set all three revolutes to have an axis of rotation about the y-axis (**{0,1,0}**) in one operation (see Figure 6).

Figure 5: Parameterisation of multi-selected objects.

Figure 6: Parameterisation of multi-selected objects – GUI.

Because there is only one prismatic instance, we will simply select the prismatic and set the axis of movement to be **{1,0,0}**. In the World object, **n**, the direction gravity will be acting in, should be set to **{0,0,-1}**

Figure 7: Resulting animation

Shortcuts can vastly speed up the creation of system models in Dymola. The shortcuts used in this example are:

- Ctrl+D
- Ctrl+R
- H
- V

**Written by: Alessandro Picarelli – Chief Engineer**

**Please get in touch if you have any questions or have got a topic in mind that you would like us to write about. You can submit your questions / topics via: Tech Blog Questions / Topic Suggestion.**

The post Speed up creating your system models appeared first on Claytex.

]]>The post Introduction to the model translation and symbolic processing appeared first on Claytex.

]]>This blog entry describes some of the model translation process, focusing on the symbolic processing that is performed.

The symbolic processing of equations is applied to the complete set of equations for the model. This “flat” form of the Modelica model is extracted in the first step of the translation process, an example of a simple electrical model is shown in Figure 1.

Figure 1: Simple electrical circuit with Modelica code extracted

In the translation procedure this flat code is translated into procedural code that serves to facilitate function evaluations to be called as the software works through each time step. This process is summarised below (see Dymola User Manual Volume 2 Section 8.8 and Section 8.9 for a more detailed description of this process). The process however does not limit itself to extracting the equations and putting them in a procedural form.

From a model’s Modelica flat code (as in Figure 1) a matrix that describes the dependency of each equation on its variables & their derivatives (treated as further variables) is created. The matrix results from each equation being assigned a row and each variable being assigned a column. If an equation makes use of a certain variable then the relevant entry is assigned the value 1 (for example in Figure 2). The only possible values for entries are zero, and unity. This matrix is referred to as the “Structure Jacobian”.

Figure 2: “Structure Jacobian” for a mechanical system. Each row is an equation and each column is a variable.

Image from Dymola User Manual Volume 2.

The “Structure Jacobian” describes the dependency of the equations on the variables; the name “Structure Jacobian” is misleading as it is not a Jacobian, see note at end of post for further details.

The aim is to rearrange the “Structure Jacobian” so that working downwards, each term can be solved for. This rearrangement essentially represents the automated writing of instructions for the computer.

To improve the computational efficiency of the solver, the system of equations is simplified as much as possible. Two simplification methods are applied, with a view to removing constants and “alias” (essentially “duplicate”) variables by substituting at translation.

Firstly, from examining the “Structure Jacobian” it is possible to determine which variables are really constants. This automates the process a person might use to spot that some “variables” for a particular set of boundary conditions or in a particular model configuration, do not vary in time, simplifying the specific solution of the system for that set of parameters & initial conditions. Some software would waste time “calculating” these variables at each time-step. This doesn’t necessarily take long, but it adds up, and blocks up spaces in the memory, which for large systems is very damaging. Dymola avoids it.

Secondly, by examining rows in the “Structure Jacobian” that contain only two variables it is possible to determine which variables may be alias or the negated alias (i.e. b = a or c = -a). The alias variables are removed, for example in Figure 3. This automates the process a person might use to spot quantities that are identically equal, so they don’t end up solving for the same thing twice, needlessly increasing the work. By doing this algorithmically, Dymola lets it happen for potentially hundreds of thousands of equations, so that problems can use the computational speed & efficiency of a computer, while not losing the common-sense of a person.

Figure 3: “Structure Jacobian” example with alias equations removed. The number of unknowns is reduced from about 1200 to 330. Image from Dymola User Manual Volume 2.

A significant reduction in complexity is typically achieved by alias reduction.

**DAE to ODE**

The Modelica flat code can describe a mixed system of Differential-Algebraic Equations (DAEs – https://en.wikipedia.org/wiki/Differential_algebraic_equation). However DAE solvers are typically slow and not robust with regards to initialisation, so the system is generally transformed into a set of Ordinary Differential Equations (ODEs), to take advantage of a wider variety of numerical solvers.

This transformation is called Index Reduction and a key part of this process is selection of states. The process followed by Dymola supports “dynamic states”, and is described in https://www.modelica.org/events/workshop2000/proceedings/old/Mattsson.pdf. This means that the variables that are considered states in the resulting set of ODEs can be selected dynamically during simulation.

The term “state” is used in state-space modelling, and in principle means “variables chosen to be the coordinates”. For example, let’s imagine you are calculating some dynamics in cartesian space, and then you notice it would be easier or better to use polar coordinates. By changing to doing the equations in a new set of coordinates you are changing the chosen “states” that (fully) describe the configuration of the dynamical system (consider looking at http://web.mit.edu/2.14/www/Handouts/StateSpace.pdf or similar material on state-space modelling).

When Dymola uses * static* states, Dymola takes a system where the cartesian and polar coordinates are both defined, and chooses which set of variables (polar or cartesian) should be used as the coordinates, and which should just be back-calculated after the fact. This can have a huge effect on the computational efficiency, and is a powerful capability that aids analysis.

The use of* dynamic* states means that Dymola not only chooses states at the beginning, but continues to re-evaluate whether it should stick to the initial choice, or change, during the analysis! This is similar to how you might solve a motion problem piecemeal, with cartesian coordinates for one part, then switch to polar for another segment which lends itself better to that.

Note that dynamic state selection is typically turned off & requires careful management by a skilled user. Discussion of how these can be used for MultiBody systems can be found here: **Understanding State Selection in Multibody Simulation**.

In the “ideal” case the Structure Jacobian can be rearranged into a Lower Triangular Matrix. Variables can then be solved for one by one. * In general, this is not the case however, and “algebraic loops”* (i.e. “coupled equations”) are present in the model. In this case, the Structure Jacobian cannot be restructured as a Lower Triangular Matrix but can be made to approach that state, laid out as in the example in Figure 4.

Figure 4: “structure” Jacobian restructured as Block Lower Triangular Matrix

The blocks along the diagonal of the BLT structure represent algebraic loops. These “algebraic loops” are two-way coupled sets of equations, possibly, but not necessarily, differential equations, requiring simultaneous solution. These could be either of systems of linear equations or systems with some nonlinear equations. The key point to note is that the distinct “blocks” that can be identified, have been isolated in the arrangement of Figure 4.

Separating these blocks, using algebra, already makes the problem more tractable, particularly if one or more of the isolated blocks requires the application of iterative nonlinear solvers. This is because it is much easier if these computationally expensive solvers are only applied to the blocks of equations that need them, and as piecemeal as possible. For example, looking at Figure 4, applying the nonlinear solver to the blocks shown, instead of the whole diagram would be faster. Applying the solver to each block identified in turn, instead of all at once, will be even faster, so the machine doing this algebra ahead of time can really pay off.

The linear system of differential equations has the form shown below. Note that the software will reduce higher order systems to this “first order” form, by creating the requisite additional equations in the same way as is documented in the typical elementary undergraduate differential equation courses provided to engineers.

**Ax **=** b
**

In this equation, the terms of **x** may well be derivatives of other terms.

An example of a linear system derived from a basic transformer is in Figure 5.

Figure 5: Basic transformer based on Modelica.Electrical.Analog.Examples.CompareTransformers. The alias variables and constants are not shown. The Solve function calculates the solution for der(transformer.i1) and der(transformer.i2) for the given A and b matrices.

In Figure 5 the linear system of equations are restructured into the **Ax = b** form and **x** is solved for using the Dymola Solve function.

A nonlinear system of differential equations has the following form:

**fn**(**x**) =** 0**

where the function **fn**() has nonlinear characteristics.

This system of equations is solved using a root finding method similar to the Newton-Raphson method (a modified Powell Hybrid method is used). This method iteratively updates **x** (the iterative variables) based on the gradient of **fn**(**x**) until **fn**(**x**) converges on **0 **(i.e. the residuals converge to zero).** **

The gradient of **fn**(**x**) is the Jacobian matrix (as entirely distinct, conceptually, from the “Structure Jacobian” discussed above):

Figure 6: Jacobian matrix

In the Newton-Raphson method the following update equation is used:

This equation describes how the inverse of the Jacobian matrix is used to update the iterative variables (refer to http://fourier.eng.hmc.edu/e176/lectures/NM/node21.html for more detail), a similar method is used in Dymola.

An example of a nonlinear system of differential equations is in Figure 7. The nonlinear characteristics due to the discontinuity in the saturating inductor.

Figure 7: Model of saturating Inductance driven by sine wave voltage. The Jacobian is calculated symbolically and is used in an iterative process to solve for Inductance.Lact and Inductance.i (the iterative process is not show).

The iterative process for finding the solution of the nonlinear equations uses the Jacobian matrix of the nonlinear system. Often this Jacobian matrix is calculated symbolically during symbolic processing (as in Figure 7). However sometimes the Jacobian cannot be symbolically calculated by the translation process, in this case the Jacobian matrix is calculated numerically using the forward difference method (see http://www.iue.tuwien.ac.at/phd/khalil/node14.html for more details). This calculation is obviously repeated at each evaluation of the function.

Evaluation of a numerical Jacobian is computationally expensive and the resulting derivative can suffer from noise and inaccuracies.

Depending on the kind of problem & its local behaviour, a numerical derivative can be considerably less satisfactory than a value from a closed-form expression too. If possible, the need for numerical evaluation of derivatives should be avoided (see http://www.claytex.com/blog/how-can-i-make-my-models-run-faster/ and Dymola User Manual Volume 2 Section 8.9 for further details). Take note, that avoiding numerical differentiation while converging nonlinear solutions, can be seen as one key reason to use Dymola software!

Algebraic loops are coupled systems of equations (whether linear or not) which are relatively computationally intensive. There are a number of methods that reduce the number of such coupled systems in the model. Firstly the process of converting the “Structure Jacobian” to the BLT ODE matrix uses efficient graph theory algorithms to select * states* that generate minimal algebraic loops. This is essentially an automated exploration for appropriate “changes of variable” (see above “Dynamic States”) – you are already familiar with the idea of transformations that decouple equations, and this is the same idea.

Some small linear algebraic loops can be solved symbolically.

Tearing is used to reduce the size of algebraic loops. This method can be seen as breaking an algebraic loop by removing the algebraic connection between the output of the system and the input as in Figure 8 below and compensating, by *constraining* the resulting system such that x2 must equal NEWx2. This is essentially a procedure for iterative solution, particularly likely to be used on coupled systems (called “loops” in the interface, as discussed) which have some nonlinear properties. On coupled sets of equations for which tearing is deployed by the software, iteration variables (called “tearing variables”) are selected intelligently, and a process of converging iterations is undertaken.

Figure 8: Tearing of algebraic loops diagram. Red line is where the f1 and f2 functions are torn

Tearing the model as in Figure 8, allows the remaining equations to be simplified further. See http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.571.9335&rep=rep1&type=pdf for more details.

Other methods for reducing the number of nonlinear systems are (See Section 8.9 of Dymola User Manual Volume 2):

- For scalar nonlinear equations applying inverses functions can sometimes be used to solve the equation analytically.
- Use of general solutions for certain classes of algebraic equations (like polynomials).
- Partitioning of a system of equations into a linear and a nonlinear part can reduce the demands of the nonlinear part.
- Using min and max values to evaluate if-conditions.

Figure 9: Size of algebraic loops is reduced by using tearing

Figure 10: A model’s Translation tab in Simulation log of a vehicle model

During the translation process the Simulation log’s translation tab is generated that contains information about symbolic processing that took place.

The Translation log is split into different sections, as in Figure 10, these are:

- A warnings and information section – A number of useful warnings, information and possibly errors.
- A Statistics section – See the next section
- A Settings section – Settings used in the model
- Selected continuous state time states – States selected by the model, or sets from which dynamic states can be selected from
- Warnings regarding initial values of iteration variables – Solutions for nonlinear equations can sometimes be difficult or slow to find. To improve robustness and efficiency of your model you should supply suitable start values for these variables. If no initial value is supplied for a variable, a warning is generated and the initial value is set to zero.

Figure 11, below, contains the statistics of a vehicle model that is under development.

Figure 11: An example of the translation log statistics expanded out

An explanation of the Statistics in Figure 11 follows:

In the **Original Model** section the following information is provided:

**Number of components**– the number of declared components in the model**Variables**– the number of individual variables in the model**Constants**/**Parameters**/**Unknowns**– the number of variables divided by whether they are declared as**constant**,**parameter**, or time-varying**Differentiated variables**– the number of variables for which a**der(x)**statement appears in the model**Equations**/**Nontrivial**– the number of equations, and the number of this that are “non-trivial” – equations that are “trivial” are usually those generated by connect statements

In the **Translated Model** section the following information is provided:

**Constants**– are constants in the model including those determined during symbolic processing – compare this figure with the number of constants declared in the model**Free parameters**– are parameters that can be altered between simulations without re-translation**Parameter depending**– are parameters dependent on other parameters**Outputs**– outputs of the model**Continuous time states**– states present in the model – this gives an indication of the overall size of model, compare this figure with the number of differentiated variables**Time-varying variables**– variables that vary with time, this includes the number of states**Alias variables**– variables equal to time varying-variables or states, or the negation of these**Assumed default initial conditions**– this is the number of variables for which the “start” value is not fixed**Number of mixed/discrete systems of equations**– the number of linear or nonlinear systems of equations that also include discrete variables**Sizes of linear systems of equations**– the linear systems of equations that are determined by the BLT partitioning**Sizes after manipulation of the linear systems**– the linear system are reduced using the methods summarised in “Reduction of algebraic loops”**Sizes of nonlinear systems of equations**– the nonlinear systems of equations that are determined by the BLT partitioning**Sizes after manipulation of the nonlinear systems**– the nonlinear systems of equations are reduced using the methods summarised in “Reduction of algebraic loops”**Number of numerical Jacobians**– is the number of nonlinear systems that require a numerical Jacobians to be calculated

In Modelica models there are **initial equation** and **initial algorithm** sections that can be used to provide characteristics to the initialisation problem, these equations are used together with the system’s equations to characterise the Initialisation system of equations. The **Initialisation problem **describes the system of initialisation equations and uses the same terminology as used in the **Translated model** section.

Future blog posts will give further tips on how to understand more about your model using these statistics.

Please take note, that the use of the term “Structure Jacobian” in this blog post, is included to remain consistent with the terminology used by the developers & the manual, however the “Structure Jacobian” concept is not as immediately related to the usual meaning of the term “Jacobian” which will also be used further on, as one might think, and the term is used for reasons beyond the current scope. If it helps, simply read “Structure Array”.

Mathematicians usually use “Jacobian” to mean: *The matrix of first-order partial derivatives of a vector function* or in other words, a kind of generalised first order derivative that applies to vector functions.

**Please get in touch if you have any questions or have got a topic in mind that you would like us to write about. You can submit your questions / topics via: Tech Blog Questions / Topic Suggestion.**

The post Introduction to the model translation and symbolic processing appeared first on Claytex.

]]>The post Investigating the applications to the inverseBlockConstraints component appeared first on Claytex.

]]>The **inverseBlockConstraints** block can be found in **Modelica.Blocks.Math**. It allows to invert the input(s) and output(s) of a model whilst maintaining the plant model identical. This is possible because Dymola supports acausal modelling with extensive support of the Modelica language. The symbolic manipulation Dymola performs prior to running a model allows the model equations to be automatically rearranged into a form where a solution can be calculated in relation to the boundary conditions and model paramterisation imposed.

Let’s have a look at a few examples of applications of **inverseBlockConstraints**:

Example 1: As an alternative to a PID.

PID are frequently used control components but they require parameter tuning.

Figure 1: Model of an inertia controlled by a torque actuator.

Above is a simple model of a torque source rotating an inertia, a PID is used to reach our desired speed.

The results are as follows:

Figure 2: Required torque and speed profile.

An alternative to using a PID is to use the inverseBlockConstraints block.

Figure 3: Same model as in figure 1, without the PID.

The results:

Figure 4: Input torque and speed profile.

Example 2: To invert a table.

Let’s consider the example of a 2D table for the sake of simplicity (it would also work with 3D tables).

Figure 5: Simple 2D table where y=u1*u2.

The output of the table is the product of the two inputs.

With u1 = 0.3 and u2 = 3, we can check that the table output is 0.9:

Figure 6: Table output.

In the case when we know one input and we know what output we want, we can use the inverseBlockConstraints block to find what the value of the second input needs to be.

Figure 7: Let’s find the value of the missing input.

We can check that the value of the second input is calculated in the correct way:

Figure 8: The value is correct!

This can be useful in cases when the table of data received from the manufacturer is not in the same format as in the model (i.e. speed=f(torque) instead of torque=f(speed) for example).

This model has to be used with caution since it can generate non-linearities. However, it can be useful to get a sense of what the input of a model should be and can later be replaced by a more physical control model.

The post Investigating the applications to the inverseBlockConstraints component appeared first on Claytex.

]]>