Including a causal relation in a Modelica simulation leads to translation Error while flattening model - modelica

I want to simulate a controller for a mass-spring model which works based on energy:
model model
//parameters
parameter Real m = 1;
parameter Real k = 1;
parameter Real Fmax = 3;
parameter Real x0 = 1;
parameter Real x1 = 2;
parameter Real t1 = 1;
//variables
Real x, v, a, xy, vm;
initial equation
x = x0;
v = 2;
equation
v = der(x);
a = der(v);
m * a + k * x = F;
algorithm
vm := sign(xy - x)*sqrt(2 * (Fmax * abs(xy - x) + k * (xy^2 - x^2) / 2) / m);
// step signal
if time < t1 then
xy := x0;
else
xy := x1;
end if;
if xy == x then
F := k * x;
else
F := sign(vm - v) * Fmax;
end if;
end model;
But it leads to the error message:
Translation Error
Error occurred while flattening model
I would appreciate it if you could help me know what is the problem and how I can fix it.
P.S.1. SIMULINK is also not able to finish!
P.S.2. New version of the code can be seen here.
P.S.3. According to this discussion on Discord, the algorithm section was not really meant for casual relations. More information about the keyword is here.

Related

Generating two random time depedant veariables with different sample periods

Following this question, I'm trying to generate two time-dependent random functions omega1 and tau using this example. The difference is that I need to have two different sample periods of 0.05 and 0.17 for omega1 and tau respectively. I just duplicated the parts I thought would do the job:
model testData
extends Modelica.Icons.Example;
import Modelica.Math.Random.Generators;
import Modelica.Math.Random.Utilities;
parameter Real k = 50.0;
parameter Real J = 0.001;
Real theta1;
Real theta2;
Real omega2;
parameter Modelica.SIunits.Period samplePeriod1 = 0.05;
parameter Integer globalSeed1 = 30020;
parameter Integer localSeed1 = 614657;
output Real omega1;
parameter Modelica.SIunits.Period samplePeriod2 = 0.17;
parameter Integer globalSeed2 = 30020;
parameter Integer localSeed2 = 614657;
output Real tau;
protected
discrete Integer state1024[33](each start=0, each fixed = true);
algorithm
when initial() then
state1024 := Generators.Xorshift1024star.initialState(localSeed1, globalSeed1);
omega1 := 0;
elsewhen sample(0, samplePeriod1) then
(omega1, state1024) := Generators.Xorshift1024star.random(pre(state1024));
omega1 := (omega1 - 0.5) * 13;
end when;
when initial() then
state1024 := Generators.Xorshift1024star.initialState(localSeed2, globalSeed2);
omega1 := 0;
elsewhen sample(0, samplePeriod2) then
(tau, state1024) := Generators.Xorshift1024star.random(pre(state1024));
tau := (tau - 0.5) * 3;
end when;
public
parameter Integer id1 = Utilities.initializeImpureRandom(globalSeed1);
discrete Real rImpure1;
Integer iImpure1;
parameter Integer id2 = Utilities.initializeImpureRandom(globalSeed2);
discrete Real rImpure2;
Integer iImpure2;
algorithm
when initial() then
rImpure1 := 0;
iImpure1 := 0;
elsewhen sample(0, samplePeriod1) then
rImpure1 := Utilities.impureRandom(id=id1);
iImpure1 := Utilities.impureRandomInteger(
id=id1,
imin=-1234,
imax=2345);
end when;
when initial() then
rImpure2 := 0;
iImpure2 := 0;
elsewhen sample(0, samplePeriod2) then
rImpure2 := Utilities.impureRandom(id=id2);
iImpure2 := Utilities.impureRandomInteger(
id=id2,
imin=-1234,
imax=2345);
end when;
initial equation
theta1 = 0;
theta2 = 0;
der(theta2) = 0;
equation
der(theta1) = omega1;
der(theta2) = omega2;
J * der(omega2) = tau + k * (theta1 - theta2);
annotation(experiment(StartTime = 0, StopTime = 10, Tolerance = 1e-6, Interval = 0.02));
end testData;
however I get the error messages:
Symbolic Error
The given system is mixed-determined. [index > 3]
Please checkout the option "--maxMixedDeterminedIndex".
Translation Error
No system for the symbolic initialization was generated
I would appreciate if you could help me know what is the problem and how I can solve it.
P.S. considering that this code is apparantly compiling fine on Dymola, this could be a problem with OpenModelica. So I'm adding th JModelica tag in the case those guys can help me know if this compiles over there or not.
You have omega1 := 0; in two when initial()statements. Replace it by tau := 0; in the second one and the example will work.
I recommend to cleanup your code a bit. I found various smaller issues and needless code lines.
everything related to the impure random numbers can be removed
localSeed2 and globalSeed2 are useless when they are initialized like the other seed variables
state1024 is initialized at 3 different places (even though it works with OpenModelica): with start values and fixed=true and in two different when initial() statements
omega2 and tau2 don't need to be outputs. The Tool determines by itself what it has to compute.
And finally: Modelica models are a lot easier to debug and understand if existing blocks and physical components are used instead of writing lengthy code in a single class. Your model can also be built graphically with blocks from Modelica.Blocks.Noise and components from Modelica.Mechanics.Rotational.
Below is an updated version of your code with units, only one section for initialization and removed algorithm section (not necessary anymore due to the additional variables rand_omega and rand_tau).
model testData2
extends Modelica.Icons.Example;
import Modelica.Math.Random.Generators;
import Modelica.Math.Random.Utilities;
import SI = Modelica.SIunits;
parameter SI.RotationalSpringConstant k = 50.0;
parameter SI.Inertia J = 0.001;
parameter SI.Period samplePeriod_tau = 0.17;
parameter SI.Period samplePeriod_omega = 0.05;
parameter Integer globalSeed = 30020;
parameter Integer localSeed_tau = 614657;
parameter Integer localSeed_omega = 45613;
SI.Angle theta1, theta2;
SI.AngularVelocity omega1, omega2, rand_omega;
SI.Torque tau, rand_tau;
protected
discrete Integer state1024_tau[33];
discrete Integer state1024_omega[33];
initial equation
state1024_omega = Generators.Xorshift1024star.initialState(localSeed_omega, globalSeed);
state1024_tau = Generators.Xorshift1024star.initialState(localSeed_tau, globalSeed);
theta1 = 0;
theta2 = 0;
der(theta2) = 0;
equation
when sample(0, samplePeriod_omega) then
(rand_omega, state1024_omega) = Generators.Xorshift1024star.random(pre(state1024_omega));
end when;
when sample(0, samplePeriod_tau) then
(rand_tau, state1024_tau) = Generators.Xorshift1024star.random(pre(state1024_tau));
end when;
der(theta1) = omega1;
der(theta2) = omega2;
omega1 = (rand_omega - 0.5) * 13;
tau = (rand_tau - 0.5) * 3;
J * der(omega2) = 0 + k * (theta1 - theta2);
annotation(experiment(StartTime = 0, StopTime = 10, Tolerance = 1e-6, Interval = 0.02));
end testData2;

