Archived OpenModelica forums. Posting is disabled.

Alternative forums include GitHub discussions or StackOverflow (make sure to read the Stack Overflow rules; you need to have well-formed questions)


Forgot password? | Forgot username? | Register

Monte Carlos Simulation

Monte Carlos Simulation

Hi, I was recently trying to simulate some given dynamics with random initial conditions. For instance, I have some dynamics x1' = -a*x1+x2, x2' = -b*x2+u, u' = -c*u. I want to simulate them to see plots to illustrate how it converges with 100 random initial conditions. I know how to construct model, but I don't know how to deal with multiple initial condition. Does anyone have any idea?

Re: Monte Carlos Simulation

You can generate a Model.exe executable from your model then use -iif=file_with_initial_conditions.mat to run with different initial variables
https://openmodelica.org/doc/OpenModeli … imflag-iif
https://openmodelica.org/doc/OpenModeli … flags.html

I would do this in python or some other programming language (you can also use OpenModelica with mos files, see for example:
https://openmodelica.org/forum/default- … ter-sweep)

Basically you should generate N initialX.mat files with random values (i guess you could use python to do that) then call your model with that input.

Code:


Model.exe -iif=initial1.mat -r output1.mat
Model.exe -iif=initial2.mat -r output2.mat
...
Model.exe -iif=initialN.mat -r outputN.mat

Then just plot output*.mat on the same plot.

Another way would be to use setComponentModifierValue(className, componentName.modifierName, $Code(expression));
Write something like this in a script.mos file

Code:


loadFile("Model.mo"); getErrorString();

for i in 1:100 loop
  // set a random start value to the component you want
  // change these here to what you need
  setComponentModifierValue(ModelName, componentName.modifierName, $Code(randomExpression));
  // compile the model
  buildModel(Model);
  // run the model and generate the output into an unique mat file.
  system("./Model -r=output_file_" + String(i) + ".mat");
end for;

then just run omc script.mos where Model.mo file is.

You can also use OMPython to do this, see for example this paper:
https://www.ep.liu.se/ecp/142/103/ecp17142103.pdf

Re: Monte Carlos Simulation

That is really helpful! Thank you so much!

There are 0 guests and 0 other users also viewing this topic
You are here: