Feeding initial states to a FMU block (FMIKit) in MATLAB - matlab

I am using Dymola 2020x to develop a thermal model and export the FMU to Simulink to simulate controllers.
For implementing advanced controllers, I require an iteratively run framework, which helps to initialize the states after every iteration to the values at end of every previous simulation. This can be done within Dymola through “import initial” and “Continue” commands in the Simulation tab of Dymola.
However, since I am designing the controller in MATLAB, I require a similar feature for that platform. The only way I know right now is to manually change the initial conditions in the FMU block, but since I have a lot of states, it would not be feasible to do it manually. Any scripting ideas are welcome as well.
All in all, I require a framework/method to be able to initialize states of my model through MATLAB/Simulink to the values I get after running a single iteration.
Some help would be appreciated.

Expose the initial conditions of the variables as parameters, and set them from MATLA Scripts with e.g.
FMIKit.setStartValue(gcb, 'step', 'true')
see https://github.com/CATIA-Systems/FMIKit-Simulink/blob/master/docs/fmu_import.md

Related

Use the result values from previous simulation result as guess values for next simulation in Dymola

Initialization could be very cumbersome and easily lead to divergence. A simple strategy is to run the simulation when building a part of the whole system and use the simulation results to modify guess values.
Here is what I got in the PPT from Francesco Casella and the book from Daniel Bouskela.
I found that I could use an option in Dymola as follows, but instead of using the initialization result, I wanna use the result when reaching a steady state. So I'd like to use a python script to extract the result from the .mat result file, then modify the iteration variables automatically. But the key problem is that I don't know when I add more components in my model, the iteration variable set of existing components would change, I don't know what kind of effect would this causes.
Anyone got opinion on this issue, welcome to answer this question.
So my question is where should I find the python
You can use the end values (= steady state) of the simulation result in order to create a new initialization (Dymola Manual 1, section 2.5.12) . If the component names are the same in the sub system model and the total model, you can run the script created in the subsystem model on the larger system model as well. But you have to check if your models have initial equations that hinder an initialization from the outside (see section 4.2 in https://2012.international.conference.modelica.org/proceedings/html/pdf/ecp12076927_KruegerMehlhaseSchmitz.pdf)
It should also be possible to initialize it steady state. Instead of providing initial values for a state x and fixing it, you can provide initial equations for the derivatives such as der(x) = 0;
With that setup activate Save Initial Results and you should be good to go.

I want to run two or more simulink model in parallel and synchronisation.

Hi I want to run two or more simulink model in parallel and synchronisation. is there any way to do it? One way I think is by creating a subsystem and put all models inside it. It should run parallely. This one is not prefered for me. I want to open two matlab instances and run two different model in synchronisation. is this possible? I want to do it programmatically. Any help is appreciable.
You should use a matlab script and implement the synchronization logic in it.
== Update ==
You can execute the simulink model by simply calling it from a Matlab Script.
You have to define a task containing the next steps: First you can calculate inputs in Matlab. Then execute the first model with the first inputs. Then save the results to a certain variable. Finally use that variable on the second model and launch second model simulation.
Repeat the task for all the necessary steps.
If you have the Instrument Control Toolbox, you can send/receive data between the two models via TCP/IP or UDP/IP blocks. No need to have two MATLAB sessions, this can be done from one MATLAB session, see this loopback example.
However, I would query the need to have two separate models. Why not put both models in the same model as subsystems, or even as Model blocks if you want to keep the atomic nature of each sub-model?
The best way to run parallel simulink simulations is probably the parsim command. Their is a complete article on the Mathworks website explaining how to do it:
Run Parallel Simulations

Why does my Simulink-Model rebuild at every iteration?

I'am trying to speedup my simulink project and want to use the Accelerator-Simulation mode.
The aim of my project is to control a cyclic process and is structured as followes:
matlab-script, where all parameters and a feedforward control with
parameter estimation is implemented. Also it starts simulating the
simulink model for each iteration.
simulink model, where the dynamic system and the feedforward control (basically a lookup-table) together with a feedback control
is implemented. Parameters of all blocks are set by workspace variables/structs generated by the script.
The feedforward control variable is calculated and parameter are estimated from the simulated data after every simulation pass. Then the model is simulated again. The model is not changing during the iterations, but still it is compiling at every cycle. From the first: Is this solution appropriate for using the Accelerator mode?
I tried to follow theses proposed steps to determine, why it is built at every iteration: mathworks
If i run it with the Accelerator-Mode (referring to the documentation of this function, it now compiles for simulation), I still cannot reproduce why it is compiled at every iteration.
csdet1.ContentsChecksum.Value ~= csdet2.ContentsChecksum.Value
is true, but the proposed code does not find any details.
csdet1.InterfaceChecksum.Value ~= csdet2.InterfaceChecksum.Value
is also true, the proposed code outputs that
UserDefinedTypesChecksum
is different. What does that mean and how can I resolve this?
Sidefact: When I run Simulink.BlockDiagram.getChecksum() with the Model opened in Simulink and Normal-Mode chosen, I get this error:
Continuous update specified for this chart chartname This is not
supported for RTW."
But this chart is a Matlab-Function block, not a stateflow chart?!

Co-Simulation with Simulink: stepwise execution and interchange of parameters with external application

I have to realise a coupled simulation with Simulink and an external application (LS-DYNA). The leading simulation is done in Simulink, where I want to implement a function block as following:
The interaction is done using the cmd of windows, so the Simulink block should do the following:
function [ x,y ] = ExternalSimlation( u,v )
% open the windows cmd and run the external simulation by passing u and v
[status,cmdout] = system( 'command for executing the external simulation -u -v');
function [ x,y ] = readcmd( cmdout )
%algorithm to evaluate the cmd output
end
[x,y] = readcmd(cmdout);
end
The exact code should NOT be relevant here. My question is, how can I implement the interface into the simulink model? Can I just use one of the custom function blocks, use my code above, and it will work? But which one, I don't really see the difference.
OR, my other idea was to build something like the following:
And then use a while-loop like this:
while ... do
[u,v] = sim('model', 'x',x,'y', y, 'some option just to run a single step');
[x,y] = ExternalSimlation( u,v )
[u,v] = sim('model' .... next step ...)
to execute the simulink simulations step-by-step. How can I realise that? (The rest of the simulation contains complex control algorithms, derivations and integrations)
I don't have experiences in writing batch files, but that seems possible for me as well.
If you wonder why I'm not just testing things out, it's because I don't have the external application available (I just know how the in- and output works) and don't want to waste time in coding a substitutional application just for testing, if it's not possible at all.
Any hints and experiences in coupled simulations with simulink are highly appreciated!
Thank you!
As far as I know the "proper" way to couple simulink to other applications would be to write
S-Functions. If the external application has a C/C++ interface this should also by far be the best solution performance-wise:
http://www.mathworks.de/de/help/simulink/create-cc-s-functions.html
The question pertains to the co-simulation mechanisms of Simulink.
i suggest http://www.mathworks.in/help/matlab/calling-external-functions.html
as a first step.
And to compare and understand the implementations of existing software's solution this manual should help.
http://vector.com/portal/medien/cmc/application_notes/AN-IND-1-007_Using_MATLAB_with_CANoe.pdf
To start with , basically all the co-simulation softwares i have worked with uses COM interfaces from windows.(i have not worked matlab in any other OS) They create objects and uses shared memory for data transmissions.And basically it is through S-functions they achieve them.
Also you can consider code generation from simulink or stateflow and writing a wrapper for external applications.

Initialization of a Dymola FMU in Simulink

I have encountered an issue while trying to simulate a model using an fmu file in Simulink:
I am using the Modelon FMI toolbox for a Dymola/Simulink interface to import a Model-Exchange type fmu file (version 1.0) into the Simulink model. I have a Matlab m-file that programmatically simulates the model sequentially, saving the final internal states of the model for initialization in the next simulation. The first iteration of the simulation runs without errors, but on the second iteration, Matlab returns the following errors at the call for the simulation:
module = partial_run_sim2/BasicModels.System_model_final_Sim, log
level = ERROR: [][FMU status:Error] fmiInitialize: dsblock_ failed,
QiErr = 1
module = partial_run_sim2/BasicModels.System_model_final_Sim, log level =
ERROR: [][FMU status:Error] Possible errors (non-exhaustive): 1. The
license file was not found. Use the environment variable
"DYMOLA_RUNTIME_LICENSE" to specify your Dymola license file. 2. The
model references external data that is not present on the target
machine, at least not with the same location. Error reported by
S-function 'sfun_fmu_me_1_0' in 'partial_run_sim2/BasicModels.System_model_final_Sim': fmiInitialize
returned with an error in initialize_fmu_model_first_time. See the
Command Window for more information printed by the FMU model.
I know that my licenses for Dymola and the FMI toolbox are up-to-date.
The simulation call in the m-file is:
simOut_itr = sim(model, model_cs);
Where “model” is the Simulink .slx model file and “model_cs” is a Simulink Configuration Setting variable. I have set the Configuration such that the model loads initial states from the workspace, and I have saved the previous iterations final states to that workspace variable. This action occurs for the first iteration as well, though the initial states are the same as the default initial states in the fmu file. I suspect that the first iteration runs without issue because the initialization is the same as the default value, but the subsequent iteration has a different initialization value, which does not agree with the fmu block.
I am aware of the ability to simulate the fmu file in Matlab using the fmi functions, but these methods do not allow for as much transparency into the system states, which hinders the sequential simulation. I am open to any methods that allow this kind of simulation, however.
Any suggestions with regard to initializing the system states in fmu files in Matlab/Simulink are much appreciated. Thank you.
I think I have encountered this error before, but not with the FMI Toolbox.
I had issues initializing a Dymola generated FMU more than once in a for-loop very similar to what you described above with the output of one initialization as the input for the next.
Give some random (but reasonably good values) and initialize the model just once such that the initialization is not the same as the default value.
If this works, then in all likelihood, the problem might be in multiple-initializations. Perhaps, you can unload the model at the end of each initialization and then load it again at the beginning of the each loop?
If nothing works, perhaps u can use JModelica.org (open source platform from Modelon) to get the output of these initializations into a mat-file and then use it in MATLAB for subsequent work. I know this is not ideal, but might save you some time while you wait for some answers here.