Skip to content

Instantly share code, notes, and snippets.

@Foadsf

Foadsf/Model.mo Secret

Last active February 23, 2022 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Foadsf/5e4b998f5b99266eb031fbaadcc16a9c to your computer and use it in GitHub Desktop.
Save Foadsf/5e4b998f5b99266eb031fbaadcc16a9c to your computer and use it in GitHub Desktop.
an energy based controller for a mass-spring model to achieve time efficiency and avoiding overshoots --> https://stackoverflow.com/q/54782904/4999991
model Model1
//constants
parameter Real m = 1;
parameter Real k = 1;
parameter Real Fmax = 3;
parameter Real x0 = 1;
parameter Real x1 = 2;
parameter Real t1 = 3;
parameter Real v0 = -2;
//variables
Real x, v, a, xy, vm, F;
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;
vm := sign(xy - x) * sqrt(2 * (Fmax * abs(xy - x) + k * (xy^2 - x^2) / 2) / m);
if abs(xy - x) < 1e-6 then
F := k * x;
else
F := Fmax * sign(vm - v);
end if;
annotation(
experiment(StartTime = 0, StopTime = 20, Tolerance = 1e-6, Interval = 0.001),
__OpenModelica_simulationFlags(lv = "LOG_STATS", outputFormat = "mat", s = "euler"));
end Model1;
model Model2
//constants
parameter Real m = 1;
parameter Real k = 2;
parameter Real M = 0.1;
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;
initial equation
x = x0;
v = v0;
equation
v = der(x);
a = der(v);
m * a + k * x + M * sign(v) = F;
algorithm
if time < t1 then
xy := x0;
else
xy := x1;
end if;
vm := sign(xy - x) * abs(sqrt(2 * ((Fmax + M) * abs(xy - x) + k * (xy^2 - x^2) / 2) / m));
if abs(xy - x) < 1e-8 then
F := k * x + M * sign(v);
else
F := Fmax * sign(vm - v);
end if;
annotation(
experiment(StartTime = 0, StopTime = 20, Tolerance = 1e-06, Interval = 0.001),
__OpenModelica_simulationFlags(lv = "LOG_STATS", outputFormat = "mat", s = "euler"));
end Model2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment