Error using the library Modelica_LinearSystems2 in OpenModelica - modelica

I am trying to use the Kalman Filter from the Modelica_LinearSystem2 Library (Modelica_LinearSystems2.WorkInProgress.Controller.KalmanFilter.KF) in OpenModelica, but it seems the functions of the library are not working properly in my test models.
To find the problem I copied the code example from the documentation (https://build.openmodelica.org/Documentation/Modelica_LinearSystems2.StateSpace.%27constructor%27.fromABCDMatrices.html)
model test3
Real A[1,1] = [1];
Real B[1,1] = [1];
Real C[1,1] = [1];
Real D[1,1] = [0];
public
Modelica_LinearSystems2.StateSpace ss;
algorithm
ss := Modelica_LinearSystems2.StateSpace.'constructor'.fromABCDMatrices(A, B, C, D);
equation
end test3;
When I click on check model I receive the Error:
[Modelica_LinearSystems2.StateSpace: 7:3-8:68]: Failed to deduce dimension 1 of A due to missing binding equation.
This refers to the line
Real A[:,size(A, 1)];
When I predefine this (and other) matrices with for example
Real A[4,4];
I get the error
Internal error Instantiation of test3 failed with no error message.
My question is: Why is this and how can I prevent these errors?

Findings
It looks like Modelica_LinearSystems2 is only supported by Dymola. The landing page of their github repository states:
Please note that the library is known to work with Dymola only.
It looks as this is still the case. At least on my machine the library Modelica_LinearSystems2 v2.4.1 has serious issues in OpenModelica v1.18.0. Most examples exit with errors or do nothing.
Still, the code in the question does not work in Dymola. Below you find an explanation and corrected examples, which were successfully tested with Dymola. The fundamental problem should be the same in all tools and I hope my solution will also work in OpenModelica once it support the Modelica_LinearSystems2 library.
Original answer (most relevant for Dymola users)
The problem with your example code is that Modelica tools must know the size of vectors, matrices and arrays when a simulation is performed, but not when a function is called. Since you are building a model, the tool assumes that you want to simulate it.
Your code instantiates the StateSpace record ss. ss holds the matrices A, B, C and D. As long as you don't assign anything to ss, their sizes are not known. Of course there is an algorithm, which sets ss, but this happens during simulation. During translation, the size of the matrices in ss cannot be determined. Therefore, a typical Modelica tool requires you to use a binding equation.
To make your snipped work, you can change it to this:
model Demo
Real A[1,1] = [1];
Real B[1,1] = [1];
Real C[1,1] = [1];
Real D[1,1] = [0];
Modelica_LinearSystems2.StateSpace ss = Modelica_LinearSystems2.StateSpace.'constructor'.fromABCDMatrices(A, B, C, D);
end Demo;
Note that ss now has a binding equation. Hence, the size of the matrices inside ss can be determined.
The question is, if you really want to run a simulation with your StateSpace record. Typically, the functions in the liner systems library are used in Modelica functions. In this case your code could look as follows:
function demo
output Modelica_LinearSystems2.StateSpace ss;
protected
Real A[1,1] = [1];
Real B[1,1] = [1];
Real C[1,1] = [1];
Real D[1,1] = [0];
algorithm
ss = Modelica_LinearSystems2.StateSpace.'constructor'.fromABCDMatrices(A, B, C, D);
end demo;
I suggest looking at the various examples in the package Modelica_LinearSystems2.Examples.StateSpace for the correct usage of the StateSpace record.

Related

fmincon: Problem with the optimization of the MPC

I try to use an economic MPC for urban traffic (modelled as a state space system), to control the intersection's light.
I use fmincon for the optimization.
When I simulate it, I find that the fmincon runs more than one time for every sample time: for the first sample time, fmincon runs 32 times, the control value changes and Matlab shows me this message:
Initial point is a local minimum that satisfies the constraints.
Optimization completed because at the initial point, the objective function is non-decreasing in feasible directions to within the default value of the optimality tolerance, and constraints are satisfied to within the default value of the constraint tolerance.
stopping criteria details
After that, fmincon runs 2 times, the control value stays the same with the same matlab message.
Can I limit this run's number?
OK, you mixed-up a couple of topics:
MPC That stands for model predictive control, which is a control technique that solves an optimization problem at every sample point for a defined future horizon (by this it determines the control law implicitly, so you don't need to do the nasty pole-placement in Laplacian-space).
Anyway, you use fmincon to solve this optimization problem. If you go for runtime (so if it is a real-controller and not just a simulation) this is a bad choice since you have just a (potentially constrained but) linear optimization problem (state-space representation as you noted). Have a look here at Matlab doc on how to choose the ideal algorithm. For real implementations, I suggest to use the open-source library NLopt, which provides a nice Matlab interface and typically runs faster.
fmincon Now to your actual question: can one limit the calls of the objective function in fmincon? (Note that your term "run" is confusing as this refers to the starting of the optimization... as one would to over and over again in MPC. But you wanted to say "call of the objective function" as I guess)
The answer is yes.
opts = optimoptions('fmincon','MaxFunctionEvaluations',100);
[x,fval,exitflag] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,opts)
Without code, it is hard to follow your specific problem, but the message (and probalb the exitflag) tells you that either your initial value or your objective-function sucks. fmincon doesn't find a direction in your parameter space, in which it can step for decreasing the value of your objective-function. The number of function-calls when it raisis this warning depends on the number of parameters length(x0) as the algorithm first needs wiggle a little at all parameters in all directions...
Thank you very much #max for your help and all this suggestion and information. About the controller, I use a real time simulation software with Matlab.
About the MPC, I use a non linear model, you can find the description here: https://www.sciencedirect.com/science/article/pii/S0968090X12000150
You're right about "call of the objective function", it's not "run".
I test the option that you suggest, the simulation is the same (same messages, same situation) I think that the problem is related with the number of "call of the objective function" for every sample time, not the number of the use of fmincon at all the simulation.
Your find below the function that I use for fmincon:
function u = solve(Np,x0,u0,Nu,q,ii)
u0 = [0];
Cycletime= 20/3600;
A = [];
b = [];
Aeq = [];
beq = [];
lb = [];
ub = [];
lbx = [];
ubx = [];
lbu = [];
ubu = [];
lx = 0;
ux = 386;
lu = 0;
uu = Cycletime;
lbx = [lbx, lx];
ubx = [ubx, ux];
lbu = [lbu lu];
ubu = [ubu uu];
lb = [lbu ;lbx];
ub = [ubu ;ubx];
% Solve optimization problem
u = fmincon(#(u)costfunction1(x0,u,Nu,Np,q,ii), u0, A, b, Aeq, beq, lb,ub) ;
end

What is the difference between check a model and tranlate a model in Dymola

I am using Dymola, but I am not sure about the difference between check a model and translate a model.
So I did a test.
Here is the code of the connector and the model file
connector Port
flow Real Q;
Real P;
Real T;
end Port;
model Inlet
parameter Real Q = 1;
parameter Real P = 2;
parameter Real T = 3;
Port a;
equation
a.Q = Q;
a.P = P;
a.T = T;
end Inlet;
If I check the model, Dymola would generate a .mof file:
model lab.Inlet
parameter Real Q = 1;
parameter Real P = 2;
parameter Real T = 3;
Real a.Q;
Real a.P;
Real a.T;
// Equations and algorithms
// Component
// class lab.Inlet
equation
a.Q = Q;
a.P = P;
a.T = T;
end lab.Inlet;
If I translate the model, the .mof file is like the following:
model lab.Inlet
parameter Real Q = 1;
parameter Real P = 2;
parameter Real T = 3;
Real a.Q;
Real a.P;
Real a.T;
// Equations and algorithms
// Component
// class lab.Inlet
equation
a.Q = Q;
a.P = P;
a.T = T;
a.Q = 0.0;
end lab.Inlet;
I could see that in the .mof file generated by translation there is one more line: a.Q = 0.0;.
So, my question is what is the detailed difference between check and translation? Is there a detailed document for this topic?
Checking a model should just create a small intermediate model that can be checked for logical errors (#eqs == #unknowns, etc.) but is not used for symbolic manipulations afterwards.
Instantiating a model should create a flat model that can be used for symbolic manipulations.
Translating a model should first run instantiation and afterwards perform symbolic manipulations (BLT, etc.) and actually create simulation code.
OpenModelica kind of does it this way, i can't for sure tell what dymola does, but i guess this gives you an idea. I don't know if there is any further documented explanation for this.
Adding to the other answer.
TL:DR;
Check normally assumes the model will be a sub-component of a larger model.
Translates is intended for running the model, i.e. the model should be complete in itself.
Longer version:
For "Check" the component is normally checked assuming a generic connection to the connector a (in general generic connections to all connectors). That connection will add one equation, and thus there will be one equation too many in this model - but we don't know exactly which one.
There are also some additional checks for instantiation, but normally missing modifiers (parameter values and redeclarations of partial models) is seen as a non-issue - since it is not a complete model.
For "Translate" it is assumed that you are translating a complete model, and non-causal connectors such as a will be default-connected, i.e. flows set to zero - which gives the specific error message you see. (And public top-level inputs would be read from dsu.txt.) Additionally the model is translated to C-code, which requires a bit more.
Normally "Check" stops before "Translate" by e.g., not solving systems of equations as indicated in the other answer.
However, in recent versions of Dymola if the model has "experiment" annotation a "Check" will also check that (it is assumed you are checking a complete model) - ignoring the normally above.
Recent versions of Dymola will also report issues for the connector Port:
The connector is not balanced, it has 1 flow variables and 2
non-causal non-flow variables (including possible over-determined
ones).
For "Check" that will be a problem for some models, as Dymola has to add 1 or 2 equations per Port-connector.

Reduce number of output variables in OpenModelica

My model is currently roughly 2000 equations, and the simulation period is a couple of weeks. I'm using the OpenModelica Connection Editor.
The problem I'm facing is the huge amount of output variables, and I've had the plot window crash a couple of times.
The question is, therefore, how can I reduce the number of output variables?
I'm only really interested in 20-50 of them. I'm aware that I can remove parameter output by making them protected, but I haven't been able to locate any similar tricks for variables.
If you are simulating the model via command line then take a look at variableFilter argument of simulate command https://build.openmodelica.org/Documentation/OpenModelica.Scripting.simulate.html.
If you are using OMEdit then Simulation->Simulation Setup->Output->Variable Filter (Optional)
Actually, protected isn't limited to parameters. Here's an example duplicating Modelica.Mechanics.Translational.Examples.SignConvention and protecting everything but mass1
Tested in Dymola 2017FD01 with pedantic mode (so it should work in OpenModelica as well); it works fine, and gives only mass1 parameters and variables in the simulation results
model SignConvention "Examples for the used sign conventions."
extends Modelica.Icons.Example;
Modelica.Mechanics.Translational.Components.Mass mass1(
L=1,
s(fixed=true),
v(fixed=true),
m=1) a;
protected
Modelica.Mechanics.Translational.Sources.Force force1
a;
Modelica.Blocks.Sources.Constant constant1(k=1) a;
Modelica.Mechanics.Translational.Components.Mass mass2(
L=1,
s(fixed=true),
v(fixed=true),
m=1) a;
Modelica.Mechanics.Translational.Sources.Force force2
a;
Modelica.Blocks.Sources.Constant constant2(k=1) a;
Modelica.Mechanics.Translational.Components.Mass mass3(
L=1,
s(fixed=true),
v(fixed=true),
m=1) a;
Modelica.Mechanics.Translational.Sources.Force force3(useSupport=true)
a;
Modelica.Blocks.Sources.Constant constant3(k=1) a;
Modelica.Mechanics.Translational.Components.Fixed fixed
a;
equation
...

MATLAB: Vectorize for loop in MATLAB

I wanted to vectorize this piece of code. Is it possible to do this? I tried finding a solution, but I was not able to find any good result on google.
for pos=length1+1:length
X1(pos) = sim(net1, [demandPred(pos), demand(pos-1), X1(pos-1), X1(pos-2)]')';
X2(pos) = sim(net1, [demandPred(pos), demand(pos-1), X2(pos-1), X2(pos-2)]')';
end
Thanks in advance. :)
Edit 1:
The model which I am going to simulate is a simple GRNN.
net1 = newgrnn([demand(169:trainElem), demand(169-1:trainElem-1), X1(169 - 1:trainElem - 1), X1(169 - 2:trainElem - 2)]', 0.09);
Can Simulink models be vectorized? Sometimes.
Can your Simulink model be vectorised? It's impossible to tell without seeing the model -- and how it is being called from m-code (as you've shown in your question) is no indication.
An example of vectorization would be: consider a model with signal s1 that gets added to constant K, and assume that you need to run the models for different values if K. You could use a loop (like the m-code you show) and run the model for each individual required value for K. Alternatively, you can make K a vector, in which case all values would get added to s1 and the result would be a vector of signals s1+K(1), s1+K(2),..., s1+K(n), and the model only needs to be executed once for all of these summations to occur.
But, whether that sort of thing can be done in your model cannot be determined without seeing the model.

Using coupled system of PDEs in modelica

Just few questions, i hope someone will find time to answer :).
What if we have COUPLED model example: system of n indepedent variables X and n nonlinear partial differential equations PDEf(X,PDEf(X)) with respect to TIME that depends of X,PDEf(X)(partial differential equation depending of variables X ). Can you give some advice? Here is one example:
Let’s say that c is output, or desired variable. Let’s say that r is independent variable.Partial differential equation looks like:
∂c/∂t=D*1/r+∂c/∂r+2(D* (∂^2 c)/(∂r^2 ))
D=constant
r=0:0.1:Rp- Matlab syntaxis, how to represent same in Modelica (I use integrator,but didn't work)?
Here is a code (does not work):
model PDEtest
/* Boundary conditions
1. delta(c)/delta(r)=0 for r=0
2. delta(c)/delta(r)=-j*d for r=Rp*/
parameter Real Rp=88*1e-3; // length
parameter Real initialConc=1000;
parameter Real Dp=1e-14;
parameter Integer np=10; // num. of points
Real cp[np](start=fill(initialConc,np));
Modelica.Blocks.Continuous.Integrator r(k=1); // independent x1
Real j;
protected
parameter Real dr=Rp/np;
parameter Real ts= 0.01; // for using when loop (sample(0,ts) )
algorithm
j:=sin(time); // this should be indepedent variable like x2
r.u:=dr;
while r.y<=Rp loop
for i in 2:np-1 loop
der(cp[i]):=2*Dp/r.y+(cp[i]-cp[i-1])/dr+2*(Dp*(cp[i+1]-2*cp[i]+cp[i-1])/dr^2);
end for;
if r.y==Rp then
cp[np]:=-j*Dp;
end if;
cp[1]:=if time >=0 then initialConc else initialConc;
end while;
annotation (uses(Modelica(version="3.2")));
end PDEtest;
Here are more questions:
This code don’t work in OpenModelica 1.8.1, also don’t work in Dymola 2013demo. How can we have continuos function of variable c, not array of functions ?
Can we place values of array cp in combiTable? And how?
If instead “algorithm” stay “equation” code can’t be succesfull checked.Why? In OpenModelica, error is :could not flattening model :S.
Is there any simplified way to use a set of equation (PDE’s) that are coupled? I know for PDEs library in Modelica, but I think they are complicated. I want to write a function for solving PDE and call these function in “main model”, so that output of function be continuos function of “c”.I don’t know what for doing with array of functions.
Can you give me advice how to understand Modelica language, if we “speak” like in Matlab? For example: Values of independent variable r,we can specife in Matlab, like r=0:TimeStep:Rp…How to do same in Modelica? And please explain me how section “equation” works, is there similarity with Matlab, and is there necessary sequancial approach?
Cheers :)
It's hard to answer your question, since you assuming that Modelica ~ Matlab, but that's not the case. So I won't comment your code, since it's really wrong. Let me give you an example model to the burger equation. Maybe you could use it as starting point.
model burgereqn
Real u[N+2](start=u0);
parameter Real h = 1/(N+1);
parameter Integer N = 10;
parameter Real v = 234;
parameter Real Pi = 3.14159265358979;
parameter Real u0[N+2]={((sin(2*Pi*x[i]))+0.5*sin(Pi*x[i])) for i in 1:N+2};
parameter Real x[N+2] = { h*i for i in 1:N+2};
equation
der(u[1]) = 0;
for i in 2:N+1 loop
der(u[i]) = - ((u[i+1]^2-u[i-1]^2)/(4*(x[i+1]-x[i-1])))
+ (v/(x[i+1]-x[i-1])^2)*(u[i+1]-2*u[i]+u[i+1]);
end for;
der(u[N+2]) = 0;
end burgereqn;
Your further questions:
cp is an continuous variable and the array is representing
every discretization point.
Why you should want to do that, as far as I understand cp is
your desired solution variable.
You should try to use almost always equation section
algorithm sections are usually used in functions. I'm pretty
sure you can represent your desire behaviour with equations.
I don't know that library, but the hard thing on a pde is the
discretization and the solving it self. You may run into issues
while solving the pde with a modelica tool, since usually
a Modelica tool has no specialized solving algorithm for pdes.
Please consider for that question further references. You could
start with Modelica.org.