Skip to content

Instantly share code, notes, and snippets.

View johanlofberg's full-sized avatar

Johan Löfberg johanlofberg

View GitHub Profile
A = randn(15,3);
b = rand(15,1);
E = randn(15,2);
z = sdpvar(3,1);
x = [0.1;0.2];
F = [A*z <= b+E*x];
obj = (z-1)'*(z-1);
%% Naive sos model
x = sdpvar(1,1);
y = sdpvar(1,1);
z = sdpvar(1,1);
p = 12+y^2-2*x^3*y+2*y*z^2+x^6-2*x^3*z^2+z^4+x^2*y^2;
options = sdpsettings('sos.newton',0,'sos.congruence',0);
[sol,v,Q] = solvesos(sos(p),[],options);
%% Newton polytope
options = sdpsettings('sos.newton',1,'sos.congruence',0);
%% Manual model
x = sdpvar(1,1);y = sdpvar(1,1);
p = (1+x)^4 + (1-y)^2;
v = monolist([x y],degree(p)/2);
Q = sdpvar(length(v));
p_sos = v'*Q*v;
F = [coefficients(p-p_sos,[x y]) == 0, Q >= 0];
optimize(F)
F = [coefficients(p-p_sos,[x y]) == 0, Q >= 0];
%% Nonconvex quadratic constraint
x1 = sdpvar(1,1);
x2 = sdpvar(1,1);
x3 = sdpvar(1,1);
p = -2*x1+x2-x3;
F = [x1*(4*x1-4*x2+4*x3-20)+x2*(2*x2-2*x3+9)+x3*(2*x3-13)+24>=0,
4-(x1+x2+x3)>=0,
6-(3*x2+x3)>=0,
x1>=0,
2-x1>=0,
%% Generate data
n = 10;
Q = randn(n);Q = Q*Q';
R = randn(n);R = R*R';
S = chol(Q);
T = chol(R);
%% Basic factorized model
x = sdpvar(n,1);
y = sdpvar(n,1);
%% Optimize over manually approximated ball
sdpvar x y
X = [1 x y;[x;y] eye(2)];
Objective = -x-y;
ops = sdpsettings('plot.shade',.1,'verbose',0);
ballApproximation = [-1 <= [x y] <= 1];
clf;hold on
for k = 1:10
for i = 1:20
vi = randn(3,1);
%% Look at function
ti = 0:0.001:8;
fi = min(min(2*ti,4),16-3*ti);
l = plot(t,fi);
grid on;hold on
l = plot(ti,0.001*cumsum(fi));
%% Manually derived
yalmip('clear')
sdpvar x
%% Simple ball approximation
x = sdpvar(2,1);
ballApproximation = [];
for i = 1:10
v = randn(2,1);v = v/norm(v);
ballApproximation = [ballApproximation, v'*x <= 1];
end
clf
plot(ballApproximation,x,'blue');hold on
plot(x'*x <= 1,x,'red');
%% Create data
x = [1 2 3 4 5 6]';
t = (0:0.02:2*pi)';
A = [sin(t) sin(2*t) sin(3*t) sin(4*t) sin(5*t) sin(6*t)];
e = (-4+8*rand(length(t),1));
e(100:115) = 30;
y = A*x+e;
%% Various estimates
xhat = sdpvar(6,1);
x = [1 2 3 4 5 6]';
t = (0:0.02:2*pi)';
Atrue = [sin(t) sin(2*t) sin(3*t) sin(4*t) sin(5*t) sin(6*t)];
ytrue = Atrue*x;
A = Atrue;%.*(0.5+rand(315,6));
A(100:210,:)=.1;
y = Atrue*x+randn(length(ytrue),1);
%% Low-level
xhat = sdpvar(6,1);