OpenModelica complains about a negative value which can't be negative

Following this question I have modified the energy based controller which I have described here to avoid negative values inside the sqrt:
model Model
//constants
parameter Real m = 1;
parameter Real k = 2;
parameter Real Fmax = 3;
parameter Real x0 = 1;
parameter Real x1 = 2;
parameter Real t1 = 5;
parameter Real v0 = -2;
//variables
Real x, v, a, xy, F, vm, K;
initial equation
x = x0;
v = v0;
equation
v = der(x);
a = der(v);
m * a + k * x = F;
algorithm
if time < t1 then
xy := x0;
else
xy := x1;
end if;
K := Fmax * abs(xy - x) + k * (xy^2 - x^2) / 2;
if abs(xy - x) < 1e-6 then
F := k * x;
else
if K > 0 then
vm := sign(xy - x) * sqrt(2 * K / m);
F := Fmax * sign(vm - v);
else
F := Fmax * sign(x - xy);
end if;
end if;
annotation(
experiment(StartTime = 0, StopTime = 20, Tolerance = 1e-06, Interval = 0.001),
__OpenModelica_simulationFlags(lv = "LOG_STATS", outputFormat = "mat", s = "euler"));
end Model;
However, it keeps giving me the error:
The following assertion has been violated at time 7.170000
Model error: Argument of sqrt(K / m) was -1.77973e-005 should be >= 0
Integrator attempt to handle a problem with a called assert.
The following assertion has been violated at time 7.169500
Model error: Argument of sqrt(K / m) was -6.5459e-006 should be >= 0
model terminate | Simulation terminated by an assert at the time: 7.1695
STATISTICS 
Simulation process failed. Exited with code -1.
I would appreciate if you could help me know what is the problem and how I can solve it.
The code you created does event localization to find out when the condition in the if-statements becomes true and/or false. During this search it is possible that the expression in the square-root becomes negative although you 'avoided' it with the if-statement.
Try reading this and to apply the solution presented there. Spoiler: It basically comes down to adding a noEvent() statement for you Boolean condition...

How to solve for the upper limit of an integral using Newton's method?

I want to write a program that makes use of Newtons Method:
To estimate the x of this integral:
Where X is the total distance.
I have functions to calculate the Time it takes to arrive at a certain distance by using the trapezoid method for numerical integration. Without using trapz.
function T = time_to_destination(x, route, n)
h=(x-0)/n;
dx = 0:h:x;
y = (1./(velocity(dx,route)));
Xk = dx(2:end)-dx(1:end-1);
Yk = y(2:end)+y(1:end-1);
T = 0.5*sum(Xk.*Yk);
end
and it fetches its values for velocity, through ppval of a cubic spline interpolation between a set of data points. Where extrapolated values should not be fetcheable.
function [v] = velocity(x, route)
load(route);
if all(x >= distance_km(1))==1 & all(x <= distance_km(end))==1
estimation = spline(distance_km, speed_kmph);
v = ppval(estimation, x);
else
error('Bad input, please choose a new value')
end
end
Plot of the velocity spline if that's interesting to you evaluated at:
dx= 1:0.1:65
Now I want to write a function that can solve for distance travelled after a certain given time, using newton's method without fzero / fsolve . But I have no idea how to solve for the upper bound of a integral.
According to the fundamental theorem of calculus I suppose the derivative of the integral is the function inside the integral, which is what I've tried to recreate as Time_to_destination / (1/velocity)
I added the constant I want to solve for to time to destination so its
(Time_to_destination - (input time)) / (1/velocity)
Not sure if I'm doing that right.
EDIT: Rewrote my code, works better now but my stopcondition for Newton Raphson doesnt seem to converge to zero. I also tried to implement the error from the trapezoid integration ( ET ) but not sure if I should bother implementing that yet. Also find the route file in the bottom.
Stop condition and error calculation of Newton's Method:
Error estimation of trapezoid:
Function x = distance(T, route)
n=180
route='test.mat'
dGuess1 = 50;
dDistance = T;
i = 1;
condition = inf;
while condition >= 1e-4 && 300 >= i
i = i + 1 ;
dGuess2 = dGuess1 - (((time_to_destination(dGuess1, route,n))-dDistance)/(1/(velocity(dGuess1, route))))
if i >= 2
ET =(time_to_destination(dGuess1, route, n/2) - time_to_destination(dGuess1, route, n))/3;
condition = abs(dGuess2 - dGuess1)+ abs(ET);
end
dGuess1 = dGuess2;
end
x = dGuess2
Route file: https://drive.google.com/open?id=18GBhlkh5ZND1Ejh0Muyt1aMyK4E2XL3C
Observe that the Newton-Raphson method determines the roots of the function. I.e. you need to have a function f(x) such that f(x)=0 at the desired solution.
In this case you can define f as
f(x) = Time(x) - t
where t is the desired time. Then by the second fundamental theorem of calculus
f'(x) = 1/Velocity(x)
With these functions defined the implementation becomes quite straightforward!
First, we define a simple Newton-Raphson function which takes anonymous functions as arguments (f and f') as well as an initial guess x0.
function x = newton_method(f, df, x0)
MAX_ITER = 100;
EPSILON = 1e-5;
x = x0;
fx = f(x);
iter = 0;
while abs(fx) > EPSILON && iter <= MAX_ITER
x = x - fx / df(x);
fx = f(x);
iter = iter + 1;
end
end
Then we can invoke our function as follows
t_given = 0.3; % e.g. we want to determine distance after 0.3 hours.
n = 180;
route = 'test.mat';
f = #(x) time_to_destination(x, route, n) - t_given;
df = #(x) 1/velocity(x, route);
distance_guess = 50;
distance = newton_method(f, df, distance_guess);
Result
>> distance
distance = 25.5877
Also, I rewrote your time_to_destination and velocity functions as follows. This version of time_to_destination uses all the available data to make a more accurate estimate of the integral. Using these functions the method seems to converge faster.
function t = time_to_destination(x, d, v)
% x is scalar value of destination distance
% d and v are arrays containing measured distance and velocity
% Assumes d is strictly increasing and d(1) <= x <= d(end)
idx = d < x;
if ~any(idx)
t = 0;
return;
end
v1 = interp1(d, v, x);
t = trapz([d(idx); x], 1./[v(idx); v1]);
end
function v = velocity(x, d, v)
v = interp1(d, v, x);
end
Using these new functions requires that the definitions of the anonymous functions are changed slightly.
t_given = 0.3; % e.g. we want to determine distance after 0.3 hours.
load('test.mat');
f = #(x) time_to_destination(x, distance_km, speed_kmph) - t_given;
df = #(x) 1/velocity(x, distance_km, speed_kmph);
distance_guess = 50;
distance = newton_method(f, df, distance_guess);
Because the integral is estimated more accurately the solution is slightly different
>> distance
distance = 25.7771
Edit
The updated stopping condition can be implemented as a slight modification to the newton_method function. We shouldn't expect the trapezoid rule error to go to zero so I omit that.
function x = newton_method(f, df, x0)
MAX_ITER = 100;
TOL = 1e-5;
x = x0;
iter = 0;
dx = inf;
while dx > TOL && iter <= MAX_ITER
x_prev = x;
x = x - f(x) / df(x);
dx = abs(x - x_prev);
iter = iter + 1;
end
end
To check our answer we can plot the time vs. distance and make sure our estimate falls on the curve.
...
distance = newton_method(f, df, distance_guess);
load('test.mat');
t = zeros(size(distance_km));
for idx = 1:numel(distance_km)
t(idx) = time_to_destination(distance_km(idx), distance_km, speed_kmph);
end
plot(t, distance_km); hold on;
plot([t(1) t(end)], [distance distance], 'r');
plot([t_given t_given], [distance_km(1) distance_km(end)], 'r');
xlabel('time');
ylabel('distance');
axis tight;
One of the main issues with my code was that n was too low, the error of the trapezoidal sum, estimation of my integral, was too high for the newton raphson method to converge to a very small number.
Here was my final code for this problem:
function x = distance(T, route)
load(route)
n=10e6;
x = mean(distance_km);
i = 1;
maxiter=100;
tol= 5e-4;
condition=inf
fx = #(x) time_to_destination(x, route,n);
dfx = #(x) 1./velocity(x, route);
while condition > tol && i <= maxiter
i = i + 1 ;
Guess2 = x - ((fx(x) - T)/(dfx(x)))
condition = abs(Guess2 - x)
x = Guess2;
end
end

Abstract switch in Modelica

I would like to motivate a question I asked before about a Modelica array of partial model. Consider the following model of a switch between 2 controllers.
model Switch
input Real u;
input Integer sel;
output Real y;
protected
Real x;
equation
if sel == 1 then
y = 0.1 * (0 - u);
der(x) = 0;
else
y = 0.1 * (0 - u) + 0.2 * x;
der(x) = 0 - u;
end if;
end Switch;
Let's ignore the fact that the PI controller may break when it is not selected for some time due to divergence of x. This can be fixed by resetting x when the PI controller is selected. However, this is not the point here.
I want to abstract this switch in 2 ways. Firstly, to switch among a parametric number of controllers. Secondly, to abstract controllers using partial models. Let Ctrl be the partial model of a controller.
partial model Ctrl
input Real u;
output Real y;
end Ctrl;
We can instantiate the two controllers embedded in the switch as follows.
model P extends Ctrl;
equation
y = 0.1 * (0 - u);
end P;
model PI extends Ctrl;
protected
Real x;
equation
y = 0.1 * (0 - u) + 0.2 * x;
der(x) = 0 - u;
end PI;
The abstract version of the switch is supposed to be something like:
model Switch
parameter Integer N(min=1);
Ctrl c[N];
input Real u;
input Integer sel(min=1, max=N);
output Real y;
equation
for i in 1:N loop
c[i].u = u;
end for;
y = c[sel].y;
end Switch;
However, this model has some problems. Firstly, it is not clear how this model can be instantiated, e.g. with one P and one PI controller. Secondly, I get a warning which surprises me, namely: The following input lacks a binding equation: c[1].u
Is it possible to do express this abstract switch in Modelica in some way?
This doesn't work with an array of models as you cannot bind it to different models via a modification. You need to specify all the controllers you have inside the GenericSwitch. You could generate the GenericSwitch and Switch model automatically if needed.
partial model Ctrl
input Real u;
output Real y;
end Ctrl;
model P
extends Ctrl;
equation
y = 0.1 * (0 - u);
end P;
model PI
extends Ctrl;
protected
Real x;
equation
y = 0.1 * (0 - u) + 0.2 * x;
der(x) = 0 - u;
end PI;
model GenericSwitch
replaceable model MyCtrl1 = Ctrl;
replaceable model MyCtrl2 = Ctrl;
MyCtrl1 c1(u = u);
MyCtrl2 c2(u = u);
input Real u;
input Integer sel;
output Real y;
equation
y = if sel == 1 then c1.y else c2.y;
end GenericSwitch;
model Switch = GenericSwitch(
redeclare model MyCtrl1 = P,
redeclare model MyCtrl2 = PI);
I guess it should work with something like:
model GenericSwitch
parameter Integer N(min=1);
replaceable model MyCtlr = Ctrl constrainedby Ctrl;
MyCtlr c[N](each u = u);
input Real u;
input Integer sel(min=1, max=N);
output Real y;
equation
y = c[sel].y;
end GenericSwitch;
model PSwitch = GenericSwitch(redeclare model MyCtrl = P);
model PISwitch = GenericSwitch(redeclare model MyCtrl = PI);

Matlab solving ODE applied to State Space System, inputs time dependent

I've got at State System, with "forced" inputs at bounds. My SS equation is: zp = A*z * B. (A is a square matrix, and B colunm)
If B is a step (along the time of experience), there is no problem, because I can use
tevent = 2;
tmax= 5*tevent;
n =100;
dT = n/tmax;
t = linspace(0,tmax,n);
u0 = 1 * ones(size(z'));
B = zeros(nz,n);
B(1,1)= utop(1)';
A = eye(nz,nz);
[tt,u]=ode23('SS',t,u0);
and SS is:
function zp = SS(t,z)
global A B
zp = A*z + B;
end
My problem is when I applied a slop, So B will be time dependent.
utop_init= 20;
utop_final = 50;
utop(1)=utop_init;
utop(tevent * dT)=utop_final;
for k = 2: tevent*dT -1
utop(k) = utop(k-1) +(( utop(tevent * dT) - utop(1))/(tevent * dT));
end
for k = (tevent * dT) +1 :(tmax*dT)
utop(k) = utop(k-1);
end
global A B
B = zeros(nz,1);
B(1,1:n) = utop(:)';
A = eye(nz,nz);
I wrote a new equation (to trying to solve), the problem, but I can't adjust "time step", and I don't get a u with 22x100 (which is the objective).
for k = 2 : n
u=solveSS(t,k,u0);
end
SolveSS has the code:
function [ u ] = solveSS( t,k,u0)
tspan = [t(k-1) t(k)];
[t,u] = ode15s(#SS,tspan,u0);
function zp = SS(t,z)
global A B
zp = A*z + B(:,k-1);
end
end
I hope that you can help!
You should define a function B that is continuously varying with t and pass it as a function handle. This way you will allow the ODE solver to adjust time steps efficiently (your use of ode15s, a stiff ODE solver, suggests that variable time stepping is even more crucial)
The form of your code will be something like this:
function [ u ] = solveSS( t,k,u0)
tspan = [t(k-1) t(k)];
[t,u] = ode15s(#SS,tspan,u0,#B);
function y = B(x)
%% insert B calculation
end
function zp = SS(t,z,B)
global A
zp = A*z + B(t);
end
end