plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
rounder.m
|
.m
|
LMI-Matlab-master/yalmip/modules/global/rounder.m
| 5,889 |
utf_8
|
88ad60f43086ef44b94f4f9d1011a82a
|
function [upper,x_min] = rounder(p,relaxedsolution,prelaxed)
% Extremely simple heuristic for finding integer
% solutions.
%
% Rounds up and down, fixes etc.
% This was the relaxed solution
x = relaxedsolution.Primal;
% Assume we fail
upper = inf;
x_min = x;
% These should be integer
intvars = [p.integer_variables(:);p.binary_variables(:)];
if ismember('shifted ceil',p.options.bnb.rounding)
% Round, update nonlinear terms, and compute feasibility
for tt = logspace(0,-4,4)
f = x(intvars)-floor(x(intvars));
xtemp = x;xtemp(intvars) = round(xtemp(intvars));
xtemp(intvars(f > tt)) = ceil(x(intvars(f > tt)));
xtemp(p.binary_variables(:)) = min(1,xtemp(p.binary_variables(:)));
xtemp(p.binary_variables(:)) = max(0,xtemp(p.binary_variables(:)));
xtemp = fix_semivar(p,xtemp);
xtemp = setnonlinearvariables(p,xtemp);
if isfield(p.options,'plottruss')
if p.options.plottruss
plottruss(4,'Shifted ceil',p,xtemp);
end
end
upperhere = computecost(p.f,p.corig,p.Q,xtemp,p);
if upperhere < upper & checkfeasiblefast(p,xtemp,p.options.bnb.feastol)%res>-p.options.bnb.feastol
x_min = xtemp;
upper =upperhere;
end
end
end
if ismember('shifted round',p.options.bnb.rounding)
% Round, update nonlinear terms, and compute feasibility
for tt = 0:0.05:0.45
xtemp = x;xtemp(intvars) = round(xtemp(intvars)+tt);
xtemp(p.binary_variables(:)) = min(1,xtemp(p.binary_variables(:)));
xtemp(p.binary_variables(:)) = max(0,xtemp(p.binary_variables(:)));
xtemp = fix_semivar(p,xtemp);
xtemp = setnonlinearvariables(p,xtemp);
if isfield(p.options,'plottruss')
if p.options.plottruss
plottruss(2,'Shifted round',p,xtemp);
end
end
upperhere = computecost(p.f,p.corig,p.Q,xtemp,p);
if upperhere < upper & checkfeasiblefast(p,xtemp,p.options.bnb.feastol)%res>-p.options.bnb.feastol
x_min = xtemp;
upper =upperhere;%p.f+x_min'*p.Q*x_min + p.corig'*x_min;
return
end
end
end
if length(prelaxed.sosgroups)>0
xtemp = x;
for i = 1:length(prelaxed.sosgroups)
xi = x(prelaxed.sosgroups{1});
[j,loc] = max(xi);
xtemp(prelaxed.sosgroups{i}) = 0;
xtemp(prelaxed.sosgroups{i}(loc)) = 1;
end
xtemp = setnonlinearvariables(p,xtemp);
upperhere = computecost(p.f,p.corig,p.Q,xtemp,p);
if upperhere < upper & checkfeasiblefast(p,xtemp,p.options.bnb.feastol)
x_min = xtemp;
upper =upperhere;
return
end
end
if upper<inf
return
end
if ismember('round',p.options.bnb.rounding)
% Round, update nonlinear terms, and compute feasibility
xtemp = x;xtemp(intvars) = round(xtemp(intvars));
xtemp(p.binary_variables(:)) = min(1,xtemp(p.binary_variables(:)));
xtemp(p.binary_variables(:)) = max(0,xtemp(p.binary_variables(:)));
xtemp = fix_semivar(p,xtemp);
xtemp = setnonlinearvariables(p,xtemp);
if isfield(p.options,'plottruss')
if p.options.plottruss
subplot(2,2,2);
cla
title('Rounded node')
pic(p.options.truss,xtemp);
drawnow
end
end
if checkfeasiblefast(p,xtemp,p.options.bnb.feastol)%res>-p.options.bnb.feastol
x_min = xtemp;
upper = computecost(p.f,p.corig,p.Q,x_min,p);%p.f+x_min'*p.Q*x_min + p.corig'*x_min;
return
end
end
if ismember('fix',p.options.bnb.rounding)
% Do same using fix instead
xtemp = x;xtemp(intvars) = fix(xtemp(intvars));
xtemp(p.binary_variables(:)) = min(1,xtemp(p.binary_variables(:)));
xtemp(p.binary_variables(:)) = max(0,xtemp(p.binary_variables(:)));
xtemp = fix_semivar(p,xtemp);
xtemp = setnonlinearvariables(p,xtemp);
if checkfeasiblefast(p,xtemp,p.options.bnb.feastol)%if res>-p.options.bnb.feastol
x_min = xtemp;
upper = computecost(p.f,p.corig,p.Q,x_min,p);%upper = p.f+x_min'*p.Q*x_min + p.corig'*x_min;
return
end
end
if ismember('ceil',p.options.bnb.rounding)
% ...or ceil
xtemp = x;xtemp(intvars) = ceil(xtemp(intvars));
xtemp(p.binary_variables(:)) = min(1,xtemp(p.binary_variables(:)));
xtemp(p.binary_variables(:)) = max(0,xtemp(p.binary_variables(:)));
xtemp = fix_semivar(p,xtemp);
xtemp = setnonlinearvariables(p,xtemp);
if checkfeasiblefast(p,xtemp,p.options.bnb.feastol)%if res>-p.options.bnb.feastol
x_min = xtemp;
upper = computecost(p.f,p.corig,p.Q,x_min,p);%upper = p.f+x_min'*p.Q*x_min + p.corig'*x_min;
return
end
end
if ismember('floor',p.options.bnb.rounding)
% or floor
xtemp = x;xtemp(intvars) = floor(xtemp(intvars));
xtemp(p.binary_variables(:)) = min(1,xtemp(p.binary_variables(:)));
xtemp(p.binary_variables(:)) = max(0,xtemp(p.binary_variables(:)));
xtemp = fix_semivar(p,xtemp);
xtemp = setnonlinearvariables(p,xtemp);
if checkfeasiblefast(p,xtemp,p.options.bnb.feastol)%if res>-p.options.bnb.feastol
x_min = xtemp;
upper = computecost(p.f,p.corig,p.Q,x_min,p);%upper = p.f+x_min'*p.Q*x_min + p.corig'*x_min;
return
end
end
function x = fix_semivar(p,x);
for i = 1:length(p.semicont_variables)
j = p.semicont_variables(i);
if x(j)>= p.semibounds.lb(i) & x(j)<= p.semibounds.ub(i)
% OK
elseif x(j)==0
% OK
else
s = [abs(x(j)-0); abs(x(j)-p.semibounds.lb(i));abs(x(j)-p.semibounds.ub(i))];
[dummy,index] = min(s);
switch index
case 1
x(j) = 0;
case 2
x(j) = p.semibounds.lb(i);
case 3
x(j) = p.semibounds.lb(i);
end
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
initializesolution.m
|
.m
|
LMI-Matlab-master/yalmip/modules/global/initializesolution.m
| 2,998 |
utf_8
|
792f46b6b802380d0b130505eeda93a4
|
function [p,x_min,upper] = initializesolution(p);
x_min = zeros(length(p.c),1);
upper = inf;
if p.options.usex0
x = p.x0;
z = evaluate_nonlinear(p,x);
residual = constraint_residuals(p,z);
relaxed_feasible = all(residual(1:p.K.f)>=-p.options.bmibnb.eqtol) & all(residual(1+p.K.f:end)>=p.options.bmibnb.pdtol);
if relaxed_feasible
upper = p.f+p.c'*z+z'*p.Q*z;
x_min = z;
end
else
x0 = p.x0;
p.x0 = zeros(length(p.c),1);
% Avoid silly warnings
if ~isempty(p.evalMap)
for i = 1:length(p.evalMap)
if (isequal(p.evalMap{i}.fcn,'log') | isequal(p.evalMap{i}.fcn,'log2') | isequal(p.evalMap{i}.fcn,'log10'))
p.x0(p.evalMap{i}.variableIndex) = (p.lb(p.evalMap{i}.variableIndex) + p.ub(p.evalMap{i}.variableIndex))/2;
end
end
end
x = p.x0;
z = evaluate_nonlinear(p,x);
z = propagateAuxilliary(p,z);
residual = constraint_residuals(p,z);
relaxed_feasible = all(residual(1:p.K.f)>=-p.options.bmibnb.eqtol) & all(residual(1+p.K.f:end)>=p.options.bmibnb.pdtol);
if relaxed_feasible
infs = isinf(z);
if isempty(infs)
upper = p.f+p.c'*z+z'*p.Q*z;
x_min = z;
x0 = x_min;
else
% Allow inf solutions if variables aren't used in objective
if all(p.c(infs)==0) & nnz(p.Q(infs,:))==0
ztemp = z;ztemp(infs)=0;
upper = p.f+p.c'*ztemp+ztemp'*p.Q*ztemp;
x_min = z;
x0 = x_min;
end
end
end
p.x0 = (p.lb + p.ub)/2;
if ~isempty(p.integer_variables)
p.x0(p.integer_variables) = round(p.x0(p.integer_variables));
end
if ~isempty(p.binary_variables)
p.x0(p.binary_variables) = round(p.x0(p.binary_variables));
end
x = p.x0;
x(isinf(x))=eps;
x(isnan(x))=eps;
z = evaluate_nonlinear(p,x);
z = propagateAuxilliary(p,z);
residual = constraint_residuals(p,z);
relaxed_feasible = all(residual(1:p.K.f)>=-p.options.bmibnb.eqtol) & all(residual(1+p.K.f:end)>=p.options.bmibnb.pdtol);
if relaxed_feasible & ( p.f+p.c'*z+z'*p.Q*z < upper)
upper = p.f+p.c'*z+z'*p.Q*z;
x_min = z;
x0 = x_min;
end
p.x0 = x0;
end
function z = propagateAuxilliary(p,z)
try
% New feature. If we introduce new variables xx = f(x) to be used
% in a nonlinear operator, we can derive its value when x is chosen
if ~isempty(p.aux_variables)
if p.K.f > 1
A = p.F_struc(1:p.K.f,2:end);
b = p.F_struc(1:p.K.f,1);
for i = 1:length(p.aux_variables)
j = find(A(:,p.aux_variables(i)));
if length(j)==1
if A(j,p.aux_variables(i))==1
z(p.aux_variables(i)) = -b(j)-A(j,:)*z;
end
end
end
z = evaluate_nonlinear(p,z);
end
end
catch
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
mpt_solvenode.m
|
.m
|
LMI-Matlab-master/yalmip/modules/parametric/mpt_solvenode.m
| 4,757 |
utf_8
|
5ba2e2ea43c2ecbf8cfb0336f50e41a9
|
function model = mpt_solvenode(Matrices,lower,upper,OriginalModel,model,options)
% This is the core code. Lot of pre-processing to get rid of strange stuff
% arising from odd problems, big-M etc etc
Matrices.lb = lower;
Matrices.ub = upper;
% Remove equality constraints and trivial stuff from big-M
[equalities,redundant] = mpt_detect_fixed_rows(Matrices);
if ~isempty(equalities)
% Constraint of the type Ex == W, i.e. lower-dimensional
% parametric space
if any(sum(abs(Matrices.G(equalities,:)),2)==0)
return
end
end
Matrices = mpt_collect_equalities(Matrices,equalities);
go_on_reducing = size(Matrices.Aeq,1)>0;
Matrices = mpt_remove_equalities(Matrices,redundant);
[Matrices,infeasible] = mpt_project_on_equality(Matrices);
% We are not interested in explicit solutions over numerically empty regions
parametric_empty = any(abs(Matrices.lb(end-Matrices.nx+1:end)-Matrices.ub(end-Matrices.nx+1:end)) < 1e-6);
% Were the equality constraints found to be infeasible?
if infeasible | parametric_empty
return
end
% For some models with a lot of big-M stuff etc, the amount of implicit
% equalities are typically large, making the LP solvers unstable if they
% are not removed. To avoid problems, we iteratively detect fixed variables
% and strenghten the bounds.
fixed = find(Matrices.lb == Matrices.ub);
infeasible = 0;
while 0%~infeasible & options.mp.presolve
[Matrices,infeasible] = mpt_derive_bounds(Matrices,options);
if isequal(find(Matrices.lb == Matrices.ub),fixed)
break
end
fixed = find(Matrices.lb == Matrices.ub);
end
% We are not interested in explicit solutions over numerically empty regions
parametric_empty = any(abs(Matrices.lb(end-Matrices.nx+1:end)-Matrices.ub(end-Matrices.nx+1:end)) < 1e-6);
if ~infeasible & ~parametric_empty
while go_on_reducing & ~infeasible & options.mp.presolve
[equalities,redundant] = mpt_detect_fixed_rows(Matrices);
if ~isempty(equalities)
% Constraint of the type Ex == W, i.e. lower-dimensional
% parametric space
if any(sum(abs(Matrices.G(equalities,:)),2)==0)
return
end
end
Matrices = mpt_collect_equalities(Matrices,equalities);
go_on_reducing = size(Matrices.Aeq,1)>0;
Matrices = mpt_remove_equalities(Matrices,redundant);
[Matrices,infeasible] = mpt_project_on_equality(Matrices);
M = Matrices;
if go_on_reducing & ~infeasible
[Matrices,infeasible] = mpt_derive_bounds(Matrices,options);
end
if infeasible
% Numerical problems most likely because this infeasibility
% should have been caught above. We have only cleaned the model
Matrices = M;
end
end
if ~infeasible
if Matrices.qp
e = eig(full(Matrices.H));
if min(e) == 0
disp('Lack of strict convexity may lead to troubles in the mpQP solver')
elseif min(e) < -1e-8
disp('Problem is not positive semidefinite! Your mpQP solution may be completely wrong')
elseif min(e) < 1e-5
disp('QP is close to being (negative) semidefinite, may lead to troubles in mpQP solver')
end
%Matrices.H = Matrices.H + eye(length(Matrices.H))*1e-4;
[Pn,Fi,Gi,ac,Pfinal,details] = mpt_mpqp(Matrices,options.mpt);
else
[Pn,Fi,Gi,ac,Pfinal,details] = mpt_mplp(Matrices,options.mpt);
end
[Fi,Gi,details] = mpt_project_back_equality(Matrices,Fi,Gi,details,OriginalModel);
[Fi,Gi] = mpt_select_rows(Fi,Gi,Matrices.requested_variables);
[Fi,Gi] = mpt_clean_optmizer(Fi,Gi);
model = mpt_appendmodel(model,Pfinal,Pn,Fi,Gi,details);
% model = mpt_reduceOverlaps_orderfaces(model);if ~isa(model,'cell');model = {model};end
end
else
end
function [Pn,Fi,Gi,ac,Pfinal,details] = mpt_mpqp_mplcp(Matrices,options)
if Matrices.qp
lcpData = lcp_mpqp(Matrices);
BB = mplcp(lcpData)
[Pn,Fi,Gi] = soln_to_mpt(lcpData,BB);
else
lcpData = lcp_mplp(Matrices);
BB = mplcp(lcpData)
[Pn,Fi,Gi] = soln_to_mpt(lcpData,BB);
end
Pfinal = union(Pn);
if Matrices.qp
for i=1:length(Fi)
details.Ai{i} = 0.5*Fi{i}'*Matrices.H*Fi{i} + 0.5*(Matrices.F*Fi{i}+Fi{i}'*Matrices.F') + Matrices.Y;
details.Bi{i} = Matrices.Cf*Fi{i}+Gi{i}'*Matrices.F' + Gi{i}'*Matrices.H*Fi{i} + Matrices.Cx;
details.Ci{i} = Matrices.Cf*Gi{i}+0.5*Gi{i}'*Matrices.H*Gi{i} + Matrices.Cc;
end
else
for i=1:length(Fi)
details.Ai{i} = [];
details.Bi{i} = Matrices.H*Fi{i};
details.Ci{i} = Matrices.H*Gi{i};
end
end
ac = [];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
mpt_parbb.m
|
.m
|
LMI-Matlab-master/yalmip/modules/parametric/mpt_parbb.m
| 5,172 |
utf_8
|
9ed244f3afde3125092cc9cd08a5feb0
|
function model = mpt_parbb(Matrices,options)
% For simple development, the code is currently implemented in high-level
% YALMIP and MPT code. Hence, a substantial part of the computation time is
% stupid over-head.
[Matrices.lb,Matrices.ub] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);
U = sdpvar(Matrices.nu,1);
x = sdpvar(Matrices.nx,1);
F = (Matrices.G*U <= Matrices.W + Matrices.E*x);
F = F + (Matrices.lb <= [U;x] <= Matrices.ub);
F = F + (binary(U(Matrices.binary_var_index)));
F = F + (Matrices.Aeq*U + Matrices.Beq*x == Matrices.beq);
h = Matrices.H*U + Matrices.F*x;
Universe = polytope((Matrices.lb(end-Matrices.nx+1:end) <= x <= Matrices.ub(end-Matrices.nx+1:end)));
model = parametric_bb(F,h,options,x,Universe);
function sol = parametric_bb(F,obj,ops,x,Universe)
% F : All constraints
% obj : Objective
% x : parametric variables
% y : all binary variables
if isempty(ops)
ops = sdpsettings;
end
ops.mp.algorithm = 1;
ops.cachesolvers = 0;
ops.mp.presolve=1;
ops.solver = '';
% Expand nonlinear operators only once
F = expandmodel(F,obj);
ops.expand = 0;
% Gather all binary variables
y = unique([depends(F) depends(obj)]);
n = length(y)-length(x);
y = intersect(y,[yalmip('binvariables') depends(F(find(is(F,'binary'))))]);
y = recover(y);
% Make sure binary relaxations satisfy 0-1 constraints
F = F + (0 <= y <= 1);
% recursive, starting in maximum universe
sol = sub_bb(F,obj,ops,x,y,Universe);
% Nice, however, we have introduced variables along the process, so the
% parametric solutions contain variables we don't care about
for i = 1:length(sol)
for j = 1:length(sol{i}.Fi)
sol{i}.Fi{j} = sol{i}.Fi{j}(1:n,:);
sol{i}.Gi{j} = sol{i}.Gi{j}(1:n,:);
end
end
function sol = sub_bb(F,obj,ops,x,y,Universe)
sol = {};
% Find a feasible point in this region. Note that it may be the case that a
% point is feasible, but the feasible space is flat. This will cause the
% mplp solver to return an empty solution, and we have to pick a new
% binary solution.
localsol = {[]};
intsol.problem = 0;
if 1%while intsol.problem == 0
localsol = {[]};
while isempty(localsol{1}) & (intsol.problem == 0)
ops.verbose = ops.verbose-1;
intsol = solvesdp(F,obj,sdpsettings(ops,'solver','glpk'));
ops.verbose = ops.verbose+1;
if intsol.problem == 0
y_feasible = round(double(y));
ops.relax = 1;
localsol = solvemp(F+(y == y_feasible),obj,ops,x);
ops.relax = 0;
if isempty(localsol{1})
F = F + not_equal(y,y_feasible);
end
F = F + not_equal(y,y_feasible);
end
end
if ~isempty(localsol{1})
% YALMIP syntax...
if isa(localsol,'cell')
localsol = localsol{1};
end
% Now we want to find solutions with other binary combinations, in
% order to find the best one. Cut away the current bionary using
% overloaded not equal
F = F + not_equal(y,y_feasible);
% Could be that the binary was feasible, but the feasible space in the
% other variables is empty/lower-dimensional
if ~isempty(localsol)
% Dig into this solution. Try to find another feasible binary
% combination, with a better cost, in each of the regions
for i = 1:length(localsol.Pn)
G = F;
% Better cost
G = G + (obj <= localsol.Bi{i}*x + localsol.Ci{i});
% In this region
[H,K] = double(localsol.Pn(i));
G = G + (H*x <= K);
% Recurse
diggsol{i} = sub_bb(G,obj,ops,x,y,localsol.Pn(i));
end
% Create all neighbour regions, and compute solutions in them too
flipped = regiondiff(union(Universe),union(localsol.Pn));
flipsol={};
for i = 1:length(flipped)
[H,K] = double(flipped(i));
flipsol{i} = sub_bb(F+ (H*x <= K),obj,ops,x,y,flipped(i));
end
% Just place all solutions in one big cell. We should do some
% intersect and compare already here, but I am lazy now.
sol = appendlists(sol,localsol,diggsol,flipsol);
end
end
end
function sol = appendlists(sol,localsol,diggsol,flipsol)
sol{end+1} = localsol;
for i = 1:length(diggsol)
if ~isempty(diggsol{i})
if isa(diggsol{i},'cell')
for j = 1:length(diggsol{i})
sol{end+1} = diggsol{i}{j};
end
else
sol{end+1} = diggsol{i};
end
end
end
for i = 1:length(flipsol)
if ~isempty(flipsol{i})
if isa(flipsol{i},'cell')
for j = 1:length(flipsol{i})
sol{end+1} = flipsol{i}{j};
end
else
sol{end+1} = flipsol{i};
end
end
end
function F = not_equal(X,Y)
zv = find((Y == 0));
ov = find((Y == 1));
lhs = 0;
if ~isempty(zv)
lhs = lhs + sum(extsubsref(X,zv));
end
if ~isempty(ov)
lhs = lhs + sum(1-extsubsref(X,ov));
end
F = (lhs >=1);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
mpt_appendmodel.m
|
.m
|
LMI-Matlab-master/yalmip/modules/parametric/mpt_appendmodel.m
| 9,545 |
utf_8
|
1d7ce75903476d3b64c70bdd45442498
|
function model = savemptmodel(model,Pfinal,Pn,Fi,Gi,details);
if length(Fi)>0
if length(model) == 0
model{1} = fakemptmodel(Pfinal, Pn, Fi, Gi, details.Ai, details.Bi, details.Ci);
[H,K] = double(Pfinal);
model{1}.epicost = [];
model{1}.convex = 1;
else
anyqp = nnz([details.Ai{:}])>0;
for i = 1:length(model)
anyqp = anyqp | nnz([model{i}.Ai{:}])>0;
if anyqp
break
end
end
if anyqp
model = savemptmodelqp(model,Pfinal,Pn,Fi,Gi,details);
return
else
newmodel = fakemptmodel(Pfinal, Pn, Fi, Gi, details.Ai, details.Bi, details.Ci);
newmodel.epicost = [];
newmodel.convex = 1;
replace = zeros(length(model),1);
discard = 0;
for i = 1:length(model)
Y = model{i}.Pfinal;
% quickeq( Pfinal, Y)
% if (Pfinal == Y) ~= quickeq( Pfinal, Y)
% 1
% end
if Pfinal == Y
if isempty(newmodel.epicost)
B = reshape([details.Bi{:}]',size(details.Bi{1},2),[])';
c = reshape([details.Ci{:}]',[],1);
[H,K] = double(Pfinal);
newmodel.epicost = generate_epicost(H,K,B,c);
end
if isempty(model{i}.epicost)
B = reshape([model{i}.Bi{:}]',size(model{i}.Bi{1},2),[])';
c = reshape([model{i}.Ci{:}]',[],1);
[H,K] = double(model{i}.Pfinal);
model{i}.epicost = generate_epicost(H,K,B,c);
end
if newmodel.epicost <= model{i}.epicost
discard = 1;
break
end
if newmodel.epicost >= model{i}.epicost
replace(i,1) = 1;
end
elseif Pfinal >= model{i}.Pfinal
if isempty(newmodel.epicost)
B = reshape([details.Bi{:}]',size(details.Bi{1},2),[])';
c = reshape([details.Ci{:}]',[],1);
[H,K] = double(Pfinal);
newmodel.epicost = generate_epicost(H,K,B,c);
end
if isempty(model{i}.epicost)
B = reshape([model{i}.Bi{:}]',size(model{i}.Bi{1},2),[])';
c = reshape([model{i}.Ci{:}]',[],1);
[H,K] = double(model{i}.Pfinal);
model{i}.epicost = generate_epicost(H,K,B,c);
end
if newmodel.epicost >= model{i}.epicost
replace(i,1) = 1;
end
elseif Pfinal <= model{i}.Pfinal
if isempty(newmodel.epicost)
B = reshape([details.Bi{:}]',size(details.Bi{1},2),[])';
c = reshape([details.Ci{:}]',[],1);
[H,K] = double(Pfinal);
newmodel.epicost = generate_epicost(H,K,B,c);
end
if isempty(model{i}.epicost)
B = reshape([model{i}.Bi{:}]',size(model{i}.Bi{1},2),[])';
c = reshape([model{i}.Ci{:}]',[],1);
[H,K] = double(model{i}.Pfinal);
model{i}.epicost = generate_epicost(H,K,B,c);
end
if newmodel.epicost <= model{i}.epicost
discard = 1;
break
end
end
end
if ~discard
model = {model{find(~replace)},newmodel};
end
end
end
end
function model = savemptmodelqp(model,Pfinal,Pn,Fi,Gi,details);
newmodel = fakemptmodel(Pfinal, Pn, Fi, Gi, details.Ai, details.Bi, details.Ci);
newmodel.epicost = [];
newmodel.convex = 1;
replace = zeros(length(model),1);
discard = 0;
for i = 1:length(model)
% Trivial pruning, why not...
if quadraticLarger(details,model{i})
if Pfinal == model{i}.Pfinal
discard = 1;
break;
elseif Pfinal <= model{i}.Pfinal
discard = 1;
break;
end
end
if Pfinal==model{i}.Pfinal
elseif Pfinal >= model{i}.Pfinal
doreplace = 1;
for k = 1:length(details.Ai)
Qnew = [details.Ai{k} 0.5*details.Bi{k}' ;0.5*details.Bi{k} details.Ci{k}];
for j = 1:length(model{i}.Pfinal)
Qold = [model{i}.Ai{j} 0.5*model{i}.Bi{j}';0.5*model{i}.Bi{j} model{i}.Ci{j}];
if ~all(real(eig(full(Qold-Qnew)))>=-1e-12)
doreplace = 0;
end
end
end
if doreplace
replace(i,1) = 1;
end
elseif Pfinal <= model{i}.Pfinal
% if relaxationLarger(details,model{i},Pn,model{i}.Pn)
% discard = 1;
% break
% end
%
if length(Pn)==1
discard = 1;
Qnew = [details.Ai{1} 0.5*details.Bi{1}' ;0.5*details.Bi{1} details.Ci{1}];
for j = 1:length(model{i}.Pfinal)
Qold = [model{i}.Ai{j} 0.5*model{i}.Bi{j}';0.5*model{i}.Bi{j} model{i}.Ci{j}];
if ~all(real(eig(full(Qnew-Qold)))>=-1e-12)
discard = 0;
end
end
if discard
break
end
end
%
% if length(Pn)==1
% discard = 1;
% Qnew = [details.Ai{1} 0.5*details.Bi{1}' ;0.5*details.Bi{1} details.Ci{1}];
% for j = 1:length(model{i}.Pn)
% Qold = [model{i}.Ai{j} 0.5*model{i}.Bi{j}';0.5*model{i}.Bi{j} model{i}.Ci{j}];
% Pis = intersect(model{i}.Pn(j),newmodel.Pfinal);
% if isfulldim(Pis)
% [H,K] = double(Pis);
% if ~quadraticLarger2(Qnew,Qold,H,K)
% discard = 0;
% end
% end
% end
% if discard
% break
% end
% end
%
end
end
if ~discard
model = {model{find(~replace)},newmodel};
end
function XbiggerY = relaxationLarger(X,Y,P1,P2)
XbiggerY = 1;
x = sdpvar(length(X.Ai{1}),1);
for k = 1:length(X.Ai)
Xq = [X.Ai{k} 0.5*X.Bi{k}' ;0.5*X.Bi{k} X.Ci{k}];
p1 = [x;1]'*Xq*[x;1];
for j = 1:length(Y.Ai)
Yq = [Y.Ai{j} 0.5*Y.Bi{j}' ;0.5*Y.Bi{j} Y.Ci{j}];
if all(real(eig(full(Xq-Yq)))>0)
else
isc = intersect(P1(k),P2(j));
if isfulldim(isc)
p2 = [x;1]'*Yq*[x;1];
[H,K] = double(isc);
[xx,cc,vv]= solvemoment((H*x <= K),p1-p2)
end
end
% if ~all(real(eig(Xq-Yq))>=-1e-12)
% XbiggerY = 0;
% return
% end
end
end
function XbiggerY = quadraticLarger2(Q1,Q2,H,K)
x = sdpvar(size(H,2),1);
obj = [x;1]'*Q1*[x;1]-[x;1]'*Q2*[x;1];
%sol = solvemoment((H*x <= K),obj,[],2);
sol = solvesdp((H*x <= K),obj,sdpsettings('solver','kktqp'));
%if relaxdouble(obj) > -1e-5
if double(obj) > -1e-5
XbiggerY = 1;
else
XbiggerY = 0;
end
function XbiggerY = quadraticLarger(X,Y)
XbiggerY = 1;
for k = 1:length(X.Ai)
Xq = [X.Ai{k} 0.5*X.Bi{k}' ;0.5*X.Bi{k} X.Ci{k}];
for j = 1:length(Y.Ai)
Yq = [Y.Ai{j} 0.5*Y.Bi{j}' ;0.5*Y.Bi{j} Y.Ci{j}];
if ~all(real(eig(full(Xq-Yq)))>=-1e-12)
XbiggerY = 0;
return
end
end
end
function epicost = generate_epicost(H,K,B,c)
epicost = polytope([B -ones(size(B,1),1);H zeros(size(H,1),1)],[-c;K]);
function C = fakemptmodel(Pfinal, Pn, Fi, Gi, Ai, Bi, Ci)
dummystruct.dummyfield = [];
C.sysStruct = dummystruct;
C.probStruct = dummystruct;
C.details.origSysStruct = dummystruct;
C.details.origProbStruct = dummystruct;
nr = length(Pn);
C.Pfinal = Pfinal;
C.Pn = Pn;
C.Fi = Fi;
C.Gi = Gi;
if isempty(Ai),
Ai = cell(1, nr);
end
C.Ai = Ai;
C.Bi = Bi;
C.Ci = Ci;
C.dynamics = repmat(0, 1, nr);
C.overlaps = 0;
function status = quickeq(P,Q)
status = 1;
Q = struct(Q);
P = struct(P);
[ncP,nxP]=size(P.H);
[ncQ,nxQ]=size(Q.H);
if ncP ~=ncQ
status = 0;
return
end
Pbbox = P.bbox;
Qbbox = Q.bbox;
if ~isempty(Pbbox) & ~isempty(Qbbox),
bbox_tol = 1e-4;
if any(abs(Pbbox(:,1) - Qbbox(:,1)) > bbox_tol) | any(abs(Pbbox(:,2) - Qbbox(:,2)) > bbox_tol),
% bounding boxes differ by more than abs_tol => polytopes cannot be equal
status = 0;
return
end
% we cannot reach any conclusion based solely on the fact that bounding
% boxes are identical, therefore we continue...
end
status=1;
PAB=[P.H P.K];
QAB=[Q.H Q.K];
for ii=1:ncP
%if all(sum(abs(QAB-repmat(PAB(ii,:),ncQ,1)),2)>abs_tol)
%if all(sum(abs(QAB-PAB(ones(ncQ,1)*ii,:)),2)>abs_tol)
Z = sum(abs(QAB-PAB(ones(ncQ,1)*ii,:)),2);
if all(Z>1e-8)
status=0;
return;
end
end
for ii=1:ncQ
%if all(sum(abs(PAB-repmat(QAB(ii,:),ncP,1)),2)>abs_tol)
%if all(sum(abs(PAB-QAB(ones(ncP,1)*ii,:)),2)>abs_tol)
Z = sum(abs(PAB-QAB(ones(ncP,1)*ii,:)),2);
if all(Z>1e-8)
status=0;
return;
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
dualize.m
|
.m
|
LMI-Matlab-master/yalmip/extras/dualize.m
| 24,839 |
utf_8
|
95f053810de0314bbbbff10c9d8c9125
|
function [Fdual,objdual,X,t,err,complexInfo] = dualize(F,obj,auto,extlp,extend,options)
% DUALIZE Create the dual of an SDP given in primal form
%
% [Fd,objd,X,t,err] = dualize(F,obj,auto)
%
% Input
% F : Primal constraint in form AX=b+dt, X>0, t free.
% obj : Primal cost CX+ct
% auto : If set to 0, YALMIP will not automatically handle variables
% and update variable values when the dual problem is solved.
% extlp: If set to 0, YALMIP will not try to perform variables changes in
% order to convert simple translated LP cones (as in x>1) to
% standard unit cone constraints (x>0)
%
% Output
% Fd : Dual constraints in form C-A'y>0, c-dy==0
% obj : Dual cost b'y (to be MAXIMIZED!)
% X : The detected primal cone variables
% t : The detected primal free variables
% err : Error status (returns 0 if no problems)
%
% Example
% See the HTML help.
%
% See also DUAL, SOLVESDP, PRIMALIZE
% Check for unsupported problems
if isempty(F)
F = ([]);
end
complexInfo = [];
LogDetTerm = 0;
if nargin < 2
obj = [];
elseif isa(obj,'logdet')
Plogdet = getP(obj);
gainlogdet = getgain(obj);
if ~all(gainlogdet <= 0)
error('There are nonconvex logdet terms in the objective')
end
if ~all(gainlogdet == -1)
error('DUALIZE does currently not support coefficients before LOGDET terms')
end
obj = getcx(obj);
if ~isempty(obj)
if ~is(obj,'linear')
error('DUALIZE does not support nonlinear terms in objective (except logdet terms)')
end
end
LogDetTerm = 1;
Ftemp = ([]);
for i = 1:length(Plogdet)
Ftemp = Ftemp + [(Plogdet{i} >= 0) : 'LOGDET'];
end
F = Ftemp + F;
end
err = 0;
p1 = ~isreal(obj);%~(isreal(F) & isreal(obj));
p2 = ~(islinear(F) & islinear(obj));
p3 = any(is(F,'integer')) | any(is(F,'binary'));
if p1 | p2 | p3
if nargout == 5
Fdual = ([]);objdual = [];y = []; X = []; t = []; err = 1;
else
problems = {'Cannot dualize complex-valued problems','Cannot dualize nonlinear problems','Cannot dualize discrete problems'};
error(problems{min(find([p1 p2 p3]))});
end
end
if nargin<5 || isempty(extend)
extend = 1;
end
if extend
if nargin < 6 || isempty(options)
options = sdpsettings;
end
options.dualize = 1;
options.allowmilp = 0;
options.solver = '';
[F,failure,cause] = expandmodel(F,obj,options);
if failure
error('Failed during convexity propagation. Avoid nonlinear operators when applying dualization.');
end
end
if nargin<3 || isempty(auto)
auto = 1;
end
if nargin<4 || isempty(extlp)
extlp = 1;
end
% Cones and equalities
F_AXb = ([]);
% Shiftmatrix is a bit messy at the moment.
% We want to be able to allow cones X>shift
% by using a new variable X-shift = Z
shiftMatrix = {};
X={};
% First, get variables in initial SDP cones
% We need this to avoid adding the same variable twice
% when we add simple LP constraints (as in P>0, P(1,3)>0)
varSDP = [];
SDPset = zeros(length(F),1);
ComplexSDPset = zeros(length(F),1);
isSDP = is(F,'sdp');
for i = 1:length(F)
if isSDP(i);
Fi = sdpvar(F(i));
if is(Fi,'shiftsdpcone')
vars = getvariables(Fi);
if isempty(findrows(varSDP,[vars(1) vars(end)]))
SDPset(i) = 1;
varSDP = [varSDP;vars(1) vars(end)];
shiftMatrix{end+1} = getbasematrix(Fi,0);
X{end+1}=Fi;
if is(Fi,'complex')
ComplexSDPset(i) = 1;
end
end
end
end
end
F_SDP = F(find(SDPset));
F = F(find(~SDPset));
% Same thing for second order cones
% However, we must not add any SOC cones
% that we already defined as SDP cones
varSOC = [];
SOCset = zeros(length(F),1);
isSOCP = is(F,'socp');
for i = 1:length(F)
if isSOCP(i);%is(F(i),'socp')
Fi = sdpvar(F(i));
if is(Fi,'socone')
vars = getvariables(Fi);
% Make sure these variables are not SDP cone variables
% This can actually only happen for (X>0) + (Xcone((2:end,1),X(1)))
if ~isempty(varSDP)
inSDP = any(varSDP(:,1)<=vars(1)& vars(1) <=varSDP(:,2)) | any(varSDP(:,1)<=vars(end)& vars(end) <=varSDP(:,2));
else
inSDP = 0;
end
if ~inSDP
SOCset(i) = 1;
vars = getvariables(Fi);
varSOC = [varSOC;vars(1) vars(end)];
shiftMatrix{end+1} = getbasematrix(Fi,0);
X{end+1}=Fi;
end
end
end
end
F_SOC = F(find(SOCset));
F = F(find(~SOCset));
% Merge SDP and SOC data
varCONE = [varSDP;varSOC];
F_CONE = F_SDP + F_SOC;
% Detect primal-variables from SDP diagonals (not tested substantially...)
implicit_positive = detect_diagonal_terms(F);
% Find all LP constraints, add slacks and extract simple cones
% to speed up things, we treat LP cone somewhat different
% compared to the conceptually similiar SOCP/SDP cones
% This code is pretty messy, since there are a lot off odd
% cases to take care of (x>0 and x>1 etc etc)
elementwise = is(F,'element-wise');
elementwise_index = find(elementwise);
if ~isempty(elementwise_index)
% Find element-wise inequalities
Flp = F(elementwise_index);
% Add constraint originating from diagonals in dual-type LMIs
if ~isempty(implicit_positive)
implicit_positive = setdiff(implicit_positive,getvariables(F_CONE));
if ~isempty(implicit_positive)
Flp = Flp + (recover(implicit_positive) >= 0);
end
end
F = F(find(~elementwise)); % remove these LPs
% Find LP cones
lpconstraint = [];
for i = 1:length(Flp)
temp = sdpvar(Flp(i));
if min(size(temp))>1
temp = temp(:);
end
lpconstraint = [lpconstraint reshape(temp,1,length(temp))];
end
% Find all constraints of type a_i+x_i >0 and extract the unique and
% most constraining inequalities (i.e. remove redundant lower bounds)
base = getbase(lpconstraint);
temp = sum(base(:,2:end)~=0,2)==1;
candidates = find(temp);
if length(candidates)>0
% The other ones...
alwayskeep = find(sum(base(:,2:end)~=0,2)~=1);
w1 = lpconstraint(alwayskeep);
if all(temp)
w2 = lpconstraint;
else
w2 = lpconstraint(candidates);
end
% Find unique rows
base = getbase(w2);
[i,uniquerows,k] = unique(base(:,2:end)*randn(size(base,2)-1,1));
aUniqueRow=k(:)';
keep = [];
rhsLP = base(:,1);
rr = histc(k,[1:max(k)]);
if all(rr==1)
lpconstraint = [w1 w2];
else
for i=1:length(k)
sameRow=find(k==k(i));
if length(sameRow)==1
keep = [keep sameRow];
else
rhs=base(sameRow,1);
[val,pos]=min(rhsLP(sameRow));
keep = [keep sameRow(pos)];
end
end
lpconstraint = [w1 w2(unique(keep))];
end
end
% LP cone will be saved in a vector for speed
x = [];
% Pure cones of the type x>0
base = getbase(lpconstraint);
purelpcones = (base(:,1)==0) & (sum(abs(base(:,2:end)),2)==1) & (sum(base(:,2:end)==1,2)==1);
if ~isempty(purelpcones)
if all(purelpcones)
x = [x lpconstraint];
else
x = [x lpconstraint(purelpcones)];
end
lpconstraint = lpconstraint(find(~purelpcones));
end
% Translated cones x>k, k positive
% User does not want to make variable changes based on k
% But if k>=0, we can at-least mark x as a simple LP cone variable and
% thus avoid a free variable.
if ~extlp & ~isempty(lpconstraint)
base = getbase(lpconstraint);
lpcones = (base(:,1)<0) & (sum(abs(base(:,2:end)),2)==1) & (sum(base(:,2:end)==1,2)==1);
if ~isempty(find(lpcones))
s = recover(getvariables(lpconstraint(find(lpcones))));
x = [x reshape(s,1,length(s))];
end
end
% Translated cones x>k
% Extract these and perform the associated variable change y=x-k
if ~isempty(lpconstraint)%Avoid warning in 5.3.1
base = getbase(lpconstraint);
lpcones = (sum(abs(base(:,2:end)),2)==1) & (sum(base(:,2:end)==1,2)==1);
if ~isempty(lpcones) & extlp
x = [x lpconstraint(find(lpcones))];
nlp = lpconstraint(find(~lpcones));
if ~isempty(nlp)
s = sdpvar(1,length(nlp));
F_AXb = F_AXb + (nlp-s==0);
x = [x s];
end
elseif length(lpconstraint) > 0
s = sdpvar(1,length(lpconstraint));
x = [x s]; % New LP cones
F_AXb = F_AXb + (lpconstraint-s==0);
end
end
% Sort asccording to variable index
% (Code below assumes x is sorted in increasing variables indicies)
base = getbase(x);base = base(:,2:end);[i,j,k] = find(base);
if ~isequal(i,(1:length(x))')
x = x(i);
end
xv = getvariables(x);
% For mixed LP/SDP problems, we must ensure that LP cone variables are
% not actually an element in a SDP cone variable
if ~isempty(varCONE)
keep = zeros(length(x),1);
for i = 1:length(xv)
if any(varCONE(:,1)<=xv(i) & xv(i) <=varCONE(:,2))
else
keep(i) = 1;
end
end
if ~all(keep)
% We need to add some explicit constraints on some elements and
% remove the x variables since they are already in a cone
% variable
xcone = x(find(~keep));
s = sdpvar(1,length(xcone));
F_AXb = F_AXb + (xcone-s==0);
x = x(find(keep));
x = [x s];
end
end
else
x = [];
end
% Check for mixed cones, ie terms C-A'y > 0.
keep = ones(length(F),1);
isSDP = is(F,'sdp');
isSOCP = is(F,'socp');
isVecSOCP = is(F,'vecsocp');
% Pre-allocate all SDP slacks in one call
% This is a lot faster
if nnz(isSDP) > 0
SDPindicies = find(isSDP)';
for i = 1:length(SDPindicies)%find(isSDP)'
Fi = sdpvar(F(SDPindicies(i)));
ns(i) = size(Fi,1);
ms(i) = ns(i);
isc(i) = is(Fi,'complex');
end
if any(isc)
for i = 1:length(ns)
if isc(i)
Slacks{i} = sdpvar(ns(i),ns(i),'hermitian','complex');
else
Slacks{i} = sdpvar(ns(i),ns(i));
end
end
else
Slacks = sdpvar(ns,ms);
end
if ~isa(Slacks,'cell')
Slacks = {Slacks};
end
end
prei = 1;
for i = 1:length(F)
if isSDP(i)
% Semidefinite dual-form cone
Fi = sdpvar(F(i));
n = size(Fi,1);
% S = sdpvar(n,n);
S = Slacks{prei};prei = prei + 1;
slack = Fi-S;
ind = find(triu(reshape(1:n^2,n,n)));
if is(slack,'complex')
F_AXb = F_AXb + (real(slack(ind))==0) + (imag(slack(ind))==0);
else
F_AXb = F_AXb + (slack(ind)==0);
end
F_CONE = F_CONE + lmi(S,[],[],[],1);
shiftMatrix{end+1} = spalloc(n,n,0);
X{end+1}=S;
keep(i)=0;
elseif isSOCP(i)
% SOC dual-form cone
Fi = sdpvar(F(i));
n = size(Fi,1);
S = sdpvar(n,1);
% S = Slacks{i};
slack = Fi-S;
if is(slack,'complex')
F_AXb = F_AXb + (real(slack)==0) + (imag(slack)==0);
else
F_AXb = F_AXb + (slack==0);
end
F_CONE = F_CONE + (cone(S(2:end),S(1)));
shiftMatrix{end+1} = spalloc(n,1,0);
X{end+1}=S;
keep(i)=0;
elseif isVecSOCP(i)
% Vectorized SOC dual-form cone
Fi = sdpvar(F(i));
[n,m] = size(Fi);
S = sdpvar(n,m,'full');
slack = Fi-S;
if is(slack,'complex')
F_AXb = F_AXb + (real(slack)==0) + (imag(slack)==0);
else
F_AXb = F_AXb + (slack==0);
end
F_CONE = F_CONE + (cone(S));
shiftMatrix{end+1} = spalloc(n,m,0);
X{end+1}=S;
keep(i)=0;
end
end
% Now, remove all mixed cones...
F = F(find(keep));
% Get the equalities
AXbset = is(F,'equality');
if any(AXbset)
% Get the constraints
F_AXb = F_AXb + F(find(AXbset));
F = F(find(~AXbset));
end
% Is there something we missed in our tests?
if length(F)>0
error('DUALIZE can only treat standard SDPs (and LPs) at the moment.')
end
% If complex SDP cone, we reformulate and call again on a real-valued
% problem. This leads to twice the amount of work, but it is a quick fix
% for the moment
if any(is(F_CONE,'complexsdpcone'))
F_NEWCONES = [];
top = 1;
for i = 1:length(X)
if is(X{i},'complexsdpcone')
Xreplace{top} = X{i};
n = length(X{i});
Xnew{top} = sdpvar(2*n);
rQ = real(Xreplace{top});
iQ = imag( Xreplace{top});
L1 = Xnew{top}(1:n,1:n);
L3 = Xnew{top}(n+1:end,n+1:end);
L2 = Xnew{top}(1:n,n + 1:end);
s0r = getvariables(rQ);
s1r = getvariables(L1);
s2r = getvariables(L3);
r0 = recover(s0r);
r1 = recover(s1r);
r2 = recover(s2r);
s0i = getvariables(iQ);
s1i = getvariables(triu(L2,1))';
s2i = getvectorvariables(L2(find(tril(ones(length(L2)),-1))));
i0 = recover(s0i);
i1 = recover(s1i);
i2 = recover(s2i);
replacement = [r1+r2;i1-i2];
if ~isempty(F_AXb)
F_AXb = remap(F_AXb,[s0r s0i],replacement);
end
if ~isempty(obj)
obj = remap(obj,[s0r s0i],replacement);
end
X{i} = Xnew{top};
top = top + 1;
end
if is(X{i},'hermitian')
F_NEWCONES = [F_NEWCONES, X{i} >= 0];
else
F_NEWCONES = [F_NEWCONES, cone(X{i})];
end
end
F_reformulated = [F_NEWCONES, F_AXb, x>=0];
complexInfo.replaced = Xreplace;
complexInfo.new = Xnew;
[Fdual,objdual,X,t,err] = dualize(F_reformulated,obj,auto,extlp,extend);
return
end
% Sort the SDP cone variables X according to YALMIP
% This is just to simplify some indexing later
ns = [];
first_var = [];
for i = 1:length(F_CONE)
ns = [ns length(X{i})];
first_var = [first_var min(getvariables(X{i}))];
end
[sorted,index] = sort(first_var);
X={X{index}};
shiftMatrix={shiftMatrix{index}};
shift = [];
for i = 1:length(F_CONE)
ns(i) = length(X{i});
if size(X{i},2)==1 | (size(X{i},1) ~= size(X{i},2))
% SOCP
shift = [shift;shiftMatrix{i}(:)];
else
% SDP
ind = find(tril(reshape(1:ns(i)^2,ns(i),ns(i))));
shift = [shift;shiftMatrix{i}(ind)];
end
end
% Free variables (here called t) is everything except the cone variables
X_variables = getvariables(F_CONE);
x_variables = getvariables(x);
Xx_variables = [X_variables x_variables];
other_variables = [getvariables(obj) getvariables(F_AXb)];
% For quadratic case
%other_variables = [depends(obj) getvariables(F_AXb)];
all_variables = uniquestripped([other_variables Xx_variables]);
% Avoid set-diff
if isequal(all_variables,Xx_variables)
t_variables = [];
t_in_all = [];
t = [];
else
t_variables = setdiff(all_variables,Xx_variables);
ind = ismembcYALMIP(all_variables,t_variables);
t_in_all = find(ind);
t = recover(t_variables);
end
ind = ismembcYALMIP(all_variables,x_variables);
x_in_all = find(ind);
ind = ismembcYALMIP(all_variables,X_variables);
X_in_all = find(ind);
vecF1 = [];
nvars = length(all_variables);
for i = 1:length(F_AXb)
AXb = sdpvar(F_AXb(i));
mapper = find(ismembcYALMIP(all_variables,getvariables(AXb)));
[n,m] = size(AXb);
data = getbase(AXb);
[iF,jF,sF] = find(data);
if 1 % New
smapper = [1 1+mapper(:)'];
F_structemp = sparse(iF,smapper(jF),sF,n*m,1+nvars);
else
F_structemp = spalloc(n*m,1+nvars,nnz(data));
F_structemp(:,[1 1+mapper(:)'])= data;
end
vecF1 = [vecF1;F_structemp];
end
%Remove trivially redundant constraints
h = 1+rand(size(vecF1,2),1);
h = vecF1*h;
% INTVAL possibility
%[dummy,uniquerows] = uniquesafe(h);
[dummy,uniquerows] = uniquesafe(mid(h));
if length(uniquerows) < length(h)
% Sort to ensure run-to-run consistency
vecF1 = vecF1((sort(uniquerows)),:);
end
if isempty(obj)
vecF1(end+1,1) = 0;
else
if is(obj,'linear')
mapper = find(ismembcYALMIP(all_variables,getvariables(obj)));
[n,m] = size(obj);
data = getbase(obj);
[iF,jF,sF] = find(data);
if 1
smapper = [1 1+mapper(:)'];
F_structemp = sparse(iF,smapper(jF),sF,n*m,1+nvars);
else
F_structemp = spalloc(n*m,1+nvars,nnz(data));
F_structemp(:,[1 1+mapper(:)'])= data;
end
vecF1 = [vecF1;F_structemp];
else
% FIX: Generalize to QP duality
% min c'x+0.5x'Qx, Ax==b, x>=0
% max b'y-0.5x'Qx, c-A'y+Qx >=0
[Q,c,xreally,info] = quaddecomp(obj,recover(all_variables))
mapper = find(ismembcYALMIP(all_variables,getvariables(c'*xreally)));
[n,m] = size(c'*xreally);
data = getbase(c'*xreally);
F_structemp = spalloc(n*m,1+nvars,nnz(data));
F_structemp(:,[1 1+mapper(:)'])= data;
vecF1 = [vecF1;F_structemp]
end
end
vecF1(end+1,1) = 0;
Fbase = vecF1;
%Fbase = unique(Fbase','rows')';
b = Fbase(1:end-2,1);
Fbase = -Fbase(1:end-1,2:end);
vecA = [];
Fbase_t = Fbase(:,t_in_all);
Fbase_x = Fbase(:,x_in_all);
Fbase_X = Fbase;
%Fbase_X(:,unionstripped(t_in_all,x_in_all)) = [];
if 1
removethese = unique([t_in_all x_in_all]);
if length(removethese) > 0.5*size(Fbase_X,2)
Fbase_X = Fbase_X(:,setdiff(1:size(Fbase_X,2),removethese));
else
Fbase_X(:,[t_in_all x_in_all]) = [];
end
else
removecols = uniquestripped([t_in_all x_in_all]);
if ~isempty(removecols)
[i,j,k] = find(Fbase_X);
keep = find(~ismember(j,removecols));
i = i(keep);
k = k(keep);
j = j(keep);
map = find(1:length(unique(j)),j);
end
end
% Shift due to translated dual cones X = Z+shift
if length(shift > 0)
b = b + Fbase_X(1:end-1,:)*shift;
end
if length(x)>0
% Arrgh
base = getbase(x);
constant = base(:,1);
base = base(:,2:end);[i,j,k] = find(base);
b = b + Fbase_x(1:end-1,:)*constant(i);
end
start = 0;
n_cones = length(ns);
% All LPs in one cone
if length(x)>0
n_lp = 1;
else
n_lp = 0;
end
n_free = length(t_variables);
% SDP cones
for j = 1:1:n_cones
if size(X{j},1)==size(X{j},2)
% SDP cone
ind = reshape(1:ns(j)^2,ns(j),ns(j));
ind = find(tril(ind));
% Get non-symmetric constraint AiX=b
Fi = Fbase_X(1:length(b),start+(1:length(ind)))'/2;
if 1
[iF,jF,sF] = find(Fi);
iA = ind(iF);
jA = jF;
sA = sF;
the_col = 1+floor((iA-1)/ns(j));
the_row = iA-(the_col-1)*ns(j);
these_must_be_transposed = find(the_row > the_col);
if ~isempty(these_must_be_transposed)
new_rowcols = the_col(these_must_be_transposed) + (the_row(these_must_be_transposed)-1)*ns(j);
iA = [iA;new_rowcols];
jA = [jA;jA(these_must_be_transposed)];
sA = [sA;sA(these_must_be_transposed)];
end
% Fix diagonal term
diags = find(diag(1:ns(j)));
id = find(ismembcYALMIP(iA,diags));
sA(id) = 2*sA(id);
Ai = sparse(iA,jA,sA,ns(j)^2,length(b));
else % Old slooooooow version
Ai = spalloc(ns(j)^2,length(b),nnz(Fi));
Ai(ind,:) = Fi;
% Symmetrize
[rowcols,varindicies,vals]=find(Ai);
the_col = 1+floor((rowcols-1)/ns(j));
the_row = rowcols-(the_col-1)*ns(j);
these_must_be_transposed = find(the_row > the_col);
if ~isempty(these_must_be_transposed)
new_rowcols = the_col(these_must_be_transposed) + (the_row(these_must_be_transposed)-1)*ns(j);
Ai(sub2ind(size(Ai),new_rowcols,varindicies(these_must_be_transposed))) = vals(these_must_be_transposed);
end
% Fix diagonal term
diags = find(diag(1:ns(j)));
Ai(diags,:) = 2*Ai(diags,:);
end
% if norm(Ai-Ai2,inf)>1e-12
% error
% end
vecA{j} = Ai;
start = start + length(ind);
else
% Second order cone
ind = 1:prod(size(X{j}));
%ind = 1:ns(j);
% Get constraint AiX=b
Fi = Fbase_X(1:length(b),start+(1:length(ind)))';
%Ai = spalloc(ns(j),length(b),nnz(Fi));
Ai = spalloc(prod(size(X{j})),length(b),nnz(Fi));
Ai(ind,:) = Fi;
vecA{j} = Ai;
start = start + length(ind);
end
end
% LP Cone
if n_lp>0
Alp=Fbase_x(1:length(b),:)';
end
% FREE VARIABLES
start = 0;
if n_free>0
Afree=Fbase_t(1:length(b),:)';
end
% COST MATRIX
% SDP CONE
start = 0;
for j = 1:1:n_cones
if size(X{j},1)==size(X{j},2)
%ind = reshape(1:ns(j)^2,ns(j),ns(j));
%ind = find(tril(ind));
%C{j} = spalloc(ns(j),ns(j),0);
%C{j}(ind) = -Fbase_X(end,start+(1:length(ind)));
%C{j} = (C{j}+ C{j}')/2;
%start = start + length(ind);
ind = reshape(1:ns(j)^2,ns(j),ns(j));
[indi,indj] = find(tril(ind));
C{j} = sparse(indi,indj,-Fbase_X(end,start+(1:length(indi))),ns(j),ns(j));
C{j} = (C{j}+ C{j}')/2;
start = start + length(indi);
else
%ind = 1:ns(j);
ind = 1:prod(size(X{j}));
C{j} = spalloc(ns(j),1,0);
C{j}(ind) = -Fbase_X(end,start+(1:length(ind)));
start = start + length(ind);
end
end
% LP CONE
for j = 1:1:n_lp
Clp = -Fbase_x(end,:)';
end
% FREE CONE
if n_free>0
Cfree = -Fbase_t(end,1:end)';
end
% Create dual
if length(b) == 0
error('Dual program is somehow trivial (0 variables in dual)');
end
y = sdpvar(length(b),1);
yvars = getvariables(y);
cf = [];
Af = [];
Fdual = ([]);
for j = 1:n_cones
if size(X{j},1)==size(X{j},2)
% Yep, this is optimized...
S = sdpvar(ns(j),ns(j),[],yvars,[C{j}(:) -vecA{j}]);
% Fast call avoids symmetry check
Fdual = Fdual + lmi(S,[],[],[],1);
else
Ay = reshape(vecA{j}*y,[],1);
%Ay = reshape(vecA{j}*y,ns(j),1);
S = C{j}-Ay;
S = reshape(S,size(X{j},1),[]);
%Fdual = Fdual + lmi(cone(S(2:end),S(1)));
Fdual = Fdual + lmi(cone(S));
end
end
if n_lp > 0
keep = any(Alp,2);
if ~all(keep)
% Fix for unused primal cones
preset=find(~keep);
xfix = x(preset);
assign(xfix(:),Clp(preset(:)));
end
keep = find(keep);
if ~isempty(keep)
z = Clp(keep)-Alp(keep,:)*y;
if isa(z,'double')
assign(x(:),z(:));
else
Fdual = Fdual + lmi(z);
if ~isequal(keep,(1:length(x))')
x = x(keep);
end
X{end+1} = x(:); % We have worked with a row for performance reasons
end
end
end
if n_free > 0
CfreeAfreey = Cfree-Afree*y;
if isa(CfreeAfreey,'double')
if nnz(CfreeAfreey)>0
error('Trivially unbounded!');
end
else
Fdual = Fdual + (0 == CfreeAfreey);
end
end
objdual = b'*y;
if auto
for i = 1:length(X)
yalmip('associatedual',getlmiid(Fdual(i)),X{i});
end
if n_free>0
yalmip('associatedual',getlmiid(Fdual(end)),t);
end
end
if LogDetTerm
for i = 1:length(Plogdet)
objdual = objdual + logdet(sdpvar(Fdual(i))) + length(sdpvar(Fdual(1)));
end
Fdual = Fdual - Fdual(1:length(Plogdet));
end
Fdual = setdualize(Fdual,1);
function implicit_positive = detect_diagonal_terms(F)
F = F(find(is(F,'sdp')));
implicit_positive = [];
for i = 1:length(F)
Fi = sdpvar(F(i));
B = getbase(Fi);
n = sqrt(size(B,1));
d = 1:(n+1):n^2;
B = B(d,:);
candidates = find((B(:,1) == 0) & (sum(B | B,2) == 1) & (sum(B,2) == 1));
if ~isempty(candidates)
vars = getvariables(Fi);
[ii,jj,kk] = find(B(candidates,2:end)');
ii = ii(:)';
implicit_positive = [implicit_positive vars(ii)];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
polyprint.m
|
.m
|
LMI-Matlab-master/yalmip/extras/polyprint.m
| 2,602 |
utf_8
|
98455d0a41ce36cf7c72c346fa924f64
|
function symb_pvec = polyprint(pvec)
%POLYPRINT Pretty print polynomial expression
%
% POLYPRINT is obsolete. Use SDISPLAY instead.
for pi = 1:size(pvec,1)
for pj = 1:size(pvec,2)
p = pvec(pi,pj);
if isa(p,'double')
symb_p = num2str(p);
else
LinearVariables = depends(p);
x = recover(LinearVariables);
exponent_p = full(exponents(p,x));
names = cell(length(x),1);
W = evalin('caller','whos');
for i = 1:size(W,1)
if strcmp(W(i).class,'sdpvar')% | strcmp(W(i).class,'lmi')
thevars = evalin('caller',W(i).name) ;
if is(thevars,'scalar') & is(thevars,'linear') & length(getvariables(thevars))==1
index_in_p = find(ismember(LinearVariables,getvariables(thevars)));
if ~isempty(index_in_p)
names{index_in_p}=W(i).name;
end
end
end
end
symb_p = '';
if all(exponent_p(1,:)==0)
symb_p = num2str(full(getbasematrix(p,0)));
exponent_p = exponent_p(2:end,:);
end
for i = 1:size(exponent_p,1)
coeff = full(getbasematrixwithoutcheck(p,i));
switch coeff
case 1
coeff='+';
case -1
coeff = '-';
otherwise
if isreal(coeff)
if coeff >0
coeff = ['+' num2str2(coeff)];
else
coeff=[num2str2(coeff)];
end
else
coeff = ['+' '(' num2str2(coeff) ')' ];
end
end
symb_p = [symb_p coeff symbmonom(names,exponent_p(i,:))];
end
if symb_p(1)=='+'
symb_p = symb_p(2:end);
end
end
symb_pvec{pi,pj} = symb_p;
end
end
function s = symbmonom(names,monom)
s = '';
for j = 1:length(monom)
if abs( monom(j))>0
s = [s names{j}];
if monom(j)~=1
s = [s '^' num2str(monom(j))];
end
end
end
function s = num2str2(x)
s = num2str(full(x));
if isequal(s,'1')
s = '';
end
if isequal(s,'-1')
s = '-';
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdd.m
|
.m
|
LMI-Matlab-master/yalmip/extras/sdd.m
| 478 |
utf_8
|
1e88bdde340f1e917f70ca6ea28f36f3
|
function Constraint = sdd(X)
if issymmetric(X)
Constraint = [];
n = size(X,1);
M = 0;
for ii = 1:n
for jj = [1:1:ii-1 ii+1:1:n]
Mij = sdpvar(2);
Constraint = Constraint + sdp2socp(Mij);
M = M + sparse([ii jj ii jj],[ii ii jj jj],Mij(:),n,n);
end
end
Constraint = Constraint + [M == X];
else
error('sdd requires a symmetric argument.');
end
function F = sdp2socp(M)
F=rcone(M(1,2),.5*M(1,1),M(2,2));
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
variable_replace.m
|
.m
|
LMI-Matlab-master/yalmip/extras/variable_replace.m
| 2,976 |
utf_8
|
24789bb29ef27f6c6f2e20d6ea39217f
|
function Z = variable_replace(X,Y,W)
% Check so that Y is a simple unit variable
Ybase = getbase(Y);
Yvariables = getvariablesSORTED(Y);
Xbase = getbase(X);
Xvariables = getvariables(X);
[i,j,k] = find(Ybase);
if ~isequal(sort(i),1:length(i))
end
if ~isequal(sort(j),2:(length(i)+1))
end
if ~all(k == 1)
end
[mt,variabletype] = yalmip('monomtable');
% Linear, or at least linear in Y
if all(variabletype(Xvariables) == 0) %| all(sum(mt(any(mt(getvariables(X),getvariables(Y)),2),:),2)==1)
% Simple linear replacement
v = 1;
v1 = [];
v2 = [];
i1 = [];
i2 = [];
for i = 1:length(Xvariables)
XisinY = find(Xvariables(i) == Yvariables);
if ~isempty(XisinY)
% v = [v;W(XisinY)];
v1 = [v1 XisinY];
i1 = [i1 i];
else
% v = [v;recover(Xvariables(i))];
v2 = [v2 Xvariables(i)];
i2 = [i2 i];
end
end
v = sparse(i1,ones(length(i1),1),W(v1),length(Xvariables),1);
v = v + sparse(i2,ones(length(i2),1),recover(v2),length(Xvariables),1);
Z = Xbase*[1;v];
%Z = Xbase*[v];
Z = reshape(Z,size(X,1),size(X,2));
else
if nnz(mt(getvariables(X),getvariables(Y)))==0
Z = X;
else
Z = nonlinearreplace(X,Y,W);
end
return
% error('Nonlinear replacement not supported yet')
end
% This has not been tested (copied from variable_replace) so it is placed
% in a catch to be safe.
try
Xvariables = getvariables(Z);
extvar = yalmip('extvariables');
Xext = find(ismember(Xvariables,extvar));
if ~isempty(Xext)
%We must dig down in extended operators to see if they use the replaced
%set of variables
for i = 1:length(Xext)
extstruct = yalmip('extstruct',Xvariables(Xext(i)));
anychanged = 0;
for j = 1:length(extstruct.arg)
if isa(extstruct.arg{j},'sdpvar')
XinY = find(ismembc(getvariables(extstruct.arg{j}),Yvariables));
if ~isempty(XinY)
anychanged = 1;
extstruct.arg{j} = replace(extstruct.arg{j},Y,W);
else
end
end
end
if anychanged
Zi = yalmip('define',extstruct.fcn,extstruct.arg{:});
Xvariables(Xext(i)) = getvariables(Zi);
end
end
% And now recover this sucker
Z = struct(Z);
Z.lmi_variables = Xvariables;
% Messed up order (lmi_variables should be sorted)
if any(diff(Z.lmi_variables)<0)
[i,j]=sort(Z.lmi_variables);
Z.basis = [Z.basis(:,1) Z.basis(:,j+1)];
Z.lmi_variables = Z.lmi_variables(j);
end
Z = sdpvar(Z.dim(1),Z.dim(2),[],Z.lmi_variables,Z.basis);
end
catch
end
function Yvariables = getvariablesSORTED(Y);
Y = Y(:);
for i = 1:length(Y)
Yvariables(i) = getvariables(Y(i));
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
separable.m
|
.m
|
LMI-Matlab-master/yalmip/extras/separable.m
| 1,525 |
utf_8
|
10bbf0c3ce778c85f88b4dde2c05da0b
|
function exponent_m = separable(exponent_m,exponent_p,options);
%SEPARABLE Internal function, not used
% %exponent_m(sum((exponent_m>0),2)>2,:)=[];
%
% card = max(sum((exponent_p>0),2));
%
% n_less = exponent_m(sum((exponent_m>0),2)<card,:);
% n_equ = exponent_m(sum((exponent_m>0),2)==card,:);
% n_larg = exponent_m(sum((exponent_m>0),2)>card,:);
%
% A = minksum(n_less,n_less);
% B = minksum(n_less,n_equ);
% C = minksum(n_less,n_larg);
% D = minksum(n_equ,n_equ);
% E = minksum(n_equ,n_larg);
% F = minksum(n_larg,n_larg);
disconnected = [];
for i = 1:size(exponent_p,2)
for j = i+1:size(exponent_p,2)
if ~any(exponent_p(:,i) & exponent_p(:,j))
disconnected = [disconnected;i j];
end
end
end
for i = 1:size(disconnected,1)
j = disconnected(i,1);
k = disconnected(i,2);
n0 = find(~exponent_m(:,j) & ~exponent_m(:,k));
nx = find(exponent_m(:,j) & ~exponent_m(:,k));
nz = find(~exponent_m(:,j) & exponent_m(:,k));
nxz = find(exponent_m(:,j) & exponent_m(:,k));
% m0 = exponent_m(n0,:);
% mx = exponent_m(nx,:);
% mz = exponent_m(nz,:);
% mxz = exponent_m(nxz,:);
%
% from_E = minksum(mx,mz);
% from_B = minksum([m0;mx;mz],mxz);
% from_C = minksum(mxz,mxz);
% m_e = exponent_m(union(nx,nz),:)
% m_cb = exponent_m(union(nx,nz),:)
exponent_m = exponent_m([n0;nx;nz],:);
end
function msum = minksum(a,b);
msum = [];
for i = 1:size(a,1)
for j = i:size(b,1)
msum = [msum;a(i,:)+b(j,:)];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
convert_polynomial_to_sdpfun.m
|
.m
|
LMI-Matlab-master/yalmip/extras/convert_polynomial_to_sdpfun.m
| 5,293 |
utf_8
|
1282b1c3b7f96c19912ea8bbbc911873
|
function [model,changed] = convert_polynomial_to_sdpfun(model)
% Assume we don't do anything
changed = 0;
found_and_converted = [];
if any(model.variabletype > 2)
% Bugger...
changed = 1;
% Find a higher order term
sigmonials = find(model.variabletype == 3);
model = update_monomial_bounds(model);
monosig = sigmonials(find(sum(model.monomtable(sigmonials,:) | model.monomtable(sigmonials,:),2)==1));
if ~isempty(monosig)
% These are just monomial terms such as x^0.4 etc
for i = 1:length(monosig)
variable = find(model.monomtable(monosig(i),:));
power = model.monomtable(monosig(i),variable);
model = add_sigmonial_eval(model,monosig(i),variable,power)
found_and_converted = [found_and_converted;variable power monosig(i)];
end
end
end
if any(model.variabletype > 2)
% Bugger...we have mixed terms such as x/y etc
% Find a higher order term
sigmonials = find(model.variabletype == 3);
for i = 1:length(sigmonials)
n_old_monoms = size(model.monomtable,1);
monoms = model.monomtable(sigmonials(i),:);
sigs = find((monoms ~= fix(monoms)) | monoms<0);
powers = monoms(sigs);
if ~isempty(found_and_converted)
for j = 1:length(sigs)
old_index = findrows(found_and_converted(:,1:2),[sigs(j) powers(j)]);
if ~isempty(old_index)
corresponding_variable = found_and_converted(old_index,3);
model.monomtable(sigmonials(i),sigs(j)) = 0;
model.monomtable(sigmonials(i),corresponding_variable) = 1;
sigs(j)=nan;
end
end
end
powers(isnan(sigs)) = [];
sigs(isnan(sigs)) = [];
if length(sigs) > 0
% Terms left that haven't been modeled
model.monomtable(sigmonials(i),sigs) = 0;
model.monomtable = blkdiag(model.monomtable,speye(length(sigs)));
model.monomtable(sigmonials(i),n_old_monoms+1:n_old_monoms+length(sigs)) = 1;
model.variabletype(sigmonials(i)) = 3;
model.variabletype(end+1:end+length(sigs)) = 0;
model.c(end+1:end+length(sigs)) = 0;
model.Q = blkdiag(model.Q,zeros(length(sigs)));
model.F_struc = [model.F_struc zeros(size(model.F_struc,1),length(sigs))];
model.lb = [model.lb;-inf(length(sigs),1)];
model.ub = [model.ub;inf(length(sigs),1)];
model.x0 = [model.x0;model.x0(sigs).^powers(:)];
for j = 1:length(sigs)
model.evalVariables = [model.evalVariables n_old_monoms+j];
model.evalMap{end+1}.fcn = 'power_internal2';
model.evalMap{end}.arg{1} = recover(n_old_monoms+j);
model.evalMap{end}.arg{2} = powers(j);
model.evalMap{end}.arg{3} = [];
model.evalMap{end}.variableIndex = sigs(j);
model.evalMap{end}.properties.bounds = @power_bound;
model.evalMap{end}.properties.convexhull = @power_convexhull;
end
end
if sum(model.monomtable(sigmonials(i),:))<=2
if nnz(model.monomtable(sigmonials(i),:))==1
model.variabletype(sigmonials(i)) = 2;
else
model.variabletype(sigmonials(i)) = 1;
end
end
end
model = update_eval_bounds(model);
end
function model = add_sigmonial_eval(model,monosig,variable,power)
model.evalVariables = [model.evalVariables monosig];
model.evalMap{end+1}.fcn = 'power_internal2';
model.evalMap{end}.arg{1} = recover(variable);
model.evalMap{end}.arg{2} = power;
model.evalMap{end}.arg{3} = [];
model.evalMap{end}.variableIndex = find(model.monomtable(monosig,:));
model.evalMap{end}.properties.bounds = @power_bound;
model.evalMap{end}.properties.convexhull = @power_convexhull;
model.monomtable(monosig,variable) = 0;
model.monomtable(monosig,monosig) = 1;
model.variabletype(monosig) = 0;
% This should not be hidden here....
function [L,U] = power_bound(xL,xU,power)
if xL >= 0
% This is the easy case
if power > 0
L = xL^power;
U = xU^power;
else
L = xU^power;
U = xL^power;
end
else
if power < 0 & xU > 0
% Nasty crossing around zero
U = inf;
L = -inf;
else
if even(power)
L = 0;
U = max([xL^power xU^power]);
elseif even(power+1)
L = xL^power;
U = xU^power;
else
disp('Not implemented yet')
error
end
end
end
function [Ax, Ay, b] = power_convexhull(xL,xU,power)
x2 = (xL + xU)/4;
x1 = (3*xL + xU)/4;
x3 = (xL + 3*xU)/4;
fL = xL^power;
f1 = x1^power;
f2 = x2^power;
f3 = x3^power;
fU = xU^power;
dfL = power*xL^(power-1);
df1 = power*x1^(power-1);
df2 = power*x2^(power-1);
df3 = power*x3^(power-1);
dfU = power*xU^(power-1);
if power > 1 | power < 0
[Ax,Ay,b] = convexhullConvex(xL,x1,x2,x3,xU,fL,f1,f2,f3,fU,dfL,df1,df2,df3,dfU);
else
[Ax,Ay,b] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);
end
if ~isempty(Ax)
if isinf(Ax(1))
Ay(1) = 0;
Ax(1) = -1;
B(1) = 0;
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
apply_recursive_evaluation.m
|
.m
|
LMI-Matlab-master/yalmip/extras/apply_recursive_evaluation.m
| 3,378 |
utf_8
|
a9d54e9a0c8d81d0b492136a014b6007
|
function xevaled = apply_recursive_evaluation(p,xevaled)
xevaled = xevaled(:)';
for i = 1:length(p.evaluation_scheme)
switch p.evaluation_scheme{i}.group
case 'eval'
xevaled = process_evals(p,xevaled,p.evaluation_scheme{i}.variables);
case 'monom'
xevaled = process_monomials(p,xevaled,p.evaluation_scheme{i}.variables);
xevaled = real(xevaled);
otherwise
end
end
xevaled = xevaled(:);
function x = process_monomials(p,x,indicies);
indicies = p.monomials(indicies);
try
% Do bilinears and quadratics directly
if max(p.variabletype(indicies))==2
BilinearIndex = p.variabletype(indicies)==1;
if any(BilinearIndex)
Bilinears = indicies(BilinearIndex);
x(Bilinears) = x(p.BilinearsList(Bilinears,1)).*x(p.BilinearsList(Bilinears,2));
end
QuadraticIndex = p.variabletype(indicies)==2;
if any(QuadraticIndex)
Quadratics = indicies(QuadraticIndex);
x(Quadratics) = x(p.QuadraticsList(Quadratics,1)).^2;
end
else
% Mixed stuff. At least do bilinear and quadratics efficiently
BilinearIndex = p.variabletype(indicies)==1;
if any(BilinearIndex)
Bilinears = indicies(BilinearIndex);
x(Bilinears) = x(p.BilinearsList(Bilinears,1)).*x(p.BilinearsList(Bilinears,2));
indicies(BilinearIndex) = [];
end
QuadraticIndex = p.variabletype(indicies)==2;
if any(QuadraticIndex)
Quadratics = indicies(QuadraticIndex);
x(Quadratics) = x(p.QuadraticsList(Quadratics,1)).^2;
indicies(QuadraticIndex)=[];
end
V = p.monomtable(indicies,:);
r = find(any(V,1));
V = V(:,r);
x(indicies) = prod(repmat(x(r),length(indicies),1).^V,2);
end
catch
for i = indicies(:)'
x(i) = prod(x.^p.monomtable(i,:),2);
end
end
function x = process_evals(p,x,indicies)
if isfield(p.evalMap{1},'prearg')
for i = indicies
arguments = p.evalMap{i}.prearg;
arguments{1+p.evalMap{i}.argumentIndex} = x(p.evalMap{i}.variableIndex);
if isequal(arguments{1},'log') & (arguments{1+p.evalMap{i}.argumentIndex}<=0)
x(p.evalVariables(i)) = -1e4;
else
x(p.evalMap{i}.computes(:)) = feval(arguments{:});
end
end
else
for i = indicies
%arguments = {p.evalMap{i}.fcn,x(p.evalMap{i}.variableIndex)};
%arguments = {arguments{:},p.evalMap{i}.arg{2:end-1}};
% Append argument with function name, and remove trailing
% artificial argument
arguments = {p.evalMap{i}.fcn,p.evalMap{i}.arg{1:end-1}};
arguments{1+p.evalMap{i}.argumentIndex} = x(p.evalMap{i}.variableIndex);
if isequal(arguments{1},'log') & (arguments{1+p.evalMap{i}.argumentIndex}<=0)
x(p.evalVariables(i)) = -1e4; %FIXME DOES NOT WORK
if length(arguments{2})>1
disp('Report bug in apply_recursive_evaluation')
end
else
if isfield(p.evalMap{i},'computes')
x(p.evalMap{i}.computes) = feval(arguments{:});
else
x(p.evalVariables(i)) = feval(arguments{:});
end
end
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdpt3struct2sdpt3block.m
|
.m
|
LMI-Matlab-master/yalmip/extras/sdpt3struct2sdpt3block.m
| 1,867 |
utf_8
|
dc8d29d2e8699f12a49253ce3dc1c69d
|
function [C,A,b,blk] = sdpt3struct2sdpt3block(F_struc,c,K)
%SDPT3STRUCT2SDPT3BLOCK Internal function to convert data to SDPT3 format
nvars = size(F_struc,2)-1;
block = 1;
top = 1;
block = 1;
blksz = 100;
if K.l>0
blk{block,1} = 'l';
blk{block,2} = K.l;
C{block,1} = sparse(F_struc(top:top+K.l-1,1));
for var_index = 1:nvars
A{block,var_index} = -sparse(F_struc(top:top+K.l-1,var_index+1));
end
block = block+1;
top = top+sum(K.l);
end
if K.q>0
blk{block,1} = 'q';
blk{block,2} = K.q;
C{block,1} = sparse(F_struc(top:top+sum(K.q)-1,1));
for var_index = 1:nvars
A{block,var_index} = -sparse(F_struc(top:top+sum(K.q)-1,var_index+1));
end
block = block+1;
top = top+sum(K.q);
end
if K.s>0
constraints = 1;
while constraints<=length(K.s)
n = K.s(constraints);
Cvec = F_struc(top:top+n^2-1,1);
C{block,1} = reshape(Cvec,n,n);
for var_index = 1:nvars
Avec = -F_struc(top:top+n^2-1,var_index+1);
A{block,var_index} = reshape(Avec,n,n);
end
blk{block,1} = 's';
blk{block,2} = n;
top = top+n^2;
constraints = constraints+1;
sum_n = n;
while (sum_n<blksz) & (constraints<=length(K.s))
n = K.s(constraints);
Cvec = F_struc(top:top+n^2-1,1);
C{block,1} = blkdiag(C{block,1},reshape(Cvec,n,n));
[n1,m1] = size(A{block,var_index});
[n2,m2] = size(reshape(-F_struc(top:top+n^2-1,1+1),n,n));
Z = spalloc(n1,m2,0);
for var_index = 1:nvars
Avec = -F_struc(top:top+n^2-1,var_index+1);
A{block,var_index} = [A{block,var_index} Z;Z' reshape(Avec,n,n)];
end
blk{block,2} = [blk{block,2} n];
top = top+n^2;
sum_n = sum_n+n;
constraints = constraints+1;
end
block = block+1;
end
end
% And we solve dual...
b = -c(:);
% blkdiag with 2 sparse blocks
function y = blkdiag(x1,x2)
[n1,m1] = size(x1);
[n2,m2] = size(x2);
Z = spalloc(n1,m2,0);
y = [x1 Z;Z' x2];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
coefficients.m
|
.m
|
LMI-Matlab-master/yalmip/extras/coefficients.m
| 6,992 |
utf_8
|
071772bad3d379ac9c6bdfa2a59483c8
|
function [base,v] = coefficients(p,x,vin)
%COEFFICIENTS Extract coefficients and monomials from polynomials
%
% [c,v] = COEFFICIENTS(p,x) extracts the coefficents
% of a scalar polynomial p(x) = c'*v(x)
%
% c = COEFFICIENTS(p,x) extracts the all coefficents
% of a matrix polynomial.
%
% INPUT
% p : SDPVAR object
% x : SDPVAR object
%
% OUTPUT
% c : SDPVAR object
% v : SDPVAR object
%
% EXAMPLE
% sdpvar x y s t
% p = x^2+x*y*(s+t)+s^2+t^2; % define p(x,y), parameterized with s and t
% [c,v] = coefficients(p,[x y]);
% sdisplay([c v])
%
% See also SDPVAR
if isa(p,'double')
base = p(:);
v = 1;
return
end
if isa(p,'ncvar')
if isa(x,'ncvar')
error('Coefficients not applicable when x is non-commuting');
end
[base,v] = ncvar_coefficients(p,x);
return
end
if nargout>1 & (max(size(p))>1)
error('For matrix inputs, only the coefficients can be returned. Request feature if you need this...');
end
if nargin==1
allvar = depends(p);
xvar = allvar;
x = recover(xvar);
else
xvar = intersect(depends(x),depends(p));
end
% Try to debug this!
p = p(:);
base = [];
for i = 1:length(p)
allvar = depends(p(i));
t = setdiff(allvar,xvar);
if isa(p(i),'double')
base = [base;p(i)];
v = 1;
elseif isa(p(i),'sdpvar')
[exponent_p,p_base] = getexponentbase(p(i),recover(depends(p(i))));
ParametricIndicies = find(ismember(allvar,t));
% FIX : don't define it here, wait until sparser below. Speed!!
tempbase = parameterizedbase(p(i),[],recover(t),ParametricIndicies,exponent_p,p_base,allvar);
[i,j,k] = unique(full(exponent_p(:,find(~ismember(allvar,t)))),'rows');
V = sparse(1:length(k),k,1,length(tempbase),max(k))';
base = [base;V*tempbase];
if nargout == 2
keepthese = j(1:max(k));
v = recovermonoms(exponent_p(keepthese,find(~ismember(allvar,t))),recover(xvar));
end
elseif isa(p,'ncvar')
[exponent_p,ordered_list] = exponents(p,recover(depends(p(i))));
ParametricIndicies = find(ismember(allvar,t));
NotParametricIndicies = find(~ismember(allvar,t));
pars = recover(allvar(ParametricIndicies))';
nonpar = recover(allvar(NotParametricIndicies))';
NonParMonoms = exponent_p(:,NotParametricIndicies);
used = zeros(size(exponent_p,1),1);
for j = 1:size(exponent_p,1)
if ~used(j)
thisMonom = NonParMonoms(j);
thisMonom = 1;
for k = 1:max(find(ordered_list(j,:)))
thisMonom = thisMonom*recover(ordered_list(j,k));
end
thisBase = prod(ordered_list(j,nonpar));
end
end
for j = 1:length(ParametricIndicies)
a = find(ordered_list(:,1) == ParametricIndicies(j))
b = [];
for k = 1:length(a)
b = [b ordered_list(a(k),2:end)]
end
b = b(find(b));
basetemp = [];
for k = 1:length(b)
basetemp = [basetemp ncvar(struct(recover(t((k)))))];
end
base = [base;sum(basetemp)];
end
end
end
if nargout <= 1
v = [];
vin=v;
else
if nargin<3
vin=v;
end
end
if isequal(v,vin)
return
else
for i = 1:length(v)
if isa(v(i),'double')
si(i) = 0;
else
si(i) = getvariables(v(i));
end
end
for i = 1:length(vin)
if isa(vin(i),'double')
vi(i) = 0;
else
vi(i) = getvariables(vin(i));
end
end
newcvals = [];
if all(ismember(si,vi))
for i = 1:length(vin)
where = find(vi(i) == si);
if isempty(where)
newcvals = [newcvals;0];
%newc(i,1) = 0;
else
%newc(i,1) = base(where);
newcvals = [newcvals;base(where)];
end
end
newc = sparse(1:length(vin),ones(length(vin),1),newcvals);
else
error('The supplied basis is not sufficient');
end
base = newc(:);
v = vin(:);
end
function p_base_parametric = parameterizedbase(p,z, params,ParametricIndicies,exponent_p,p_base,allvar)
% Check for linear parameterization
parametric_basis = exponent_p(:,ParametricIndicies);
%if all(sum(parametric_basis,2)==0)
if all(all(parametric_basis==0))
p_base_parametric = full(p_base(:));
return
end
if all(ismember(parametric_basis,[0 1])) & all(sum(parametric_basis,2)<=1)%all(sum(parametric_basis,2)<=1)
p_base_parametric = full(p_base(:));
n = length(p_base_parametric);
ii = [];
vars = [];
js = sum(parametric_basis,1);
for i = 1:size(parametric_basis,2)
if js(i)
j = find(parametric_basis(:,i));
ii = [ii j(:)'];
vars = [vars repmat(i,1,js(i))];
end
end
k = setdiff1D(1:n,ii);
if isempty(k)
p_base_parametric = p_base_parametric.*sparse(ii,repmat(1,1,n),params(vars));
else
pp = params(vars); % Must do this, bug in ML 6.1 (x=sparse(1);x([1 1]) gives different result in 6.1 and 7.0!)
p_base_parametric = p_base_parametric.*sparse([ii k(:)'],repmat(1,1,n),[pp(:)' ones(1,1,length(k))]);
end
else
% Bummer, nonlinear parameterization sucks...
[mt,variabletype,hashedmonoms,hashkey] = yalmip('monomtable');
exponent_p_ParametricIndicies = exponent_p(:,ParametricIndicies);
LocalHash = exponent_p_ParametricIndicies*hashkey(allvar(ParametricIndicies));
[yn,loc] = ismember(LocalHash,hashedmonoms);
something = any(exponent_p_ParametricIndicies,2);
dummy = sdpvar(1);
for i = 1:length(p_base)
%j = find(exponent_p(i,ParametricIndicies));
% j = find(exponent_p_ParametricIndicies(i,:));
if something(i)%~isempty(j)
% temp = 1;%p_base(i);
% quickfind = findhashsorted(hashedmonoms, hashkey(ParametricIndicies(j))'*exponent_p(i,ParametricIndicies(j))');
quickfind = loc(i);
if (quickfind)
%temp = recover(quickfind);
temp = quickrecover(dummy,quickfind,p_base(i));
else
temp = p_base(i);
j = find(exponent_p_ParametricIndicies(i,:));
for k = 1:length(j)
if exponent_p(i,ParametricIndicies(j(k)))==1
temp = temp*params(j(k));
else
temp = temp*params(j(k))^exponent_p(i,ParametricIndicies(j(k)));
end
end
end
xx{i} = temp;
else
xx{i} = p_base(i);
end
end
p_base_parametric = stackcell(sdpvar(1,1),xx)';
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
shadowjacobian.m
|
.m
|
LMI-Matlab-master/yalmip/extras/shadowjacobian.m
| 2,364 |
utf_8
|
f46a1b7f9bb3d8e236fea4f759ca7036
|
function dfdx = shadowjacobian(f,x)
% See SDPVAR/jacobian
if isa(f,'double')
dfdx = zeros(size(f,1),length(x));
return
end
if ~isempty(intersect(deepdepends(f),depends(x)))
% Under development
end
if nargin==1
if isa(f,'sdpvar')
x = recover(depends(f));
else
x = 0;
end
else
if length(getvariables(x))<length(x)
error('x should be a vector of scalar independant variables');
end
end
[n,m]=size(f);
if m>1
error('Jacobian only defined for column vectors.')
end
if n*m==1
dfdx = scalar_jacobian(f,x);
% Argh, fix this (sorts inside scalar_jacobian
for i = 1:length(x)
var(i,1)=getvariables(x(i));
end
[i,j]=sort(var);
dfdx = dfdx(1,j);
return
else
dfdx = [];
AllVars = recover(unique([depends(f) getvariables(x)]));
for i = 1:length(f)
dfdx = [dfdx;scalar_jacobian(f(i),x,AllVars)];
end
% Argh, fix this (sorts inside scalar_jacobian
for i = 1:length(x)
var(i,1)=getvariables(x(i));
end
[i,j]=sort(var);
dfdx = dfdx(:,j);
end
function [dfdx,dummy] = scalar_jacobian(f,x,AllVars)
if isa(f,'double')
dfdx = zeros(1,length(x));
return
end
if nargin==2
AllVars = recover(uniquestripped([depends(f) getvariables(x)]));
%AllVars = recover(uniquestripped([deepdepends(f) depends(f) getvariables(x)]));
end
exponent_p = exponents(f,AllVars);
coefficients = getbase(f);
coefficients = coefficients(2:end);
coefficients = coefficients(:);
if nnz(exponent_p(1,:))==0
exponent_p=exponent_p(2:end,:);
end
x_variables = getvariables(x);
AllVars_variables = getvariables(AllVars);
%AllDeriv = [];
AllDeriv2 = [];
for k = 1:length(x)
wrt = find(ismembc(AllVars_variables,x_variables(k)));
deriv = exponent_p;
deriv(:,wrt) = deriv(:,wrt)-1;
keep{k} = find(deriv(:,wrt)~=-1);
AllDeriv2 = [AllDeriv2;deriv(keep{k},:)];
end
if size(AllDeriv2,1)==0
dummy = 1;
else
dummy = recovermonoms(AllDeriv2,AllVars);
end
top = 1;
dfdx=[];
for k = 1:length(x)
wrt = find(ismembc(AllVars_variables,x_variables(k)));
m = length(keep{k});
if m>0
poly = sum((coefficients(keep{k}(:)).*exponent_p(keep{k}(:),wrt)).*dummy(top:top+m-1),1);
top = top + m;
else
poly = 0;
end
dfdx = [dfdx ; poly];
end
dfdx = dfdx';
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
convert_sigmonial_to_sdpfun.m
|
.m
|
LMI-Matlab-master/yalmip/extras/convert_sigmonial_to_sdpfun.m
| 9,191 |
utf_8
|
56fb4a0deca7cfa0652142e2078fbb28
|
function [model,changed] = convert_sigmonial_to_sdpfun(model)
% Always add this dummy struct
model.high_monom_model = [];
% Assume we don't do anything
changed = 0;
found_and_converted = [];
if any(model.variabletype > 3)
% Bugger...
changed = 1;
% Find a higher order term
sigmonials = find(model.variabletype == 4);
model = update_monomial_bounds(model);
monosig = sigmonials(find(sum(model.monomtable(sigmonials,:) | model.monomtable(sigmonials,:),2)==1));
if ~isempty(monosig)
% These are just monomial terms such as x^0.4 etc
for i = 1:length(monosig)
variable = find(model.monomtable(monosig(i),:));
power = model.monomtable(monosig(i),variable);
model = add_sigmonial_eval(model,monosig(i),variable,power);
found_and_converted = [found_and_converted;variable power monosig(i)];
end
end
end
if any(model.variabletype > 3)
% Bugger...we have mixed terms such as x/y etc
% Find a higher order term
sigmonials = find(model.variabletype == 4);
for i = 1:length(sigmonials)
n_old_monoms = size(model.monomtable,1);
monoms = model.monomtable(sigmonials(i),:);
% Which variables have fractional or negative powers
sigs = find((monoms ~= fix(monoms)) | monoms<0);
powers = monoms(sigs);
if ~isempty(found_and_converted)
% Maybe some of the terms have already been defined as new
% variables
for j = 1:length(sigs)
old_index = findrows(found_and_converted(:,1:2),[sigs(j) powers(j)]);
if ~isempty(old_index)
corresponding_variable = found_and_converted(old_index,3);
model.monomtable(sigmonials(i),sigs(j)) = 0;
model.monomtable(sigmonials(i),corresponding_variable) = 1;
sigs(j)=nan;
end
end
end
powers(isnan(sigs)) = [];
sigs(isnan(sigs)) = [];
if length(sigs) > 0
% Terms left that haven't been modeled
model.monomtable(sigmonials(i),sigs) = 0;
model.monomtable = blkdiag(model.monomtable,speye(length(sigs)));
model.monomtable(sigmonials(i),n_old_monoms+1:n_old_monoms+length(sigs)) = 1;
model.variabletype(sigmonials(i)) = 3;
model.variabletype(end+1:end+length(sigs)) = 0;
model.c(end+1:end+length(sigs)) = 0;
model.Q = blkdiag(model.Q,zeros(length(sigs)));
model.F_struc = [model.F_struc zeros(size(model.F_struc,1),length(sigs))];
model.lb = [model.lb;-inf(length(sigs),1)];
model.ub = [model.ub;inf(length(sigs),1)];
if ~isempty(model.x0)
model.x0 = [model.x0;model.x0(sigs).^powers(:)];
end
for j = 1:length(sigs)
model.evalVariables = [model.evalVariables n_old_monoms+j];
model.isevalVariable(model.evalVariables)=1;
if powers(j)==-1
model.evalMap{end+1} = inverse_internal2_operator(model,sigs(j),n_old_monoms+j);
else
model.evalMap{end+1} = power_internal2_operator(model,sigs(j),powers(j));
end
model.evalMap{end}.properties.domain = [-inf inf];
model.evalMap{end}.variableIndex = sigs(j);
model.evalMap{end}.argumentIndex = 1;
model.evalMap{end}.computes = n_old_monoms+j;
found_and_converted = [found_and_converted;sigs(j) powers(j) n_old_monoms+j];
end
end
if sum(model.monomtable(sigmonials(i),:))<=2
if nnz(model.monomtable(sigmonials(i),:))==1
model.variabletype(sigmonials(i)) = 2;
else
model.variabletype(sigmonials(i)) = 1;
end
end
end
model = update_eval_bounds(model);
for i = 1:length(model.evalMap)
if isequal(model.evalMap{i}.fcn,'power_internal2')
if isequal(model.evalMap{i}.arg{2},-1)
if model.lb(model.evalMap{i}.variableIndex) > 0
model.evalMap{i}.properties.convexity = 'convex';
model.evalMap{i}.properties.monotonicity='decreasing';
model.evalMap{i}.properties.inverse=@(x)1./x;
elseif model.ub(model.evalMap{i}.variableIndex) < 0
model.evalMap{i}.properties.convexity = 'concave';
model.evalMap{i}.properties.monotonicity='increasing';
model.evalMap{i}.properties.inverse=@(x)1./x;
end
end
end
end
end
function model = add_sigmonial_eval(model,monosig,variable,power)
model.evalVariables = [model.evalVariables monosig];
model.isevalVariable(model.evalVariables)=1;
if power == -1
model.evalMap{end+1} = inverse_internal2_operator(model,variable,variable);
else
model.evalMap{end+1} = power_internal2_operator(model,variable,power);
end
model.evalMap{end}.variableIndex = find(model.monomtable(monosig,:));
model.evalMap{end}.argumentIndex = 1;
model.evalMap{end}.computes = monosig;
model.monomtable(monosig,variable) = 0;
model.monomtable(monosig,monosig) = 1;
model.variabletype(monosig) = 0;
% This should not be hidden here....
function [L,U] = power_bound(xL,xU,power)
if xL >= 0
% This is the easy case
% we use abs since 0 sometimes actually is -0 but still passes the test
% above
if power > 0
L = abs(xL)^power;
U = abs(xU)^power;
else
L = abs(xU)^power;
U = abs(xL)^power;
end
else
if power < 0 & xU > 0
% Nasty crossing around zero
U = inf;
L = -inf;
elseif xU < 0
L = xU^power;
U = xL^power;
else
disp('Not implemented yet')
error
end
end
function [L,U] = inverse_bound(xL,xU)
if xL >= 0
% This is the easy case. We use abs since 0 sometimes actually is -0
% but still passes the test above
L = abs(xU)^-1;
U = abs(xL)^-1;
else
if xU > 0
% Nasty crossing around zero
U = inf;
L = -inf;
elseif xU < 0
L = xU^-1;
U = xL^-1;
else
disp('Not implemented yet')
error
end
end
function [Ax, Ay, b] = power_convexhull(xL,xU,power)
fL = xL^power;
fU = xU^power;
dfL = power*xL^(power-1);
dfU = power*xU^(power-1);
if xL<0 & xU>0
% Nasty crossing
Ax = [];
Ay = [];
b = [];
return
end
average_derivative = (fU-fL)/(xU-xL);
xM = (average_derivative/power).^(1/(power-1));
if xU < 0
xM = -xM;
end
fM = xM^power;
dfM = power*xM^(power-1);
if ((power > 1 | power < 0) & (xL >=0)) | ((power < 1 & power > 0) & (xU <=0))
[Ax,Ay,b] = convexhullConvex(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
else
[Ax,Ay,b] = convexhullConcave(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
end
if ~isempty(Ax)
if isinf(Ax(1))
Ay(1) = 0;
Ax(1) = -1;
B(1) = 0;
end
end
function [Ax, Ay, b] = inverse_convexhull(xL,xU)
fL = xL^-1;
fU = xU^-1;
dfL = -1*xL^(-2);
dfU = -1*xU^(-2);
if xL<0 & xU>0
% Nasty crossing
Ax = [];
Ay = [];
b = [];
return
end
average_derivative = (fU-fL)/(xU-xL);
xM = (average_derivative/(-1)).^(1/(-1-1));
if xU < 0
xM = -xM;
end
fM = xM^(-1);
dfM = (-1)*xM^(-2);
if xL >= 0
[Ax,Ay,b] = convexhullConvex(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
else
[Ax,Ay,b] = convexhullConcave(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
end
if ~isempty(Ax)
if isinf(Ax(1))
Ay(1) = 0;
Ax(1) = -1;
B(1) = 0;
end
end
function df = power_derivative(x,power)
fL = xL^power;
fU = xU^power;
dfL = power*xL^(power-1);
dfU = power*xU^(power-1);
if xL<0 & xU>0
% Nasty crossing
Ax = [];
Ay = [];
b = [];
return
end
if power > 1 | power < 0
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
else
[Ax,Ay,b] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);
end
if ~isempty(Ax)
if isinf(Ax(1))
Ay(1) = 0;
Ax(1) = -1;
B(1) = 0;
end
end
function f = inverse_internal2_operator(model,variable,in);
f.fcn = 'inverse_internal2';
f.arg{1} = recover(in);
f.arg{2} = [];
f.properties.bounds = @inverse_bound;
f.properties.convexhull = @inverse_convexhull;
f.properties.derivative = @(x) -1./(x.^2);
if model.lb(variable)>0 | model.ub(variable) < 0
f.properties.monotonicity = 'decreasing';
f.properties.inverse = @(x)(1./x);
end
if model.lb(variable) >= 0
f.properties.convexity = 'convex';
elseif model.ub(variable) <= 0
f.properties.convexity = 'concave';
end
function f = power_internal2_operator(model,variable,power);
f.fcn = 'power_internal2';
f.arg{1} = recover(variable);
f.arg{2} = power;
f.arg{3} = [];
f.properties.bounds = @power_bound;
f.properties.convexhull = @power_convexhull;
f.properties.derivative = eval(['@(x) ' num2str(power) '*x.^(' num2str(power) '-1);']);
if even(power)
f.properties.range = [0 inf];
else
f.properties.range = [-inf inf];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
expandmodel.m
|
.m
|
LMI-Matlab-master/yalmip/extras/expandmodel.m
| 14,898 |
utf_8
|
d969c77d2766c9985e6935c762569593
|
function [F,failure,cause,ALREADY_MODELLED] = expandmodel(F,h,options,w)
% FIX : Current code experimental, complex, conservative, has issues with
% nonlinearities and is slow...
%
% If it wasn't for polynomials and sigmonials, it would be trivial, but the
% code is extremely messy since we want to have this functionality too
global LUbounds
global ALREADY_MODELLED
global MARKER_VARIABLES
global DUDE_ITS_A_GP
global ALREADY_MODELLED
global ALREADY_MODELLED_INDEX
global REMOVE_THESE_IN_THE_END
global OPERATOR_IN_POLYNOM
global CONSTRAINTCUTSTATE
% All extended variables in the problem. It is expensive to extract this
% one so we will keep it and pass it along in the recursion
extendedvariables = yalmip('extvariables');
% We keep track of all auxilliary variables introduced by YALMIP
nInitial = yalmip('nvars');
boundsAlreadySet = 0;
% Meta constraints are expanded first (iff, implies, alldifferent etc)
if ~isempty(F)
meta = find(is(F,'meta'));
if ~isempty(meta)
LUbounds=setupBounds(F,options,extendedvariables);
boundsAlreadySet = 1;
F = expandmeta(F);
end
end
if isa(F,'constraint')
F = lmi(F);
end
if nargin < 3
options = sdpsettings;
end
if isempty(options)
options = sdpsettings;
end
if isfield(options,'reusemodel')
else
ALREADY_MODELLED = [];
% Temporary hack to deal with a bug in CPLEX. For the implies operator (and
% some more) YALMIP creates a dummy variable x with (x==1). Cplex fails
% to solve problem with these stupid variables kept, hence we need to
% remove these variables and constraints...
MARKER_VARIABLES = [];
% Temporary hack to deal with geometric programs. GPs are messy here,
% becasue we can by mistake claim nonconvexity, since we may have no
% sigmonial terms but indefinite quadratic term, but the whole problem is
% meant to be solved using a GP solver. YES, globals suck, but this is
% only temporary...hrm.
DUDE_ITS_A_GP = 0;
% Keep track of expressions that already have been modelled. Note that if a
% graph-model already has been constructed but we now require a milp, for
% numerical reasons, we should remove the old graph descriptions (important
% for MPT models in particular)
% FIX: Pre-parse the whole problem etc (solves the issues with GP also)
ALREADY_MODELLED = {};
ALREADY_MODELLED_INDEX = [];
REMOVE_THESE_IN_THE_END = [];
% Nonlinear operator variables are not allowed to be used in polynomial
% expressions, except if they are exactly modelled, i.e. modelled using
% MILP models. We will expand the model and collect variables that are in
% polynomials, and check in the end if they are exaclty modelled
OPERATOR_IN_POLYNOM = [];
end
% Assume success
failure = 0;
cause = '';
% Early bail out
if isempty(extendedvariables)
return
end
if nargin < 4
w = [];
end
if isempty(F) & isempty(h)
return
end
% Check if it already has ben expanded in robustify or similar
F_alreadyexpanded = [];
if ~isempty(F)
F_alreadyexpanded = [];
already_expanded = expanded(F);
if all(already_expanded)
if isempty(setdiff(getvariables(h),expanded(h)))
return
end
elseif any(already_expanded)
F_alreadyexpanded = F(find(already_expanded));
F = F(find(~already_expanded));
end
end
if ~isempty(F)
% Extract all simple bounds from the model, and update the internal bounds
% in YALMIP. This is done in order to get tighter big-M models
if boundsAlreadySet == 0;
LUbounds = setupBounds(F,options,extendedvariables);
end
% Expand equalities first, since these might generate nonconvex models,
% thus making it unnecessaryu to generate epigraphs etc
equalities = is(F,'equality');
if any(equalities)
F = [F(find(equalities));F(find(~equalities))];
end
end
% All variable indicies used in the problem
v1 = getvariables(F);
v2 = depends(F);
v3 = getvariables(h);
v4 = depends(h);
% HACK: Performance for LARGE-scale dualizations
if isequal(v3,v4) & isequal(v1,v2)
variables = uniquestripped([v1 v3]);
else
variables = uniquestripped([v1 v2 v3 v4]);
end
% Index to variables modeling operators
extended = find(ismembcYALMIP(variables,extendedvariables));
if nargin < 3
options = sdpsettings;
end
% This is a tweak to allow epxansion of bilinear terms in robust problems,
% is expression such as abs(x*w) < 1 for all -1 < w < 1
% This field is set to 1 in robustify and tells YALMIP to skip checking for
% polynomial nonconvexity in the propagation
if ~isfield(options,'expandbilinear')
options.expandbilinear = 0;
end
% Monomial information. Expensive to retrieve, so we pass this along
[monomtable,variabletype] = yalmip('monomtable');
% Is this trivially a GP, or meant to be at least?
if strcmpi(options.solver,'gpposy') | strcmpi(options.solver,'fmincon-geometric') | strcmpi(options.solver,'mosek-geometric')
DUDE_ITS_A_GP = 1;
else
if ~isequal(options.solver,'fmincon') & ~isequal(options.solver,'snopt') & ~isequal(options.solver,'ipopt') & ~isequal(options.solver,'') & ~isequal(options.solver,'mosek')
% User has specified some other solver, which does not
% support GPs, hence it cannot be intended to be a GP
DUDE_ITS_A_GP = 0;
else
% Check to see if there are any sigmonial terms on top-level
DUDE_ITS_A_GP = ~isempty(find(variabletype(variables) == 4));
end
end
% Constraints generated during recursive process to model operators
F_expand = ([]);
if isempty(F)
F = ([]);
end
% First, check the objective
variables = uniquestripped([depends(h) getvariables(h)]);
monomtable = monomtable(:,extendedvariables);
% However, some of the variables are already expanded (expand can be called
% sequentially from solvemp and solverobust)
variables = setdiff1D(variables,expanded(h));
% Determine if we should aim for MILP/EXACT model directly
if options.allowmilp == 2
method = 'exact';
else
method = 'graph';
end
if DUDE_ITS_A_GP == 1
options.allowmilp = 0;
method = 'graph';
end
% Test for very common special case with only norm expression
ExtendedMap = yalmip('extendedmap');
fail = 0;
if 0%length(ExtendedMap) > 0 && all(strcmp('norm',{ExtendedMap.fcn}))
for i = 1:length(ExtendedMap)
if ~isequal(ExtendedMap(i).arg{2},2)
fail = 1;
break;
end
if ~isreal(ExtendedMap(i).arg{1})
fail = 1;
break;
end
if any(ismembcYALMIP(getvariables(ExtendedMap(i).arg{1}),extendedvariables))
fail = 1;
break;
end
end
for i = 1:length(ExtendedMap)
F_expand = [F_expand, cone(ExtendedMap(i).arg{1},ExtendedMap(i).var)];
end
F = F + lifted(F_expand,1);
return
end
% *************************************************************************
% OK, looks good. Apply recursive expansion on the objective
% *************************************************************************
index_in_extended = find(ismembcYALMIP(variables,extendedvariables));
allExtStructs = yalmip('extstruct');
if ~isempty(index_in_extended)
[F_expand,failure,cause] = expand(index_in_extended,variables,h,F_expand,extendedvariables,monomtable,variabletype,'objective',0,options,method,[],allExtStructs,w);
end
% *************************************************************************
% Continue with constraints
% *************************************************************************
constraint = 1;
all_extstruct = yalmip('extstruct');
while constraint <=length(F) & ~failure
if ~already_expanded(constraint)
Fconstraint = F(constraint);
variables = uniquestripped([depends(Fconstraint) getvariables(Fconstraint)]);
% If constraint is a cut, all generated constraints must be marked
% as cuts too
CONSTRAINTCUTSTATE = getcutflag(Fconstraint);
[ix,jx,kx] = find(monomtable(variables,:));
if ~isempty(jx) % Bug in 6.1
if any(kx>1)
OPERATOR_IN_POLYNOM = [OPERATOR_IN_POLYNOM extendedvariables(jx(find(kx>1)))];
end
end
index_in_extended = find(ismembcYALMIP(variables,extendedvariables));
if ~isempty(index_in_extended)
if is(Fconstraint,'equality')
if options.allowmilp | options.allownonconvex
[F_expand,failure,cause] = expand(index_in_extended,variables,-sdpvar(Fconstraint),F_expand,extendedvariables,monomtable,variabletype,['constraint #' num2str(constraint)],0,options,'exact',[],allExtStructs,w);
else
failure = 1;
cause = ['integer model required for equality in constraint #' num2str(constraint)];
end
else
[F_expand,failure,cause] = expand(index_in_extended,variables,-sdpvar(Fconstraint),F_expand,extendedvariables,monomtable,variabletype,['constraint #' num2str(constraint)],0,options,method,[],allExtStructs,w);
end
end
end
constraint = constraint+1;
end
CONSTRAINTCUTSTATE = 0;
% *************************************************************************
% Temporary hack to fix the implies operator (cplex has some problem on
% these trivial models where a variable only is used in x==1
% FIX: Automatically support this type of nonlinear operators
% *************************************************************************
if ~isempty(MARKER_VARIABLES)
MARKER_VARIABLES = sort(MARKER_VARIABLES);
equalities = find(is(F,'equality'));
equalities = equalities(:)';
remove = [];
for j = equalities
v = getvariables(F(j));
if length(v)==1
if ismembcYALMIP(v,MARKER_VARIABLES)
remove = [remove j];
end
end
end
if ~isempty(remove)
F(remove) = [];
end
end
nNow = yalmip('nvars');
if nNow > nInitial
% YALMIP has introduced auxilliary variables
% We mark these as auxilliary
yalmip('addauxvariables',nInitial+1:nNow);
end
F_expand = lifted(F_expand,1);
% *************************************************************************
% We are done. We might have generated some stuff more than once, but
% luckily we keep track of these mistakes and remove them in the end (this
% happens if we have constraints like (max(x)<1) + (max(x)>0) where
% the first constraint would genrate a graph-model but the second set
% creates a integer model.
% *************************************************************************
if ~failure
F = F + F_expand;
if length(REMOVE_THESE_IN_THE_END) > 0
F = F(find(~ismember(getlmiid(F),REMOVE_THESE_IN_THE_END)));
end
end
% *************************************************************************
% Normally, operators are not allowed in polynomial expressions. We do
% however allow this if the variable has been modelled with an exact MILP
% model.
% *************************************************************************
if ~failure
dummy = unique(OPERATOR_IN_POLYNOM);
if ~isempty(dummy)
for i = 1:length(dummy)
aux(i,1) = find(ALREADY_MODELLED_INDEX == dummy(i));
end
% Final_model = {ALREADY_MODELLED{unique(OPERATOR_IN_POLYNOM)}};
Final_model = {ALREADY_MODELLED{aux}};
for i = 1:length(Final_model)
if ~(strcmp(Final_model{i}.method,'integer') | strcmp(Final_model{i}.method,'exact') | options.allownonconvex)
failure = 1;
cause = 'Nonlinear operator in polynomial expression.';
return
end
end
end
end
% Append the previously appended
F = F + F_alreadyexpanded;
% Declare this model as expanded
F = expanded(F,1);
function [F_expand,failure,cause] = expand(index_in_extended,variables,expression,F_expand,extendedvariables,monomtable,variabletype,where,level,options,method,extstruct,allExtStruct,w)
global DUDE_ITS_A_GP ALREADY_MODELLED ALREADY_MODELLED_INDEX REMOVE_THESE_IN_THE_END OPERATOR_IN_POLYNOM
% *************************************************************************
% Go through all parts of expression to check for convexity/concavity
% First, a small gateway function before calling the recursive stuff
% *************************************************************************
if ~DUDE_ITS_A_GP
[ix,jx,kx] = find(monomtable(variables,:));
if ~isempty(jx) % Bug in 6.1
if any(kx>1)
OPERATOR_IN_POLYNOM = [OPERATOR_IN_POLYNOM extendedvariables(jx(find(kx>1)))];
end
end
end
failure = 0;
j = 1;
try
% Optimized for 6.5 and higher (location in ismember). If user has
% older version, it will crash and go to code below
expression_basis = getbase(expression);
expression_vars = getvariables(expression);
[yesno,location] = ismember(variables(index_in_extended),expression_vars);
ztemp = recover(variables(index_in_extended));
while j<=length(index_in_extended) & ~failure
% i = index_in_extended(j);
% zi = recover(variables(i));
zi = ztemp(j);%recover(variables(i));
basis = expression_basis(:,1 + location(j));
if all(basis == 0) % The nonlinear term is inside a monomial
if options.allownonconvex
[F_expand,failure,cause] = expandrecursive(zi,F_expand,extendedvariables,monomtable,variabletype,where,level+1,options,'exact',[],'exact',allExtStruct,w);
else
failure = 1;
cause = 'Possible nonconvexity due to operator in monomial';
end
%[F_expand,failure,cause] = expandrecursive(zi,F_expand,extendedvariables,monomtable,variabletype,where,level+1,options,method,[],'exact',allExtStruct,w);
elseif all(basis >= 0)
[F_expand,failure,cause] = expandrecursive(zi,F_expand,extendedvariables,monomtable,variabletype,where,level+1,options,method,[],'convex',allExtStruct,w);
else
[F_expand,failure,cause] = expandrecursive(zi,F_expand,extendedvariables,monomtable,variabletype,where,level+1,options,method,[],'concave',allExtStruct,w);
end
j=j+1;
end
catch
while j<=length(index_in_extended) & ~failure
i = index_in_extended(j);
basis = getbasematrix(expression,variables(i));
if all(basis >= 0)
[F_expand,failure,cause] = expandrecursive(recover(variables(i)),F_expand,extendedvariables,monomtable,variabletype,where,level+1,options,method,[],'convex',allExtStruct,w);
else
[F_expand,failure,cause] = expandrecursive(recover(variables(i)),F_expand,extendedvariables,monomtable,variabletype,where,level+1,options,method,[],'concave',allExtStruct,w);
end
j=j+1;
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
loadsedumidata.m
|
.m
|
LMI-Matlab-master/yalmip/extras/loadsedumidata.m
| 2,549 |
utf_8
|
bd6523935b1fd7c5c70b5bf8db27e0a7
|
function [F,h] = loadsedumidata(varargin)
%LOADSEDUMIDATA Loads a problem definition in the SeDuMi format
%
% [F,h] = loadsedumidata('filename') Loads the problem min(h(x)), F(x)>0 from file 'filename'
% [F,h] = loadsedumidata An "Open" - box will be opened
filename = varargin{1};
% Does the file exist
if ~exist(filename)
filename = [filename '.mat'];
if ~exist(filename)
error(['No such file.']);
end
end
load(filename)
try
if ~exist('At')
At = A;
end
if ~exist('b')
b = zeros(size(At,1),1);
else
b = b(:);
end
if ~exist('c')
if exist('C')
c = C(:);
else
c = zeros(size(At,2),1);
end
else
c = c(:);
end
K = K;
catch
error('The file should contain the data At, b, c and K');
end
nvars = length(b);
x = sdpvar(nvars,1);
% No reason to try to do factor tracking here
x = flush(x);
if size(At,2)~=length(b)
At = At';
end
F = ([]);
top = 1;
if isvalidfield(K,'f')
X = c(top:top+K.f-1)-At(top:top+K.f-1,:)*x;
F = F + (X(:) == 0);
top = top + K.f;
end
if isvalidfield(K,'l')
X = c(top:top+K.l-1)-At(top:top+K.l-1,:)*x;
F = F + (X(:)>=0);
top = top + K.l;
end
if isvalidfield(K,'q')
for i = 1:length(K.q)
X = c(top:top+K.q(i)-1)-At(top:top+K.q(i)-1,:)*x;
F = F + (cone(X(2:end),X(1)));
top = top + K.q(i);
end
end
if isvalidfield(K,'r')
for i = 1:length(K.r)
X = c(top:top+K.r(i)-1)-At(top:top+K.r(i)-1,:)*x;
F = F + (rcone(X(3:end),X(2),X(1)));
top = top + K.r(i);
end
end
if isvalidfield(K,'s')
for i = 1:length(K.s)
[ix,iy,iv] = find([c(top:top+K.s(i)^2-1) At(top:top+K.s(i)^2-1,:)]);
off = (ix-1)/(K.s(i)+1);
if all(off == round(off))
X = c(top:top+K.s(i)^2-1)-At(top:top+K.s(i)^2-1,:)*x;
if isa(X,'sdpvar')
F = F + (diag(reshape(X,K.s(i),K.s(i))) >= 0);
else
X
i
'silly data!'
end
top = top + K.s(i)^2;
else
X = c(top:top+K.s(i)^2-1)-At(top:top+K.s(i)^2-1,:)*x;
X = reshape(X,K.s(i),K.s(i));
X = (X+X')/2;
F = F + (X >= 0);
top = top + K.s(i)^2;
end
end
end
h = -b'*x;
function ok = isvalidfield(K,fld)
ok = 0;
if isfield(K,fld)
s = getfield(K,fld);
if prod(size(s))>0
if s(1)>0
ok = 1;
end
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
convert_polynomial_to_quadratic.m
|
.m
|
LMI-Matlab-master/yalmip/extras/convert_polynomial_to_quadratic.m
| 6,093 |
utf_8
|
e42036044ee1903d0c693160c460a838
|
function [model,changed] = convert_polynomial_to_quadratic(model)
% Assume we don't do anything
changed = 0;
% Are there really any non-quadratic terms?
already_done = 0;
while any(model.variabletype > 2)
% Bugger...
changed = 1;
% Find a higher order term
polynomials = find(model.variabletype >= 3);
model = update_monomial_bounds(model,(already_done+1):size(model.monomtable,1));
already_done = size(model.monomtable,1);
% Start with the highest order monomial (the bilinearization is not
% unique, but by starting here, we get a reasonable small
% bilineared model
[i,j] = max(sum(abs(model.monomtable(polynomials,:)),2));
polynomials = polynomials(j);
powers = model.monomtable(polynomials,:);
if any(powers < 0)
model = eliminate_sigmonial(model,polynomials,powers);
elseif nnz(powers) == 1
model = bilinearize_recursive(model,polynomials,powers);
else
model = bilinearize_recursive(model,polynomials,powers);
end
end
function model = eliminate_sigmonial(model,polynomial,powers);
% Silly bug
if isempty(model.F_struc)
model.F_struc = zeros(0,length(model.c) + 1);
end
% x^(-p1)*w^(p2)
powers_pos = powers;
powers_neg = powers;
powers_pos(powers_pos<0) = 0;
powers_neg(powers_neg>0) = 0;
[model,index_neg] = findoraddlinearmonomial(model,-powers_neg);
if any(powers_pos)
[model,index_pos] = findoraddlinearmonomial(model,powers_pos);
else
index_pos = [];
end
% Now create a new variable y, used to model x^(-p1)*w^(p2)
% We will also add the constraint y*x^p1 = w^p2
model.monomtable(polynomial,:) = 0;
model.monomtable(polynomial,polynomial) = 1;
model.variabletype(polynomial) = 0;
model.high_monom_model = blockthem(model.high_monom_model,[polynomial powers_neg]);;
if ~isempty(model.x0);
model.x0(polynomial) = prod(model.x0(find(powers_neg))'.^powers_neg);
end
powers = -powers_neg;
powers(polynomial) = 1;
[model,index_xy] = findoraddmonomial(model,powers);
model.lb(index_xy) = 1;
model.ub(index_xy) = 1;
model = convert_polynomial_to_quadratic(model);
function model = bilinearize_recursive(model,polynomial,powers);
% Silly bug
if isempty(model.F_struc)
model.F_struc = zeros(0,length(model.c) + 1);
end
% variable^power
if nnz(powers) == 1
univariate = 1;
variable = find(powers);
p1 = floor(powers(variable)/2);
p2 = ceil(powers(variable)/2);
powers_1 = powers;powers_1(variable) = p1;
powers_2 = powers;powers_2(variable) = p2;
else
univariate = 0;
variables = find(powers);
mid = floor(length(variables)/2);
variables_1 = variables(1:mid);
variables_2 = variables(mid+1:end);
powers_1 = powers;
powers_2 = powers;
powers_1(variables_2) = 0;
powers_2(variables_1) = 0;
end
[model,index1] = findoraddlinearmonomial(model,powers_1);
[model,index2] = findoraddlinearmonomial(model,powers_2);
model.monomtable(polynomial,:) = 0;
model.monomtable(polynomial,index1) = model.monomtable(polynomial,index1) + 1;
model.monomtable(polynomial,index2) = model.monomtable(polynomial,index2) + 1;
if index1 == index2
model.variabletype(polynomial) = 2;
else
model.variabletype(polynomial) = 1;
end
%model = convert_polynomial_to_quadratic(model);
function [model,index] = findoraddmonomial(model,powers);
if length(powers) < size(model.monomtable,2)
powers(size(model.monomtable,1)) = 0;
end
index = findrows(model.monomtable,powers);
if isempty(index)
model.monomtable = [model.monomtable;powers];
model.monomtable(end,end+1) = 0;
index = size(model.monomtable,1);
model.c(end+1) = 0;
model.Q(end+1,end+1) = 0;
if size(model.F_struc,1)>0
model.F_struc(1,end+1) = 0;
else
model.F_struc = zeros(0, size(model.F_struc,2)+1);
end
bound = powerbound(model.lb,model.ub,powers);
model.lb(end+1) = bound(1);
model.ub(end+1) = bound(2);
if ~isempty(model.x0)
model.x0(end+1) = 0;
end
switch sum(powers)
case 1
model.variabletype(end+1) = 0;
case 2
if nnz(powers)==1
model.variabletype(end+1) = 2;
else
model.variabletype(end+1) = 1;
end
otherwise
model.variabletype(end+1) = 3;
end
end
function [model,index] = findoraddlinearmonomial(model,powers);
if sum(powers) == 1
if length(powers)<size(model.monomtable,2)
powers(size(model.monomtable,2)) = 0;
end
index = findrows(model.monomtable,powers);
return
end
% We want to see if the monomial x^powers already is modelled by a linear
% variable. If not, we create the linear variable and add the associated
% constraint y == x^powers
index = [];
if ~isempty(model.high_monom_model)
if length(powers)>size(model.high_monom_model,2)+1
model.high_monom_model(1,end+1) = 0;
end
Z = model.high_monom_model(:,2:end);
index = findrows(Z,powers);
if ~isempty(index)
index = model.high_monom_model(index,1);
return
end
end
% OK, we could not find a linear model of this monomial. We thus create a
% linear variable, and add the constraint. Note that it is assumed that the
% nonlinear monomial x^power does exist
[model,index_nonlinear] = findoraddmonomial(model,powers);
model.monomtable(end+1,end+1) = 1;
model.variabletype(end+1) = 0;
model.F_struc = [zeros(1,size(model.F_struc,2));model.F_struc];
model.K.f = model.K.f + 1;
model.F_struc(1,end+1) = 1;
model.F_struc(1,1+index_nonlinear) = -1;
model.c(end+1) = 0;
model.Q(end+1,end+1) = 0;
model.high_monom_model = blockthem(model.high_monom_model,[length(model.c) powers]);;
if ~isempty(model.x0);
model.x0(end+1) = model.x0(index_nonlinear);
end
model.lb(end+1) = model.lb(index_nonlinear);
model.ub(end+1) = model.ub(index_nonlinear);
index = length(model.c);
function z = initial(x0,powers)
z = 1;
vars = find(powers);
for k = 1:length(vars)
z = z * x0(vars(k))^powers(vars(k));
end
function A = blockthem(A,B)
n = size(A,2);
m = size(B,2);
A = [A zeros(size(A,1),max([0 m-n]));B zeros(size(B,1),max([0 n-m]))];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
convert_perspective_log.m
|
.m
|
LMI-Matlab-master/yalmip/extras/convert_perspective_log.m
| 4,688 |
utf_8
|
d0b63460b38dcdea37d6dcb4721c262c
|
function p = convert_perspective_log(p)
p.kept = 1:length(p.c);
if isempty(p.evalMap)
return
end
if ~any(p.variabletype == 4)
return
end
variableIndex = [];
for i=1:length(p.evalMap)
variableIndex = [variableIndex p.evalMap{i}.variableIndex];
end
removable = [];
for i = 1:length(p.evalMap)
if strcmp(p.evalMap{i}.fcn,'log')
argument = p.evalMap{i}.variableIndex;
if length(argument) == 1
if p.variabletype(argument)==4
monoms = p.monomtable(argument,:);
if nnz(monoms) == 2
k = find(monoms);
p1 = monoms(k(1));
p2 = monoms(k(2));
if isequal(sort([p1 p2]) , [-1 1])
if p2>p1
x = k(2);
y = k(1);
else
x = k(1);
y = k(2);
end
% Ok, so we have log(x/y)
% is this multiplied by x somewhere
logxy = p.evalMap{i}.computes;
enters_in = find(p.monomtable(:,logxy));
other = setdiff(enters_in,p.evalMap{i}.computes);
if length(nnz(other)) == 1
monomsxlog = p.monomtable(other,:);
if nnz(monomsxlog) == 2 & (monomsxlog(x) == 1)
% Hey, x*log(x/y)!
% we change this monomial variable to a
% callback variable
p.evalMap{i}.fcn = 'perspective_log';
p.evalMap{i}.arg{1} = recover([x;y]);
p.evalMap{i}.arg{2} = [];
p.evalMap{i}.variableIndex = [x y];
p.evalMap{i}.computes = other;
p.evalMap{i}.properties.bounds = @plog_bounds;
p.evalMap{i}.properties.convexhull = @plog_convexhull;
p.evalMap{i}.properties.derivative = @plog_derivative;
p.evalMap{i}.properties.inverse = [];
p.variabletype(other) = 0;
p.monomtable(other,:) = 0;
p.monomtable(other,other) = 1;
p.evalVariables(i) = other;
% Figure out if x/y can be removed
% This is possible if the x/y term never is
% used besides inside the log term
if nnz(p.F_struc(:,1+argument)) == 1 & p.c(argument) == 0 & nnz(argument == variableIndex) == 1
removable = [removable argument];
end
end
end
end
end
end
end
end
end
kept = 1:length(p.c);
kept = setdiff(kept,removable);
aux_used = zeros(1,length(p.c));
aux_used(p.aux_variables) = 1;
aux_used(removable)=[];
p.aux_variables = find(aux_used);
if length(removable) > 0
kept = 1:length(p.c);
kept = setdiff(kept,removable);
[ii,jj,kk] = find(p.F_struc(:,1+removable));
p.F_struc(:,1+removable) = [];
p.F_struc(ii,:) = [];
p.K.l = p.K.l - length(removable);
p.c(removable) = [];
p.Q(removable,:) = [];
p.Q(:,removable) = [];
p.variabletype(removable) = [];
p.monomtable(:,removable) = [];
p.monomtable(removable,:) = [];
for i = 1:length(p.evalVariables)
p.evalVariables(i) = find(p.evalVariables(i) == kept);
for j = 1:length(p.evalMap{i}.variableIndex)
p.evalMap{i}.variableIndex(j) = find(p.evalMap{i}.variableIndex(j) == kept);
end
for j = 1:length(p.evalMap{i}.computes)
p.evalMap{i}.computes(j) = find(p.evalMap{i}.computes(j) == kept);
end
end
p.lb(removable) = [];
p.ub(removable) = [];
p.used_variables(removable) = [];
end
function dp = plog_derivative(x)
dp = [log(x(1)/x(2)) + 1;-x(1)/x(2)];
function [L,U] = plog_bounds(xL,xU)
xU(isinf(xU)) = 1e12;
x1 = xL(1)*log(xL(1)/xL(2));
x2 = xU(1)*log(xU(1)/xL(2));
x3 = xL(1)*log(xL(1)/xU(2));
x4 = xU(1)*log(xU(1)/xU(2));
U = max([x1 x2 x3 x4]);
if (exp(-1)*xU(2) > xL(1)) & (exp(-1)*xU(2) < xU(1))
L = -exp(-1)*xU(2);
else
L = min([x1 x2 x3 x4]);
end
function [Ax,Ay,b] = plog_convexhull(L,U);
Ax = [];
Ay = [];
b = [];
return
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
yalmiptable.m
|
.m
|
LMI-Matlab-master/yalmip/extras/yalmiptable.m
| 1,761 |
utf_8
|
9d3d69d9a7db32cbea823623e730f309
|
function yalmiptable(superheader,header,data,formats)
%TABLE Internal function to display tables
[nheadersy,nheadersx] = size(header);
[ndatay,ndatax] = size(data);
datasizes = zeros(ndatay,ndatax);
for i = 1:ndatay
for j = 1:ndatax
if isa(data{i,j},'double')
data{i,j} = num2str(data{i,j});
end
datasizes(i,j) = length(data{i,j});
end
end
headersizes = zeros(1,nheadersx);
for j = 1:nheadersx
if isa(header{j},'double')
header{j} = num2str(header{j});
end
headersizes(1,j) = length(header{j});
end
if nargin<4
for i = 1:ndatax
formats{i}.header.just = 'right';
formats{i}.data.just = 'right';
end
end
datawidth = sum(datasizes,2);
MaxWidth = max([headersizes;datasizes]);
HeaderLine = ['|'];
for i = 1:nheadersx
HeaderLine = [HeaderLine ' ' strjust(fillstringRight(header{i},MaxWidth(i)+2),formats{i}.header.just) '|'];
end
HeaderLine = [HeaderLine ''];
for j = 1:ndatay
DataLine{j} = ['|'];
for i = 1:ndatax
DataLine{j} = [DataLine{j} ' ' strjust(fillstringRight(data{j,i},MaxWidth(i)+2),formats{i}.data.just) '|'];
end
end
if ~isempty(superheader)
disp(char(repmat(double('+'),1,length(HeaderLine))))
disp(['|' strjust(fillstringLeft(superheader{1},length(HeaderLine)-2),'center') '|'])
end
disp(char(repmat(double('+'),1,length(HeaderLine))))
disp(HeaderLine)
disp(char(repmat(double('+'),1,length(HeaderLine))))
for i = 1:length(DataLine)
disp(DataLine{i});
end
disp(char(repmat(double('+'),1,length(HeaderLine))))
function x= truncstring(x,n)
if length(x) > n
x = [x(1:n-3) '...'];
end
function x = fillstringLeft(x,n)
x = [x blanks(n-length(x))];
function x = fillstringRight(x,n)
x = [blanks(n-length(x)) x];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdisplay2.m
|
.m
|
LMI-Matlab-master/yalmip/extras/sdisplay2.m
| 7,460 |
utf_8
|
1580149b36a2d9dad048527aa6633013
|
function symb_pvec = sdisplay2(p,names)
% TODO: sdpvar a b
% x = (a+b)^0.3 -- writes "mpower_internal"
%
% TODO: sdpvar h x k
% sdisplay2(h*x - k) -- misses the minus in front of "k"
if nargin < 2
LinearVariables = 1:yalmip('nvars');
x = recover(LinearVariables);
names = cell(length(x),1);
W = evalin('caller','whos');
for i = 1:size(W,1)
if strcmp(W(i).class,'sdpvar') | strcmp(W(i).class,'ncvar')
% Get the SDPVAR variable
thevars = evalin('caller',W(i).name);
% Distinguish 4 cases
% 1: Sclalar varible x
% 2: Vector variable x(i)
% 3: Matrix variable x(i,j)
% 4: Variable not really defined
if is(thevars,'scalar') & is(thevars,'linear') & length(getvariables(thevars))==1 & isequal(getbase(thevars),[0 1])
index_in_p = find(ismember(LinearVariables,getvariables(thevars)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
if isempty(already)
already = 0;
end
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
% Case 1
names{index_in_p}=W(i).name;
end
elseif is(thevars,'lpcone')
if size(thevars,1)==size(thevars,2)
% Case 2
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for ii = indicies
index_in_p = find(ismember(LinearVariables,vars(ii)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
if isempty(already)
already = 0;
end
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
B = reshape(getbasematrix(thevars,vars(ii)),size(thevars,1),size(thevars,2));
[ix,jx,kx] = find(B);
ix=ix(1);
jx=jx(1);
names{index_in_p}=[W(i).name '(' num2str(ix) ',' num2str(jx) ')'];
end
end
else
% Case 3
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for ii = indicies
index_in_p = find(ismember(LinearVariables,vars(ii)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
if isempty(already)
already = 0;
end
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
names{index_in_p}=[W(i).name '(' num2str(ii) ')'];
end
end
end
elseif is(thevars,'sdpcone')
% Case 3
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for ii = indicies
index_in_p = find(ismember(LinearVariables,vars(ii)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
B = reshape(getbasematrix(thevars,vars(ii)),size(thevars,1),size(thevars,2));
[ix,jx,kx] = find(B);
ix=ix(1);
jx=jx(1);
names{index_in_p}=[W(i).name '(' num2str(ix) ',' num2str(jx) ')'];
end
end
else
% Case 4
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for i = indicies
index_in_p = find(ismember(LinearVariables,vars(i)));
if ~isempty(index_in_p) & isempty(names{index_in_p})
names{index_in_p}=['internal(' num2str(vars(i)) ')'];
end
end
end
end
end
end
[mt,vt] = yalmip('monomtable');
ev = yalmip('extvariables');
for i = 1:size(p, 1)
for j = 1:size(p, 2)
symb_pvec{i, j} = symbolicdisplay(p(i, j), names, vt, ev, mt);
end
end
%------------------------------------------------------------------------
function expression = symbolicdisplay(p,names,vt,ev,mt)
sp = size(p);
if any(sp > 1)
out = '[';
else
out = '';
end
p_orig = p;
for i1 = 1:sp(1)
for i2 = 1:sp(2)
p = p_orig(i1, i2);
basis = getbase(p);
if basis(1)~=0
expression = [num2str(basis(1)) '+'];
else
expression = [''];
end
[dummy, variables, coeffs] = find(basis(2:end));
variables = getvariables(p);
for i = 1:length(coeffs)
if coeffs(i)==1
expression = [expression symbolicmonomial(variables(i), ...
names,vt,ev,mt) '+'];
else
expression = [expression num2str(coeffs(i)) '*' ...
symbolicmonomial(variables(i),names,vt,ev,mt) '+'];
end
end
expression(end) = [];
out = [out expression ','];
end
out(end) = ';';
end
out(end) = [];
if any(sp > 1)
out = [out ']'];
end
expression = out;
%------------------------------------------------------------------------
function s = symbolicmonomial(variable,names,vt,ev,mt)
terms = find(mt(variable,:));
if ismember(variable,ev)
q = yalmip('extstruct',variable);
s = [q.fcn '(' symbolicdisplay(q.arg{1},names,vt,ev,mt)];
for i = 2:length(q.arg)-1
s = [s ',' symbolicdisplay(q.arg{i}, names, vt, ev, mt)];
end
s = [s ')'];
elseif ~vt(variable)
% Linear expression
s = names{variable};
else
% Fancy display of a monomial
s = [''];
for i = 1:length(terms)
if mt(variable,terms(i)) == 1
exponent = '';
else
exponent = ['^' num2str(mt(variable,terms(i)))];
end
s = [s symbolicmonomial(terms(i),names,vt,ev,mt) exponent '*'];
end
s(end)=[];
end
% s = strrep(s,'^1+','+');
% s = strrep(s,'^1*','*');
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
dissect.m
|
.m
|
LMI-Matlab-master/yalmip/extras/dissect.m
| 2,898 |
utf_8
|
287c87ea98e36a7d4b0f42fb58700649
|
function varargout = dissect(X);
% DISSECT Dissect SDP constraint
%
% G = unblkdiag(F) Converts SDP to several smaller SDPs with more variables
%
% See also UNBLKDIAG
if isa(X,'constraint')
X = lmi(X);
end
switch class(X)
case 'sdpvar'
% Get sparsity pattern
Z=spy(X);
% Partition as
% [A1 0 C1
% 0 A2 C2
% C1' C2' E]
% Find a dissection
try
sep = metismex('NodeBisect',Z);
catch
error('You have to install the MATLAB interface to METIS, http://www.cerfacs.fr/algor/Softs/MESHPART/');
end
% Indicies for elements in Ai
s = setdiff(1:length(Z),sep);
% re-order Ais to get diagonal blocks
Z = Z(s,s);
AB = X(s,s);
CD = X(s,sep);
[v,dummy,r,dummy2]=dmperm(Z);
for i = 1:length(r)-1
A{i} = AB(v(r(i):r(i+1)-1),v(r(i):r(i+1)-1));
C{i}= CD(v(r(i):r(i+1)-1),:);
end
E = X(sep,sep);
varargout{1} = A;
varargout{2} = C;
varargout{3} = E;
case 'lmi'
Fnew=([]);
% decompose trivial block diagonal stuff
X = unblkdiag(X);
for i = 1:length(X)
if is(X(i),'sdp') & length(sdpvar(X(i)))
if 0
[A,B,C,D,E]=dissect(sdpvar(X(i)));
if ~isempty(B)
S=sdpvar(size(E,1));
S = S.*inversesparsity(E,D,B);
Fnew=Fnew+([A C;C' S]>=0)+([E-S D';D B]>=0);
else
Fnew = Fnew + X(i);
end
else
[A,C,E]=dissect(sdpvar(X(i)));
if length(A)>1
allS = 0;
for i = 1:length(A)-1
S{i}=sdpvar(size(E,1));
S{i} = S{i}.*inversesparsity(E,C{i},A{i});
allS = allS + S{i};
Fnew=Fnew+([A{i} C{i};C{i}' S{i}]>=0);
end
i = i + 1;
S{i}=E-allS;
S{i} = S{i}.*inversesparsity(E,C{i},A{i});
Fnew=Fnew+([A{i} C{i};C{i}' S{i}]>=0);
else
Fnew = Fnew + X(i);
end
end
else
Fnew=Fnew+X(i);
end
end
varargout{1} = Fnew;
end
function S = inversesparsity(E,D,B)
if isa(E,'sdpvar')
E = spy(E).*randn(size(E));
else
E = E.*randn(size(E));
end
if isa(D,'sdpvar')
D = spy(D).*randn(size(D));
else
D = D.*randn(size(D));
end
if isa(B,'sdpvar')
B = spy(B).*randn(size(B));
else
B = B.*randn(size(B));
end
S = E-D'*inv(B)*D;
S = S | S';
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
fmincon_con.m
|
.m
|
LMI-Matlab-master/yalmip/extras/fmincon_con.m
| 3,980 |
utf_8
|
bb638cd9a153556cf293b5b1615934b5
|
function [g,geq,dg,dgeq,xevaled] = fmincon_con(x,model,xevaled)
global latest_xevaled
global latest_x_xevaled
% Early bail for linear problems
g = [];
geq = [];
dg = [];
dgeq = [];
if model.linearconstraints
xevaled = [];
return
end
if nargin<3
if isequal(x,latest_x_xevaled)
xevaled = latest_xevaled;
else
xevaled = zeros(1,length(model.c));
xevaled(model.linearindicies) = x;
xevaled = apply_recursive_evaluation(model,xevaled);
latest_x_xevaled = x;
latest_xevaled = xevaled;
end
end
if model.nonlinearinequalities
g = full(model.Anonlinineq*xevaled(:)-model.bnonlinineq);
end
if nnz(model.K.q) > 0
top = 1;
for i = 1:length(model.K.q)
z = model.F_struc(top:top+model.K.q(i)-1,:)*[1;xevaled];
g = [g;-(z(1)^2 - z(2:end)'*z(2:end))];
top = top + model.K.q(i);
end
end
if model.nonlinearequalities
geq = full(model.Anonlineq*xevaled(:)-model.bnonlineq);
end
dgAll_test = [];
if nargout == 2 || ~model.derivative_available
return
elseif ~isempty(dgAll_test) & isempty(model.evalMap)
dgAll = dgAll_test;
elseif isempty(model.evalMap) & (model.nonlinearinequalities==0) & (model.nonlinearequalities==0) & (model.nonlinearcones==0) & any(model.K.q)
dg = computeConeDeriv(model,xevaled);
elseif isempty(model.evalMap) & (model.nonlinearinequalities | model.nonlinearequalities | model.nonlinearcones)
n = length(model.c);
linearindicies = model.linearindicies;
% xevaled = zeros(1,n);
% xevaled(linearindicies) = x;
% FIXME: This should be vectorized
news = model.fastdiff.news;
allDerivemt = model.fastdiff.allDerivemt;
c = model.fastdiff.c;
if model.fastdiff.univariateDifferentiates
zzz = c.*(x(model.fastdiff.univariateDiffMonom).^model.fastdiff.univariateDiffPower);
else
% X = repmat(x(:)',length(c),1);
O = ones(length(c),length(x));
nz = find(allDerivemt);
% O(nz) = X(nz).^allDerivemt(nz);
O(nz) = x(ceil(nz/length(c))).^allDerivemt(nz);
zzz = c.*prod(O,2);
end
newdxx = model.fastdiff.newdxx;
newdxx(model.fastdiff.linear_in_newdxx) = zzz;
%newdxx = newdxx';
if ~isempty(model.Anonlineq)
dgeq = model.Anonlineq*newdxx;
end
if ~isempty(model.Anonlinineq)
dg = model.Anonlinineq*newdxx;
end
if nnz(model.K.q)>0
dg = [dg;computeConeDeriv(model,xevaled,newdxx);];
end
else
requested = model.fastdiff.requested;
dx = apply_recursive_differentiation(model,xevaled,requested,model.Crecursivederivativeprecompute);
conederiv = computeConeDeriv(model,xevaled,dx);
if ~isempty(model.Anonlineq)
dgeq = [model.Anonlineq*dx];
end
if ~isempty(model.Anonlinineq)
dg = [model.Anonlinineq*dx];
end
if ~isempty(conederiv)
dg = [dg;conederiv];
end
end
if model.nonlinearequalities
dgeq = dgeq';
end
if model.nonlinearinequalities | any(model.K.q)
dg = dg';
end
function conederiv = computeConeDeriv(model,z,dzdx)
conederiv = [];
z = z(:);
if any(model.K.q)
top = 1 + model.K.f + model.K.l;
for i = 1:length(model.K.q)
d = model.F_struc(top,1);
c = model.F_struc(top,2:end)';
b = model.F_struc(top+1:top+model.K.q(i)-1,1);
A = model.F_struc(top+1:top+model.K.q(i)-1,2:end);
if nargin == 2
% No inner derivative
conederiv = [conederiv;(2*A(:,model.linearindicies)'*(A(:,model.linearindicies)*z(model.linearindicies)+b)-2*c(model.linearindicies)*(c(model.linearindicies)'*z(model.linearindicies)+d))'];
else
% inner derivative
aux = 2*z'*(A'*A-c*c')*dzdx+2*(b'*A-d*c')*dzdx;
conederiv = [conederiv;aux];
end
top = top + model.K.q(i);
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sedumi2sdpt3.m
|
.m
|
LMI-Matlab-master/yalmip/extras/sedumi2sdpt3.m
| 4,093 |
utf_8
|
8f142cc073201468ac59c3aab8d61e4b
|
%SEDUMI2SDPT3 Internal function, obsolete
%%*******************************************************************
%% Converts from SeDuMi format.
%%
%% [blk,A,C,b] = sedumi2sdpt3(c,A,b,K)
%%
%% Input: fname.mat = name of the file containing SDP data in
%% SeDuMi format.
%%
%% Important note: Sedumi's notation for free variables "K.f"
%% is coded in SDPT3 as blk{p,1} = 'u', where
%% "u" is used for unrestricted variables.
%%
%% Ripped from:
%% SDPT3: version 3.0
%% Copyright (c) 2000 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 2 Feb 01
%%******************************************************************
function [blk,Avec,C,b,oldKs] = sedumi2sdpt3(c,A,b,K,smallblkdim)
if (size(c,1) == 1), c = c'; end;
if (size(b,1) == 1), b = b'; end;
if (norm(A,'fro') > 0) & (size(A,2) == length(b)); At = A; end
if (norm(At,'fro')==0), At = A'; end;
[nn,mm] = size(At); if (max(size(c)) == 1); c = c*ones(nn,1); end;
if ~isfield(K,'f'); K.f = 0; end
if ~isfield(K,'l'); K.l = 0; end
if ~isfield(K,'q'); K.q = 0; end
if ~isfield(K,'s'); K.s = 0; end
if (K.f == 0) | isempty(K.f); K.f = 0; end;
if (K.l == 0) | isempty(K.l); K.l = 0; end;
if (sum(K.q) == 0) | isempty(K.q); K.q = 0; end
if (sum(K.s) == 0) | isempty(K.s); K.s = 0; end
%%
%%
%%
m = length(b);
rowidx = 0; idxblk = 0;
if ~(K.f == 0)
len = K.f;
idxblk = idxblk + 1;
blk{idxblk,1} = 'u'; blk{idxblk,2} = K.f;
Avec{idxblk,1} = At(rowidx+[1:len],:);
C{idxblk,1} = c(rowidx+[1:len]);
rowidx = rowidx + len;
end
if ~(K.l == 0)
len = K.l;
idxblk = idxblk + 1;
blk{idxblk,1} = 'l'; blk{idxblk,2} = K.l;
Avec{idxblk,1} = At(rowidx+[1:len],:);
C{idxblk,1} = c(rowidx+[1:len]);
rowidx = rowidx + len;
end
if ~(K.q == 0)
len = sum(K.q);
idxblk = idxblk + 1;
blk{idxblk,1} = 'q'; blk{idxblk,2} = K.q;
Avec{idxblk,1} = At(rowidx+[1:len],:);
C{idxblk,1} = c(rowidx+[1:len]);
rowidx = rowidx + len;
end
oldKs = [];
if ~(K.s == 0)
% Avoid extracting rows!
At = At';
smblkdim = smallblkdim;
blksize = K.s;
if size(blksize,2) == 1; blksize = blksize'; end
blknnz = [0 cumsum(blksize.*blksize)];
deblkidx = find(blksize > smblkdim);
if ~isempty(deblkidx)
for p = 1:length(deblkidx)
idxblk = idxblk + 1;
n = blksize(deblkidx(p));
oldKs = [oldKs deblkidx(p)];
pblk{1,1} = 's'; pblk{1,2} = n;
blk(idxblk,:) = pblk;
Atmp = At(:,rowidx+blknnz(deblkidx(p))+[1:n*n])';
Avec{idxblk,1} = sparse(n*(n+1)/2,m);
warning_yes = 1;
if 1
Avec{idxblk,1} = yalmipsvec(Atmp,n);
else
for k = 1:m
Ak = mexmat(pblk,Atmp(:,k),1);
Avec{idxblk,1}(:,k) = svec(pblk,Ak,1);
end
end
Ctmp = c(rowidx+blknnz(deblkidx(p))+[1:n*n]);
Ctmp = mexmat(pblk,Ctmp,1);
C{idxblk,1} = 0.5*(Ctmp+Ctmp');
end
end
spblkidx = find(blksize <= smblkdim);
if ~isempty(spblkidx)
pos = []; len = 0;
for p = 1:length(spblkidx)
n = blksize(spblkidx(p));
oldKs = [oldKs spblkidx(p)];
len = len + n*(n+1)/2;
pos = [pos, rowidx+blknnz(spblkidx(p))+[1:n*n]];
end
idxblk = idxblk + 1;
blk{idxblk,1} = 's'; blk{idxblk,2} = blksize(spblkidx);
Avec{idxblk,1} = sparse(len,m);
Atmp = At(:,pos)';
warning_yes = 1;
for k = 1:m
Ak = mexmat(blk(idxblk,:),sparse(full(Atmp(:,k))),1);
Avec{idxblk,1}(:,k) = svec(blk(idxblk,:),Ak,1);
end
Ctmp = c(pos);
Ctmp = mexmat(blk(idxblk,:),Ctmp,1);
C{idxblk,1} = 0.5*(Ctmp+Ctmp');
end
end
function x = yalmipsvec(X,n)
Y = reshape(1:n^2,n,n)';
d = diag(Y);
Y = tril(Y);
Y = (Y+Y')-diag(sparse(diag(Y)));
[uu,oo,pp] = unique(Y(:));
X = X*sqrt(2);
X(d,:)=X(d,:)/sqrt(2);
x = X(uu,:);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
compress_evaluation_scheme.m
|
.m
|
LMI-Matlab-master/yalmip/extras/compress_evaluation_scheme.m
| 2,228 |
utf_8
|
ccf30e513f35e6ac7a6dc02416d6fae8
|
function model = compress_evaluation_scheme(model);
scalars = {'erf','exp','log','sin','cos','log2','log10','slog','power_internal2','inverse_internal2','sqrtm_internal'};
for i = 1:length(model.evaluation_scheme)
if strcmp(model.evaluation_scheme{i}.group,'eval')
clear fun
for k = 1:length(scalars)
for j = 1:length(model.evaluation_scheme{i}.variables)
fun{k}(j) = strcmp(model.evalMap{model.evaluation_scheme{i}.variables(j)}.fcn,scalars{k});
end
end
for k = 1:length(scalars)
fun_i = find(fun{k});
if length(fun_i) > 1
all_outputs = [];
all_inputs = [];
for j = fun_i
all_outputs = [all_outputs model.evalMap{model.evaluation_scheme{i}.variables(j)}.computes];
all_inputs = [all_inputs model.evalMap{model.evaluation_scheme{i}.variables(j)}.variableIndex];
end
model.evalMap{model.evaluation_scheme{i}.variables(fun_i(1))}.computes = all_outputs;
model.evalMap{model.evaluation_scheme{i}.variables(fun_i(1))}.variableIndex = all_inputs;
model.evaluation_scheme{i}.variables(fun_i(2:end)) = nan;
end
end
model.evaluation_scheme{i}.variables(isnan(model.evaluation_scheme{i}.variables)) = [];
try
variables = removeDuplicates(model,model.evaluation_scheme{i}.variables);
model.evaluation_scheme{i}.variables = variables;
catch
end
end
end
function variables = removeDuplicates(model,variables)
% optimizer_ evaluation objects leads to multiple copies of similiar
% evaluations which can be performed in one shot
remove = zeros(1,length(variables));
for i = 1:length(variables)
for j = i+1:length(variables)
if ~remove(j)
if isequal(model.evalMap{variables(i)}.computes,model.evalMap{variables(j)}.computes)
if isequal(model.evalMap{variables(i)}.variableIndex,model.evalMap{variables(j)}.variableIndex)
remove(j) = 1;
end
end
end
end
end
variables = variables(find(~remove));
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdpvar2str.m
|
.m
|
LMI-Matlab-master/yalmip/extras/sdpvar2str.m
| 2,503 |
utf_8
|
dcd7bff7503ead1c19e49a6497f6e84b
|
function symb_pvec = sdpvar2str(pvec)
%SDPVAR2STR Converts an SDPVAR object to MATLAB string representation
%
% S = SDPVAR2STR(P)
%
% S : String
% P : SDPVAR object
for pi = 1:size(pvec,1)
for pj = 1:size(pvec,2)
p = pvec(pi,pj);
if isa(p,'double')
symb_p = num2str(p);
else
LinearVariables = depends(p);
x = recover(LinearVariables);
exponent_p = full(exponents(p,x));
names = cell(length(LinearVariables),1);
for i = 1:length(LinearVariables)
names{i}=['x(' num2str(LinearVariables(i)) ')'];
end
symb_p = '';
if all(exponent_p(1,:)==0)
symb_p = num2str(getbasematrix(p,0));
exponent_p = exponent_p(2:end,:);
end
for i = 1:size(exponent_p,1)
coeff = getbasematrixwithoutcheck(p,i);
switch full(coeff)
case 1
coeff='+';
case -1
coeff = '-';
otherwise
if coeff >0
coeff = ['+' num2str2(coeff)];
else
coeff=[num2str2(coeff)];
end
end
if strcmp(symb_p,'') & (strcmp(coeff,'+') | strcmp(coeff,'-'))
symb_p = [symb_p coeff symbmonom(names,exponent_p(i,:))];
else
symb_p = [symb_p coeff '*' symbmonom(names,exponent_p(i,:))];
end
end
if symb_p(1)=='+'
symb_p = symb_p(2:end);
end
end
symb_p = strrep(symb_p,'*^0','');
symb_p = strrep(symb_p,'^0','');
symb_p = strrep(symb_p,'+*','+');
symb_p = strrep(symb_p,'-*','-');
symb_pvec{pi,pj} = symb_p;
end
end
function s = symbmonom(names,monom)
s = '';
for j = 1:length(monom)
if monom(j)~=0
if strcmp(s,'')
s = [s names{j}];
else
s = [s '*' names{j}];
end
end
if monom(j)~=1
s = [s '^' num2str(monom(j))];
end
% if monom(j)>1
% s = [s '^' num2str(monom(j))];
% end
end
function s = num2str2(x)
s = num2str(x);
if isequal(s,'1')
s = '';
end
if isequal(s,'-1')
s = '-';
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
compileinterfacedata.m
|
.m
|
LMI-Matlab-master/yalmip/extras/compileinterfacedata.m
| 50,239 |
utf_8
|
430b4ae42ad938e379c3ece8cde7b5bb
|
function [interfacedata,recoverdata,solver,diagnostic,F,Fremoved,ForiginalQuadratics] = compileinterfacedata(F,aux_obsolete,logdetStruct,h,options,findallsolvers,parametric)
persistent CACHED_SOLVERS
persistent allsolvers
persistent EXISTTIME
persistent NCHECKS
%% Initilize default empty outputs
diagnostic = [];
interfacedata = [];
recoverdata = [];
solver = [];
Fremoved = [];
ForiginalQuadratics = [];
%% Did we make the call from SOLVEMP
if nargin<7
parametric = 0;
end
%% Clean objective to default empty
if isa(h,'double')
h = [];
end
% *************************************************************************
%% Exit if LOGDET objective is nonlinear
% *************************************************************************
if ~isempty(logdetStruct)
for i = 1:length(logdetStruct.P)
if ~is(logdetStruct.P{i},'linear')
diagnostic.solvertime = 0;
diagnostic.problem = -2;
diagnostic.info = yalmiperror(diagnostic.problem,'');
return
end
end
end
% *************************************************************************
%% EXTRACT LOW-RANK DESCRIPTION
% *************************************************************************
lowrankdetails = getlrdata(F);
if ~isempty(lowrankdetails)
F = F(~is(F,'lowrank'));
end
% *************************************************************************
%% PERTURB STRICT INEQULAITIES
% *************************************************************************
if isa(options.shift,'sdpvar') | (options.shift~=0)
F = shift(F,options.shift);
end
% *************************************************************************
%% ADD RADIUS CONSTRAINT
% *************************************************************************
if isa(options.radius,'sdpvar') | ~isinf(options.radius)
x = recover(unique(union(depends(h),depends(F))));
if length(x)>1
F = F + (cone(x,options.radius));
else
F = F + (-options.radius <= x <= options.radius);
end
F = flatten(F);
end
% *************************************************************************
%% CONVERT LOGIC CONSTRAINTS
% *************************************************************************
[F,changed] = convertlogics(F);
if changed
F = flatten(F);
options.saveduals = 0; % Don't calculate duals since we changed the problem
end
% *************************************************************************
%% Take care of the nonlinear operators by converting expressions such as
% t = max(x,y) to standard conic models and mixed integer models
% This part also adds parts from logical expressions and mpower terms
% *************************************************************************
if options.expand
% Experimental hack due to support for the PWQ function used for
% quadratic dynamic programming with MPT.
% FIX: Clean up and generalize
try
h1v = depends(h);
h2v = getvariables(h);
if ~isequal(h1v,h2v)
variables = uniquestripped([h1v h2v]);
else
variables = h1v;
end
extendedvariables = yalmip('extvariables');
index_in_extended = find(ismembcYALMIP(variables,extendedvariables));
if ~isempty(index_in_extended)
extstruct = yalmip('extstruct',variables(index_in_extended));
if ~isa(extstruct,'cell')
extstruct = {extstruct};
end
for i = 1:length(extstruct)
if isequal(extstruct{i}.fcn ,'pwq_yalmip')
[properties,Fz,arguments]=model(extstruct{i}.var,'integer',options,extstruct{i});
if iscell(properties)
properties = properties{1};
end
gain = getbasematrix(h,getvariables(extstruct{i}.var));
h = replace(h,extstruct{i}.var,0);
h = h + gain*properties.replacer;
F = F + Fz;
end
end
end
catch
end
[F,failure,cause,operators] = expandmodel(F,h,options);
F = flatten(F);
if failure % Convexity propgation failed
interfacedata = [];
recoverdata = [];
solver = '';
diagnostic.solvertime = 0;
diagnostic.problem = 14;
diagnostic.info = yalmiperror(14,cause);
return
end
evalVariables = unique(determineEvaluationBased(operators));
if isempty(evalVariables)
evaluation_based = 0;
exponential_cone = 0;
else
used = [depends(h) depends(F)];
usedevalvariables = intersect(used,evalVariables);
evaluation_based = ~isempty(usedevalvariables);
exponential_cone = isempty(setdiff(usedevalvariables,yalmip('expvariables')));
end
else
evalVariables = [];
evaluation_based = 0;
exponential_cone = 0;
end
% *************************************************************************
%% LOOK FOR AVAILABLE SOLVERS
% Finding solvers can be very slow on some systems. To alleviate this
% problem, YALMIP can cache the list of available solvers.
% *************************************************************************
if (options.cachesolvers==0) | isempty(CACHED_SOLVERS)
getsolvertime = clock;
[solvers,kept,allsolvers] = getavailablesolvers(findallsolvers,options);
getsolvertime = etime(clock,getsolvertime);
% CODE TO INFORM USERS ABOUT SLOW NETWORKS!
if isempty(EXISTTIME)
EXISTTIME = getsolvertime;
NCHECKS = 1;
else
EXISTTIME = [EXISTTIME getsolvertime];
NCHECKS = NCHECKS + 1;
end
if (options.cachesolvers==0)
if ((NCHECKS >= 3 & (sum(EXISTTIME)/NCHECKS > 1)) | EXISTTIME(end)>2)
if warningon
info = 'Warning: YALMIP has detected that your drive or network is unusually slow.\nThis causes a severe delay in SOLVESDP when I try to find available solvers.\nTo avoid this, use the options CACHESOLVERS in SDPSETTINGS.\nSee the FAQ for more information.\n';
fprintf(info);
end
end
end
if length(EXISTTIME) > 5
EXISTTIME = EXISTTIME(end-4:end);
NCHECKS = 5;
end
CACHED_SOLVERS = solvers;
else
solvers = CACHED_SOLVERS;
end
% *************************************************************************
%% NO SOLVER AVAILABLE
% *************************************************************************
if isempty(solvers)
diagnostic.solvertime = 0;
if isempty(options.solver)
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
else
diagnostic.info = yalmiperror(-3,'YALMIP');
diagnostic.problem = -3;
end
if warningon & options.warning & isempty(findstr(diagnostic.info,'No problems detected'))
disp(['Warning: ' diagnostic.info]);
end
return
end
% *************************************************************************
%% CONVERT CONVEX QUADRATIC CONSTRAINTS
% We do not convert quadratic constraints to SOCPs if we have have
% sigmonial terms (thus indicating a GP problem), if we have relaxed
% nonlinear expressions, or if we have specified a nonlinear solver.
% Why do we convert them already here? Don't remember, should be cleaned up
% *************************************************************************
[monomtable,variabletype] = yalmip('monomtable');
F_vars = getvariables(F);
do_not_convert = any(variabletype(F_vars)==4);
%do_not_convert = do_not_convert | ~solverCapable(solvers,options.solver,'constraint.inequalities.secondordercone');
do_not_convert = do_not_convert | strcmpi(options.solver,'bmibnb');
do_not_convert = do_not_convert | strcmpi(options.solver,'scip');
do_not_convert = do_not_convert | strcmpi(options.solver,'snopt');
do_not_convert = do_not_convert | strcmpi(options.solver,'knitro');
do_not_convert = do_not_convert | strcmpi(options.solver,'snopt-geometric');
do_not_convert = do_not_convert | strcmpi(options.solver,'snopt-standard');
do_not_convert = do_not_convert | strcmpi(options.solver,'ipopt');
do_not_convert = do_not_convert | strcmpi(options.solver,'bonmin');
do_not_convert = do_not_convert | strcmpi(options.solver,'nomad');
do_not_convert = do_not_convert | strcmpi(options.solver,'ipopt-geometric');
do_not_convert = do_not_convert | strcmpi(options.solver,'ipopt-standard');
do_not_convert = do_not_convert | strcmpi(options.solver,'filtersd');
do_not_convert = do_not_convert | strcmpi(options.solver,'filtersd-dense');
do_not_convert = do_not_convert | strcmpi(options.solver,'filtersd-sparse');
do_not_convert = do_not_convert | strcmpi(options.solver,'pennon');
do_not_convert = do_not_convert | strcmpi(options.solver,'pennon-geometric');
do_not_convert = do_not_convert | strcmpi(options.solver,'pennon-standard');
do_not_convert = do_not_convert | strcmpi(options.solver,'pennlp');
do_not_convert = do_not_convert | strcmpi(options.solver,'penbmi');
do_not_convert = do_not_convert | strcmpi(options.solver,'fmincon');
do_not_convert = do_not_convert | strcmpi(options.solver,'lindo');
do_not_convert = do_not_convert | strcmpi(options.solver,'sqplab');
do_not_convert = do_not_convert | strcmpi(options.solver,'fmincon-geometric');
do_not_convert = do_not_convert | strcmpi(options.solver,'fmincon-standard');
do_not_convert = do_not_convert | strcmpi(options.solver,'bmibnb');
do_not_convert = do_not_convert | strcmpi(options.solver,'moment');
do_not_convert = do_not_convert | strcmpi(options.solver,'sparsepop');
do_not_convert = do_not_convert | strcmpi(options.solver,'baron');
do_not_convert = do_not_convert | (options.convertconvexquad == 0);
do_not_convert = do_not_convert | (options.relax == 1);
if ~do_not_convert & any(variabletype(F_vars))
[F,socp_changed,infeasible,ForiginalQuadratics] = convertquadratics(F);
if infeasible
diagnostic.solvertime = 0;
diagnostic.problem = 1;
diagnostic.info = yalmiperror(diagnostic.problem,'YALMIP');
return
end
if socp_changed % changed holds the number of QC -> SOCC conversions
options.saveduals = 0; % We cannot calculate duals since we changed the problem
F_vars = []; % We have changed model so we cannot use this in categorizemodel
end
else
socp_changed = 0;
end
% CHEAT FOR QC
if socp_changed>0 & length(find(is(F,'socc')))==socp_changed
socp_are_really_qc = 1;
else
socp_are_really_qc = 0;
end
% *************************************************************************
%% WHAT KIND OF PROBLEM DO WE HAVE NOW?
% *************************************************************************
[ProblemClass,integer_variables,binary_variables,parametric_variables,uncertain_variables,semicont_variables,quad_info] = categorizeproblem(F,logdetStruct,h,options.relax,parametric,evaluation_based,F_vars,exponential_cone);
% Ugly fix to short-cut any decision on GP. min -x-y cannot be cast as GP,
% while min -x can, as we can invert the objective
ProblemClass.gppossible = 1;
if ~isempty(h)
c = getbase(h);c = c(2:end);
if nnz(c)>1
if any(c<0)
ProblemClass.gppossible = 0;
end
end
end
% *************************************************************************
%% SELECT SUITABLE SOLVER
% *************************************************************************
[solver,problem] = selectsolver(options,ProblemClass,solvers,socp_are_really_qc,allsolvers);
if isempty(solver)
diagnostic.solvertime = 0;
if problem == -4 || problem == -3 || problem == -9
diagnostic.info = yalmiperror(problem,options.solver);
else
diagnostic.info = yalmiperror(problem,'YALMIP');
end
diagnostic.problem = problem;
if warningon & options.warning
disp(['Warning: ' diagnostic.info]);
end
return
end
if length(solver.version)>0
solver.tag = [solver.tag '-' solver.version];
end
if ProblemClass.constraint.complementarity.variable | ProblemClass.constraint.complementarity.linear | ProblemClass.constraint.complementarity.nonlinear
if ~(solver.constraint.complementarity.variable | solver.constraint.complementarity.linear | solver.constraint.complementarity.nonlinear)
% Extract the terms in the complementarity constraints x^Ty==0,
% x>=0, y>=0, since these involves bounds that should be appended
% to the list of constraints from which we do bound propagation
Fc = F(find(is(F,'complementarity')));
Ftemp = F;
for i = 1:length(Fc)
[Cx,Cy] = getComplementarityTerms(Fc(i));
Ftemp = [Ftemp, Cx>=0, Cy >=0];
end
% FIXME: SYNC with expandmodel
setupBounds(Ftemp,options,extendedvariables);
[F] = modelComplementarityConstraints(F,solver,ProblemClass);
% FIXME Reclassify should be possible to do manually!
oldProblemClass = ProblemClass;
[ProblemClass,integer_variables,binary_variables,parametric_variables,uncertain_variables,semicont_variables,quad_info] = categorizeproblem(F,logdetStruct,h,options.relax,parametric,evaluation_based,F_vars,exponential_cone);
ProblemClass.gppossible = oldProblemClass.gppossible;
elseif solver.constraint.complementarity.variable
% Solver supports x(i)*x(j)==0
Fok = [];
Freform = [];
Fc = F(find(is(F,'complementarity')));
for i = 1:length(Fc)
[Cx,Cy] = getComplementarityTerms(Fc(i));
if (islinear(Cx) & islinear(Cy) & is(Cx,'lpcone') & is(Cy,'lpcone'))
Fok = [Fok, Fc(i)];
else
s1 = sdpvar(length(Cx),1);
s2 = sdpvar(length(Cy),1);
Freform = [Freform,complements(s1>=0,s2>=0),s1 == Cx, s2 == Cy];
end
end
F = F-Fc;
F = F + Fok + Freform;
end
end
% *************************************************************************
%% DID WE SELECT THE INTERNAL BNB SOLVER
% IN THAT CASE, SELECT LOCAL SOLVER
% (UNLESS ALREADY SPECIFIED IN OPTIONS.BNB)
% *************************************************************************
localsolver.qc = 0;
localsolver = solver;
if strcmpi(solver.tag,'bnb')
[solver,diagnostic] = setupBNB(solver,ProblemClass,options,solvers,socp_are_really_qc,F,h,logdetStruct,parametric,evaluation_based,F_vars,exponential_cone,allsolvers);
if ~isempty(diagnostic)
return
end
end
if findstr(lower(solver.tag),'sparsecolo')
temp_options = options;
temp_options.solver = options.sparsecolo.SDPsolver;
tempProblemClass = ProblemClass;
localsolver = selectsolver(temp_options,tempProblemClass,solvers,socp_are_really_qc,allsolvers);
if isempty(localsolver) | strcmpi(localsolver.tag,'sparsecolo')
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
return
end
solver.sdpsolver = localsolver;
end
if findstr(lower(solver.tag),'frlib')
temp_options = options;
temp_options.solver = options.frlib.solver;
tempProblemClass = ProblemClass;
localsolver = selectsolver(temp_options,tempProblemClass,solvers,socp_are_really_qc,allsolvers);
if isempty(localsolver) | strcmpi(localsolver.tag,'frlib')
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
return
end
solver.solver = localsolver;
end
% *************************************************************************
%% DID WE SELECT THE MPCVX SOLVER
% IN THAT CASE, SELECT SOLVER TO SOLVE BOUND COMPUTATIONS
% *************************************************************************
localsolver.qc = 0;
localsolver = solver;
if strcmpi(solver.tag,'mpcvx')
temp_options = options;
temp_options.solver = options.mpcvx.solver;
tempProblemClass = ProblemClass;
tempProblemClass.objective.quadratic.convex = tempProblemClass.objective.quadratic.convex | tempProblemClass.objective.quadratic.nonconvex;
tempProblemClass.objective.quadratic.nonconvex = 0;
tempProblemClass.parametric = 0;
localsolver = selectsolver(temp_options,tempProblemClass,solvers,socp_are_really_qc,allsolvers);
if isempty(localsolver) | strcmpi(localsolver.tag,'bnb') | strcmpi(localsolver.tag,'kktqp')
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
return
end
solver.lower = localsolver;
end
% *************************************************************************
%% DID WE SELECT THE INTERNAL EXPERIMENTAL KKT SOLVER
% IN THAT CASE, SELECT SOLVER TO SOLVE THE MILP PROBLEM
% *************************************************************************
localsolver.qc = 0;
localsolver = solver;
if strcmpi(solver.tag,'kktqp')
temp_options = options;
temp_options.solver = '';
tempProblemClass = ProblemClass;
tempProblemClass.constraint.binary = 1;
tempProblemClass.objective.quadratic.convex = 0;
tempProblemClass.objective.quadratic.nonconvex = 0;
localsolver = selectsolver(temp_options,tempProblemClass,solvers,socp_are_really_qc,allsolvers);
if isempty(localsolver) | strcmpi(localsolver.tag,'bnb') | strcmpi(localsolver.tag,'kktqp')
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
return
end
solver.lower = localsolver;
end
% *************************************************************************
%% DID WE SELECT THE LMIRANK?
% FIND SDP SOLVER FOR INITIAL SOLUTION
% *************************************************************************
if strcmpi(solver.tag,'lmirank')
temp_options = options;
temp_options.solver = options.lmirank.solver;
tempProblemClass = ProblemClass;
tempProblemClass.constraint.inequalities.rank = 0;
tempProblemClass.constraint.inequalities.semidefinite.linear = 1;
tempProblemClass.objective.linear = 1;
initialsolver = selectsolver(temp_options,tempProblemClass,solvers,socp_are_really_qc,allsolvers);
if isempty(initialsolver) | strcmpi(initialsolver.tag,'lmirank')
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
return
end
solver.initialsolver = initialsolver;
end
% *************************************************************************
%% DID WE SELECT THE VSDP SOLVER? Define a solver for VSDP to use
% *************************************************************************
if findstr(solver.tag,'VSDP')
temp_options = options;
temp_options.solver = options.vsdp.solver;
tempProblemClass = ProblemClass;
tempProblemClass.interval = 0;
tempProblemClass.constraint.inequalities.semidefinite.linear = tempProblemClass.constraint.inequalities.semidefinite.linear | tempProblemClass.objective.quadratic.convex;
tempProblemClass.constraint.inequalities.semidefinite.linear = tempProblemClass.constraint.inequalities.semidefinite.linear | tempProblemClass.constraint.inequalities.secondordercone;
tempProblemClass.constraint.inequalities.secondordercone = 0;
tempProblemClass.objective.quadratic.convex = 0;
initialsolver = selectsolver(temp_options,tempProblemClass,solvers,socp_are_really_qc,allsolvers);
if isempty(initialsolver) | strcmpi(initialsolver.tag,'vsdp')
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
return
end
solver.solver = initialsolver;
end
% *************************************************************************
%% DID WE SELECT THE INTERNAL BMIBNB SOLVER? SELECT UPPER/LOWER SOLVERs
% (UNLESS ALREADY SPECIFIED IN OPTIONS)
% *************************************************************************
if strcmpi(solver.tag,'bmibnb')
[solver,diagnostic] = setupBMIBNB(solver,ProblemClass,options,solvers,socp_are_really_qc,F,h,logdetStruct,parametric,evaluation_based,F_vars,exponential_cone,allsolvers);
if ~isempty(diagnostic)
return
end
end
% *************************************************************************
%% DID WE SELECT THE INTERNAL SDPMILP SOLVER
% This solver solves MISDP problems by solving MILP problems and adding SDP
% cuts based on the infasible MILP solution.
% *************************************************************************
if strcmpi(solver.tag,'cutsdp')
% Relax problem for lower solver
tempProblemClass = ProblemClass;
tempProblemClass.constraint.inequalities.elementwise.linear = tempProblemClass.constraint.inequalities.elementwise.linear | tempProblemClass.constraint.inequalities.semidefinite.linear | tempProblemClass.constraint.inequalities.secondordercone.linear;
tempProblemClass.constraint.inequalities.semidefinite.linear = 0;
tempProblemClass.constraint.inequalities.secondordercone.linear = 0;
tempProblemClass.objective.quadratic.convex = 0;
temp_options = options;
temp_options.solver = options.cutsdp.solver;
if strcmp(options.cutsdp.solver,'bnb')
error('BNB can not be used in CUTSDP. Please install and use a better MILP solver');
end
[lowersolver,problem] = selectsolver(temp_options,tempProblemClass,solvers,socp_are_really_qc,allsolvers);
if ~isempty(lowersolver) & strcmpi(lowersolver.tag,'bnb')
error('BNB can not be used in CUTSDP. Please install and use a better MILP solver');
end
if isempty(lowersolver) | strcmpi(lowersolver.tag,'cutsdp') |strcmpi(lowersolver.tag,'bmibnb') | strcmpi(lowersolver.tag,'bnb')
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(-2,'YALMIP');
diagnostic.problem = -2;
return
end
solver.lower = lowersolver;
end
showprogress(['Solver chosen : ' solver.tag],options.showprogress);
% *************************************************************************
%% CONVERT SOS2 to binary constraints for solver not supporting sos2
% *************************************************************************
if ProblemClass.constraint.sos2 & ~solver.constraint.sos2
[F,binary_variables] = expandsos2(F,binary_variables);
end
% *************************************************************************
%% CONVERT MAXDET TO SDP USING GEOMEAN?
% *************************************************************************
% MAXDET using geometric mean construction
if ~isempty(logdetStruct)
if isequal(solver.tag,'BNB')
can_solve_maxdet = solver.lower.objective.maxdet.convex;
can_solve_expcone = solver.lower.exponentialcone;
else
can_solve_maxdet = solver.objective.maxdet.convex;
can_solve_expcone = solver.exponentialcone;
end
if ~can_solve_maxdet
if isempty(h)
h = 0;
end
if can_solve_expcone
for i = 1:length(logdetStruct.P)
[vi,Modeli] = eigv(logdetStruct.P{i});
F = [F, Modeli, logdetStruct.P{i} >= 0];
log_vi = log(vi);
h = h + logdetStruct.gain(i)*sum(log_vi);
evalVariables = union(evalVariables,getvariables( log_vi));
end
else
t = sdpvar(1,1);
Ptemp = [];
for i = 1:length(logdetStruct.P)
Ptemp = blkdiag(Ptemp,logdetStruct.P{i});
end
P = {Ptemp};
if length(F)>0
if isequal(P,sdpvar(F(end)))
F = F(1:end-1);
end
end
F = F + detset(t,P{1});
if isempty(h)
h = -t;
if length(logdetStruct.P) > 1 && options.verbose>0 && options.warning>0
disp(' ')
disp('Objective -sum logdet(P_i) has been changed to -sum det(P_i)^(1/(2^ceil(log2(length(P_i))))).')
disp('This is not an equivalent transformation. You should use SDPT3 which supports MAXDET terms')
disp('See the MAXDET section in the manual for details.')
disp(' ')
end
else
h = h-t;
% Warn about logdet -> det^1/m
if options.verbose>0 & options.warning>0
disp(' ')
disp('Objective c''x-sum logdet(P_i) has been changed to c''x-sum det(P_i)^(1/(2^ceil(log2(length(P_i))))).')
disp('This is not an equivalent transformation. You should use SDPT3 which supports MAXDET terms')
disp('See the MAXDET section in the manual for details.')
disp(' ')
end
end
end
P = [];
logdetStruct = [];
end
end
% *************************************************************************
%% Change binary variables to integer?
% *************************************************************************
old_binary_variables = binary_variables;
if ~isempty(binary_variables) & (solver.constraint.binary==0)
x_bin = recover(binary_variables(ismember(binary_variables,unique([getvariables(h) getvariables(F)]))));
F = F + (x_bin<=1)+(x_bin>=0);
integer_variables = union(binary_variables,integer_variables);
binary_variables = [];
end
% *************************************************************************
%% Model quadratics using SOCP?
% Should not be done when using PENNLP or BMIBNB or FMINCON, or if we have relaxed the
% monmial terms or...Ouch, need to clean up all special cases, this sucks.
% *************************************************************************
convertQuadraticObjective = ~strcmpi(solver.tag,'pennlp-standard');
convertQuadraticObjective = convertQuadraticObjective & ~strcmpi(solver.tag,'bmibnb');
relaxed = (options.relax==1 | options.relax==3);
%| (~isempty(quad_info) & strcmp(solver.tag,'bnb') & localsolver.objective.quadratic.convex==0)
convertQuadraticObjective = convertQuadraticObjective & (~relaxed & (~isempty(quad_info) & solver.objective.quadratic.convex==0));
%convertQuadraticObjective = convertQuadraticObjective; % | strcmpi(solver.tag,'cutsdp');
if any(strcmpi(solver.tag,{'bnb','cutsdp'})) & ~isempty(quad_info)
if solver.lower.objective.quadratic.convex==0
convertQuadraticObjective = 1;
end
end
if convertQuadraticObjective
t = sdpvar(1,1);
x = quad_info.x;
R = quad_info.R;
if ~isempty(R)
c = quad_info.c;
f = quad_info.f;
F = F + lmi(cone([2*R*x;1-(t-c'*x-f)],1+t-c'*x-f));
h = t;
end
quad_info = [];
end
if solver.constraint.inequalities.rotatedsecondordercone == 0
[F,changed] = convertlorentz(F);
if changed
options.saveduals = 0; % We cannot calculate duals since we change the problem
end
end
% Whoa, horrible tests to find out when to convert SOCP to SDP
% This should not be done if :
% 1. Problem is actually a QCQP and solver supports this
% 2. Problem is integer, local solver supports SOCC
% 3. Solver supports SOCC
if ~((solver.constraint.inequalities.elementwise.quadratic.convex == 1) & socp_are_really_qc)
if ~(strcmp(solver.tag,'bnb') & socp_are_really_qc & localsolver.constraint.inequalities.elementwise.quadratic.convex==1 )
if ((solver.constraint.inequalities.secondordercone.linear == 0) | (strcmpi(solver.tag,'bnb') & localsolver.constraint.inequalities.secondordercone.linear==0))
if solver.constraint.inequalities.semidefinite.linear
[F,changed] = convertsocp(F);
else
[F,changed] = convertsocp2NONLINEAR(F);
end
if changed
options.saveduals = 0; % We cannot calculate duals since we change the problem
end
end
end
end
% *************************************************************************
%% Add logaritmic barrier cost/constraint for MAXDET and SDPT3-4. Note we
% have to add it her in order for a complex valued matrix to be converted.
% *************************************************************************
if ~isempty(logdetStruct) & solver.objective.maxdet.convex==1 & solver.constraint.inequalities.semidefinite.linear
for i = 1:length(logdetStruct.P)
F = F + (logdetStruct.P{i} >= 0);
if ~isreal(logdetStruct.P{i})
logdetStruct.gain(i) = logdetStruct.gain(i)/2;
ProblemClass.complex = 1;
end
end
end
if ((solver.complex==0) & ProblemClass.complex) | ((strcmp(solver.tag,'bnb') & localsolver.complex==0) & ProblemClass.complex)
showprogress('Converting to real constraints',options.showprogress)
F = imag2reallmi(F);
if ~isempty(logdetStruct)
for i = 1:length(logdetStruct.P)
P{i} = sdpvar(F(end-length(logdetStruct.P)+i));
end
end
options.saveduals = 0; % We cannot calculate duals since we change the problem
%else
% complex_logdet = zeros(length(P),1);
end
% *************************************************************************
%% CREATE OBJECTIVE FUNCTION c'*x+x'*Q*x
% *************************************************************************
showprogress('Processing objective function',options.showprogress);
try
% If these solvers, the Q term is placed in c, hence quadratic terms
% are treated as any other nonlinear term
geometric = strcmpi(solver.tag,'fmincon-geometric')| strcmpi(solver.tag,'gpposy') | strcmpi(solver.tag,'mosek-geometric') | strcmpi(solver.tag,'snopt-geometric') | strcmpi(solver.tag,'ipopt-geometric') | strcmpi(solver.tag,'pennon-geometric');
if strcmpi(solver.tag,'bnb')
lowersolver = lower([solver.lower.tag '-' solver.lower.version]);
if strcmpi(lowersolver,'fmincon-geometric')| strcmpi(lowersolver,'gpposy-') | strcmpi(lowersolver,'mosek-geometric')
geometric = 1;
end
end
if strcmpi(solver.tag,'bmibnb') | strcmpi(solver.tag,'sparsepop') | strcmpi(solver.tag,'pennlp-standard') | geometric | evaluation_based ;
tempoptions = options;
tempoptions.relax = 1;
[c,Q,f]=createobjective(h,logdetStruct,tempoptions,quad_info);
else
[c,Q,f]=createobjective(h,logdetStruct,options,quad_info);
end
catch
error(lasterr)
end
% *************************************************************************
%% Convert {F(x),G(x)} to a numerical SeDuMi-like format
% *************************************************************************
showprogress('Processing constraints',options.showprogress);
F = lmi(F);
[F_struc,K,KCut,schur_funs,schur_data,schur_variables] = lmi2sedumistruct(F);
% We add a field to remember the dimension of the logarithmic cost.
% Actually, the actually value is not interesting, we know that the
% logarithmic cost corresponds to the last LP or SDP constraint anyway
if isempty(logdetStruct)
K.m = 0;
else
for i = 1:length(logdetStruct.P)
K.m(i) = length(logdetStruct.P{i});
end
K.maxdetgain = logdetStruct.gain;
end
if ~isempty(schur_funs)
if length(schur_funs)<length(K.s)
schur_funs{length(K.s)}=[];
schur_data{length(K.s)}=[];
schur_variables{length(K.s)}=[];
end
end
K.schur_funs = schur_funs;
K.schur_data = schur_data;
K.schur_variables = schur_variables;
% *************************************************************************
%% SOME HORRIBLE CODE TO DETERMINE USED VARIABLES
% *************************************************************************
% Which sdpvar variables are actually in the problem
used_variables_LMI = find(any(F_struc(:,2:end),1));
used_variables_obj = find(any(c',1) | any(Q));
if isequal(used_variables_LMI,used_variables_obj)
used_variables = used_variables_LMI;
else
used_variables = uniquestripped([used_variables_LMI used_variables_obj]);
end
if ~isempty(K.sos)
for i = 1:length(K.sos.type)
used_variables = uniquestripped([used_variables K.sos.variables{i}(:)']);
end
end
% The problem is that linear terms might be missing in problems with only
% nonlinear expressions
[monomtable,variabletype] = yalmip('monomtable');
if (options.relax==1)|(options.relax==3)
monomtable = [];
nonlinearvariables = [];
linearvariables = used_variables;
else
nonlinearvariables = find(variabletype);
linearvariables = used_variables(find(variabletype(used_variables)==0));
end
needednonlinear = nonlinearvariables(ismembcYALMIP(nonlinearvariables,used_variables));
linearinnonlinear = find(sum(abs(monomtable(needednonlinear,:)),1));
missinglinear = setdiff(linearinnonlinear(:),linearvariables);
used_variables = uniquestripped([used_variables(:);missinglinear(:)]);
% *************************************************************************
%% So are we done now? No... What about variables hiding inside so called
% evaluation variables. We detect these, and at the same time set up the
% structures needed to support general functions such as exp, log, etc
% NOTE : This is experimental code
% FIX : Clean up...
% *************************************************************************
[evalMap,evalVariables,used_variables,nonlinearvariables,linearvariables] = detectHiddenNonlinear(used_variables,options,nonlinearvariables,linearvariables,evalVariables);
% Attach information on the evaluation based variables that was generated
% when the model was expanded
if ~isempty(evalMap)
for i = 1:length(operators)
index = find(operators{i}.properties.models(1) == used_variables(evalVariables));
if ~isempty(index)
evalMap{index}.properties = operators{i}.properties;
end
end
for i = 1:length(evalMap)
for j = 1:length(evalMap{i}.computes)
evalMap{i}.computes(j) = find(evalMap{i}.computes(j) == used_variables);
end
end
% Add information about which argument is the variable
for i = 1:length(evalMap)
for j = 1:length(evalMap{i}.arg)-1
if isa(evalMap{i}.arg{j},'sdpvar')
evalMap{i}.argumentIndex = j;
break
end
end
end
end
% *************************************************************************
%% REMOVE UNNECESSARY VARIABLES FROM PROBLEM
% *************************************************************************
if length(used_variables)<yalmip('nvars')
c = c(used_variables);
if 0
% very slow in some extreme cases
Q = Q(:,used_variables);Q = Q(used_variables,:);
else
[i,j,s] = find(Q);
keep = ismembcYALMIP(i,used_variables) & ismembcYALMIP(j,used_variables);
i = i(keep);
j = j(keep);
s = s(keep);
[ii,jj] = ismember(1:length(Q),used_variables);
i = jj(i);
j = jj(j);
Q = sparse(i,j,s,length(used_variables),length(used_variables));
end
if ~isempty(F_struc)
F_struc = sparse(F_struc(:,[1 1+used_variables]));
end
end
% *************************************************************************
%% Map variables and constraints in low-rank definition to local stuff
% *************************************************************************
if ~isempty(lowrankdetails)
% Identifiers of the SDP constraints
lmiid = getlmiid(F);
for i = 1:length(lowrankdetails)
lowrankdetails{i}.id = find(ismember(lmiid,lowrankdetails{i}.id));
if ~isempty(lowrankdetails{i}.variables)
index = ismember(used_variables,lowrankdetails{i}.variables);
lowrankdetails{i}.variables = find(index);
end
end
end
% *************************************************************************
%% SPECIAL VARIABLES
% Relax = 1 : relax both integers and nonlinear stuff
% Relax = 2 : relax integers
% Relax = 3 : relax nonlinear stuff
% *************************************************************************
if (options.relax==1) | (options.relax==3)
nonlins = [];
end
if (options.relax == 1) | (options.relax==2)
integer_variables = [];
binary_variables = [];
semicont_variables = [];
old_binary_variables = find(ismember(used_variables,old_binary_variables));
else
integer_variables = find(ismember(used_variables,integer_variables));
binary_variables = find(ismember(used_variables,binary_variables));
semicont_variables = find(ismember(used_variables,semicont_variables));
old_binary_variables = find(ismember(used_variables,old_binary_variables));
end
parametric_variables = find(ismember(used_variables,parametric_variables));
extended_variables = find(ismember(used_variables,yalmip('extvariables')));
aux_variables = find(ismember(used_variables,yalmip('auxvariables')));
if ~isempty(K.sos)
for i = 1:length(K.sos.type)
K.sos.variables{i} = find(ismember(used_variables,K.sos.variables{i}));
K.sos.variables{i} = K.sos.variables{i}(:);
end
end
% if ~isempty(semicont_variables) && ~solver.constraint.semivar
% [F_struc,K,binary_variables] = expandsemivar(F_struc,K,semicont_variables);
% end
% *************************************************************************
%% Equality constraints not supported or supposed to be removed
% *************************************************************************
% We may save some data in order to reconstruct
% dual variables related to equality constraints that
% have been removed.
oldF_struc = [];
oldQ = [];
oldc = [];
oldK = K;
Fremoved = [];
if (K.f>0)
if (isequal(solver.tag,'BNB') && ~solver.lower.constraint.equalities.linear) || (isequal(solver.tag,'BMIBNB') && ~solver.lowersolver.constraint.equalities.linear)
badLower = 1;
else
badLower = 0;
end
% reduce if user explicitely says remove, or user says nothing but
% solverdefinitions does, and there are no nonlinear variables
if ~badLower && ((options.removeequalities==1 | options.removeequalities==2) & isempty(intersect(used_variables,nonlinearvariables))) | ((options.removeequalities==0) & (solver.constraint.equalities.linear==-1))
showprogress('Solving equalities',options.showprogress);
[x_equ,H,A_equ,b_equ,factors] = solveequalities(F_struc,K,options.removeequalities==1);
% Exit if no consistent solution exist
if (norm(A_equ*x_equ-b_equ,'inf')>1e-5)%sqrt(eps)*size(A_equ,2))
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(1,'YALMIP');
diagnostic.problem = 1;
solution = diagnostic;
solution.variables = used_variables(:);
solution.optvar = x_equ;
% And we are done! Save the result
% sdpvar('setSolution',solution);
return
end
% We dont need the rows for equalities anymore
oldF_struc = F_struc;
oldc = c;
oldQ = Q;
oldK = K;
F_struc = F_struc(K.f+1:end,:);
K.f = 0;
Fold = F;
[nlmi neq]=sizeOLD(F);
iseq = is(Fold(1:(nlmi+neq)),'equality');
F = Fold(find(~iseq));
Fremoved = Fold(find(iseq));
% No variables left. Problem solved!
if size(H,2)==0
diagnostic.solvertime = 0;
diagnostic.info = yalmiperror(0,'YALMIP');
diagnostic.problem = 0;
solution = diagnostic;
solution.variables = used_variables(:);
solution.optvar = x_equ;
% And we are done! Save the result
% Note, no dual is saved
yalmip('setSolution',solution);
p = checkset(F);
if any(p<1e-5)
diagnostic.info = yalmiperror(1,'YALMIP');
diagnostic.problem = 1;
end
return
end
showprogress('Converting problem to new basis',options.showprogress)
% objective in new basis
f = f + x_equ'*Q*x_equ;
c = H'*c + 2*H'*Q*x_equ;
Q = H'*Q*H;Q=((Q+Q')/2);
% LMI in new basis
F_struc = [F_struc*[1;x_equ] F_struc(:,2:end)*H];
else
% Solver does not support equality constraints and user specifies
% double-sided inequalitis to remove them, or solver is used from
% lmilab or similiar solver
if (solver.constraint.equalities.linear==0 | options.removeequalities==-1 | badLower)
% Add equalities
F_struc = [-F_struc(1:1:K.f,:);F_struc];
K.l = K.l+K.f*2;
% Keep this in mind...
K.fold = K.f;
K.f = 0;
end
% For simpliciy we introduce a dummy coordinate change
x_equ = 0;
H = 1;
factors = [];
end
else
x_equ = 0;
H = 1;
factors = [];
end
% *************************************************************************
%% Setup the initial solution
% *************************************************************************
x0 = [];
if options.usex0
if solver.supportsinitial == 0
error('You have specified an initial point, but the selected solver does not support warm-starts through YALMIP');
end
if options.relax
x0_used = relaxdouble(recover(used_variables));
else
%FIX : Do directly using yalmip('solution')
%solution = yalmip('getsolution');
x0_used = double(recover(used_variables));
end
x0 = zeros(sdpvar('nvars'),1);
x0(used_variables) = x0_used(:);
if ~solver.supportsinitialNAN
x0(isnan(x0))=0;
end
end
if ~isempty(x0)
% Get a coordinate in the reduced space
x0 = H\(x0(used_variables)-x_equ);
end
% Monomial table for nonlinear variables
% FIX : Why here!!! mt handled above also
[mt,variabletype] = yalmip('monomtable');
if size(mt,1)>size(mt,2)
mt(size(mt,1),size(mt,1)) = 0;
end
% In local variables
mt = mt(used_variables,used_variables);
variabletype = variabletype(used_variables);
if (options.relax == 1)|(options.relax==3)
mt = speye(length(used_variables));
variabletype = variabletype*0;
end
% FIX : Make sure these things work...
lub = yalmip('getbounds',used_variables);
lb = lub(:,1)-inf;
ub = lub(:,2)+inf;
lb(old_binary_variables) = max(lb(old_binary_variables),0);
ub(old_binary_variables) = min(ub(old_binary_variables),1);
% This does not work if we have used removeequalities, so we clear them for
% safety. note that bounds are not guaranteed to be used according to the
% manual, so this is allowed, although it might be a bit inconsistent to
% some users.
if ~isempty(oldc)
lb = [];
ub = [];
end
% Sanity check
if ~isempty(c)
if any(isnan(c) )
error('You have NaNs in your objective!. Read more: http://users.isy.liu.se/johanl/yalmip/pmwiki.php?n=Extra.NANInModel')
end
end
if ~isempty(Q)
if any(any(isnan(Q)))
error('You have NaNs in your quadratic objective!. Read more: http://users.isy.liu.se/johanl/yalmip/pmwiki.php?n=Extra.NANInModel')
end
end
if ~isempty(lb)
if any(isnan(lb))
error('You have NaNs in a lower bound!. Read more: http://users.isy.liu.se/johanl/yalmip/pmwiki.php?n=Extra.NANInModel')
end
end
if ~isempty(ub)
if any(isnan(ub))
error('You have NaNs in an upper bound!.Read more: http://users.isy.liu.se/johanl/yalmip/pmwiki.php?n=Extra.NANInModel')
end
end
if ~isempty(F_struc)
if any(any(isnan(F_struc)))
error('You have NaNs in your constraints!. Read more: http://users.isy.liu.se/johanl/yalmip/pmwiki.php?n=Extra.NANInModel')
end
end
% *************************************************************************
%% GENERAL DATA EXCHANGE WITH SOLVER
% *************************************************************************
interfacedata.F_struc = F_struc;
interfacedata.c = c;
interfacedata.Q = Q;
interfacedata.f = f;
interfacedata.K = K;
interfacedata.lb = lb;
interfacedata.ub = ub;
interfacedata.x0 = x0;
interfacedata.options = options;
interfacedata.solver = solver;
interfacedata.monomtable = mt;
interfacedata.variabletype = variabletype;
interfacedata.integer_variables = integer_variables;
interfacedata.binary_variables = binary_variables;
interfacedata.semicont_variables = semicont_variables;
interfacedata.semibounds = [];
interfacedata.uncertain_variables = [];
interfacedata.parametric_variables= parametric_variables;
interfacedata.extended_variables = extended_variables;
interfacedata.aux_variables = aux_variables;
interfacedata.used_variables = used_variables;
interfacedata.lowrankdetails = lowrankdetails;
interfacedata.problemclass = ProblemClass;
interfacedata.KCut = KCut;
interfacedata.getsolvertime = 1;
% Data to be able to recover duals when model is reduced
interfacedata.oldF_struc = oldF_struc;
interfacedata.oldc = oldc;
interfacedata.oldK = oldK;
interfacedata.factors = factors;
interfacedata.Fremoved = Fremoved;
interfacedata.evalMap = evalMap;
interfacedata.evalVariables = evalVariables;
interfacedata.evaluation_scheme = [];
if strcmpi(solver.tag,'bmibnb')
interfacedata.equalitypresolved = 0;
interfacedata.presolveequalities = 1;
else
interfacedata.equalitypresolved = 1;
interfacedata.presolveequalities = 1;
end
interfacedata.ProblemClass = ProblemClass;
interfacedata.dualized = is(F,'dualized');
% *************************************************************************
%% GENERAL DATA EXCANGE TO RECOVER SOLUTION AND UPDATE YALMIP VARIABLES
% *************************************************************************
recoverdata.H = H;
recoverdata.x_equ = x_equ;
recoverdata.used_variables = used_variables;
%%
function yesno = warningon
s = warning;
if isa(s,'char')
yesno = isequal(s,'on');
else
yesno = isequal(s(1).state,'on');
end
%%
function [evalMap,evalVariables,used_variables,nonlinearvariables,linearvariables] = detectHiddenNonlinear(used_variables,options,nonlinearvariables,linearvariables,eIN)
%evalVariables = yalmip('evalVariables');
evalVariables = eIN;
old_used_variables = used_variables;
goon = 1;
if ~isempty(evalVariables)
while goon
% Which used_variables are representing general functions
% evalVariables = yalmip('evalVariables');
evalVariables = eIN;
usedEvalVariables = find(ismember(used_variables,evalVariables));
evalMap = yalmip('extstruct',used_variables(usedEvalVariables));
if ~isa(evalMap,'cell')
evalMap = {evalMap};
end
% Find all variables used in the arguments of these functions
hidden = [];
for i = 1:length(evalMap)
% Find main main argument (typically first argument, but this
% could be different in a user-specified sdpfun object)
for aux = 1:length(evalMap{i}.arg)-1
if isa(evalMap{i}.arg{aux},'sdpvar')
X = evalMap{i}.arg{aux};
break
end
end
n = length(X);
if isequal(getbase(X),[spalloc(n,1,0) speye(n)])% & is(evalMap{i}.arg{1},'linear')
for j = 1:length(evalMap{i}.arg)-1
% The last argument is the help variable z in the
% transformation from f(ax+b) to f(z),z==ax+b. We should not
% use this transformation if the argument already is unitary
hidden = [hidden getvariables(evalMap{i}.arg{j})];
end
else
for j = 1:length(evalMap{i}.arg)
% The last argument is the help variable z in the
% transformation from f(ax+b) to f(z),z==ax+b. We should not
% use this transformation if the argument already is unitary
hidden = [hidden getvariables(evalMap{i}.arg{j})];
end
end
end
used_variables = union(used_variables,hidden);
% The problem is that linear terms might be missing in problems with only
% nonlinear expressions
[monomtable,variabletype] = yalmip('monomtable');
if (options.relax==1)|(options.relax==3)
monomtable = [];
nonlinearvariables = [];
linearvariables = used_variables;
else
nonlinearvariables = find(variabletype);
linearvariables = used_variables(find(variabletype(used_variables)==0));
end
needednonlinear = nonlinearvariables(ismembcYALMIP(nonlinearvariables,used_variables));
linearinnonlinear = find(sum(abs(monomtable(needednonlinear,:)),1));
missinglinear = setdiff(linearinnonlinear(:),linearvariables);
used_variables = uniquestripped([used_variables(:);missinglinear(:)]);
usedEvalVariables = find(ismember(used_variables,evalVariables));
evalMap = yalmip('extstruct',used_variables(usedEvalVariables));
if ~isa(evalMap,'cell')
evalMap = {evalMap};
end
evalVariables = usedEvalVariables;
for i = 1:length(evalMap)
for aux = 1:length(evalMap{i}.arg)-1
if isa(evalMap{i}.arg{aux},'sdpvar')
X = evalMap{i}.arg{aux};
break
end
end
n = length(X);
if isequal(getbase(X),[spalloc(n,1,0) speye(n)])
index = ismember(used_variables,getvariables(X));
evalMap{i}.variableIndex = find(index);
else
index = ismember(used_variables,getvariables(evalMap{i}.arg{end}));
evalMap{i}.variableIndex = find(index);
end
end
goon = ~isequal(used_variables,old_used_variables);
old_used_variables = used_variables;
end
else
evalMap = [];
end
function evalVariables = determineEvaluationBased(operators)
evalVariables = [];
for i = 1:length(operators)
if strcmpi(operators{i}.properties.model,'callback')
evalVariables = [evalVariables operators{i}.properties.models];
end
end
function [Fnew,changed] = convertsocp2NONLINEAR(F);
changed = 0;
socps = find(is(F,'socp'));
Fsocp = F(socps);
Fnew = F;
if length(socps) > 0
changed = 1;
Fnew(socps) = [];
for i = 1:length(Fsocp)
z = sdpvar(Fsocp(i));
Fnew = [Fnew, z(1)>=0, z(1)^2 >= z(2:end)'*z(2:end)];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
selectsolver.m
|
.m
|
LMI-Matlab-master/yalmip/extras/selectsolver.m
| 23,046 |
utf_8
|
1cf76f327e2fcc2f98d45d6024ced027
|
function [solver,problem,forced_choice] = selectsolver(options,ProblemClass,solvers,socp_are_really_qc,allsolvers);
%SELECTSOLVER Internal function to select solver based on problem category
problem = 0;
% UNDOCUMENTED
force_solver = yalmip('solver');
if length(force_solver)>0
options.solver = force_solver;
end
% YALMIP has discovered in an previous call that the model isn't a GP, and
% now searches for a non-GP solver
if options.thisisnotagp
ProblemClass.gppossible = 0;
end
% ***************************************************
% Maybe the user is stubborn and wants to pick solver
% ***************************************************
forced_choice = 0;
if length(options.solver)>0 & isempty(findstr(options.solver,'*'))
if strfind(options.solver,'+')
forced_choice = 1;
options.solver = strrep(options.solver,'+','');
end
% Create tags with version also
temp = expandSolverName(solvers);
opsolver = lower(options.solver);
splits = findstr(opsolver,',');
if isempty(splits)
names{1} = opsolver;
else
start = 1;
for i = 1:length(splits)
names{i} = opsolver(start:splits(i)-1);
start = splits(i)+1;
end
names{end+1} = opsolver(start:end);
end
index1 = [];
index2 = [];
for i = 1:length(names)
index1 = [index1 find(strcmpi({solvers.tag},names{i}))];
index2 = [index1 find(strcmpi({temp.tag},names{i}))];
end
if isempty(index1) & isempty(index2)
% Specified solver not found among available solvers
% Is it even a supported solver
temp = expandSolverName(allsolvers);
for i = 1:length(names)
index1 = [index1 find(strcmp(lower({allsolvers.tag}),names{i}))];
index2 = [index1 find(strcmp(lower({temp.tag}),names{i}))];
end
if isempty(index1) & isempty(index2)
problem = -9;
else
problem = -3;
end
solver = [];
return;
else
solvers = solvers(union(index1,index2));
end
end
% if forced_choice
% solver = solvers(end);
% problem = 0;
% return
% end
% ************************************************
% Prune based on objective
% ************************************************
if ProblemClass.objective.sigmonial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).objective.sigmonial;
end
solvers = solvers(find(keep));
end
if ProblemClass.objective.polynomial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.equalities.quadratic | solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex | solvers(i).objective.polynomial | solvers(i).objective.sigmonial;
end
solvers = solvers(find(keep));
end
if ProblemClass.objective.quadratic.nonconvex & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).objective.polynomial | solvers(i).objective.sigmonial | solvers(i).objective.quadratic.nonconvex;
end
solvers = solvers(find(keep));
end
if ProblemClass.objective.quadratic.convex & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
direct = solvers(i).objective.polynomial | solvers(i).objective.sigmonial | solvers(i).objective.quadratic.nonconvex | solvers(i).objective.quadratic.convex;
indirect = solvers(i).constraint.inequalities.semidefinite.linear | solvers(i).constraint.inequalities.secondordercone.linear;
if direct | indirect
keep(i)=1;
else
keep(i)=0;
end
end
solvers = solvers(find(keep));
end
if ProblemClass.objective.linear & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).objective.polynomial | solvers(i).objective.sigmonial | solvers(i).objective.quadratic.nonconvex | solvers(i).objective.quadratic.convex | solvers(i).objective.linear;
end
solvers = solvers(find(keep));
end
if ProblemClass.objective.maxdet.convex & ~ProblemClass.objective.linear & ~ProblemClass.objective.quadratic.convex & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).objective.maxdet.convex | solvers(i).constraint.inequalities.semidefinite.linear;
end
solvers = solvers(find(keep));
end
if ProblemClass.objective.maxdet.convex & (ProblemClass.objective.linear | ProblemClass.objective.quadratic.convex) & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).objective.maxdet.convex;
end
solvers = solvers(find(keep));
end
if ProblemClass.objective.maxdet.nonconvex & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).objective.maxdet.nonconvex;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Prune based on rank constraints
% ******************************************************
if ProblemClass.constraint.inequalities.rank & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.rank;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Prune based on semidefinite constraints
% ******************************************************
if ProblemClass.constraint.inequalities.semidefinite.sigmonial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.semidefinite.sigmonial;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.semidefinite.polynomial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.semidefinite.sigmonial | solvers(i).constraint.inequalities.semidefinite.polynomial;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.semidefinite.quadratic & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.semidefinite.sigmonial | solvers(i).constraint.inequalities.semidefinite.polynomial | solvers(i).constraint.inequalities.semidefinite.quadratic;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.semidefinite.linear & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.semidefinite.sigmonial | solvers(i).constraint.inequalities.semidefinite.polynomial | solvers(i).constraint.inequalities.semidefinite.quadratic | solvers(i).constraint.inequalities.semidefinite.linear;
end
solvers = solvers(find(keep));
end
% If user has specified a, e.g., LP solver for an SDP when using OPTIMIZER,
% we must bail out, as there is no chance this model instantiates as an LP.
if forced_choice & (ProblemClass.constraint.inequalities.semidefinite.linear | ProblemClass.constraint.inequalities.semidefinite.quadratic | ProblemClass.constraint.inequalities.semidefinite.polynomial | ProblemClass.constraint.inequalities.semidefinite.sigmonial)
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.semidefinite.sigmonial | solvers(i).constraint.inequalities.semidefinite.polynomial | solvers(i).constraint.inequalities.semidefinite.quadratic | solvers(i).constraint.inequalities.semidefinite.linear;
end
solvers = solvers(find(keep));
end
% Similarily, we have a SOCP by definition. We must support that
if forced_choice & ~socp_are_really_qc & (ProblemClass.constraint.inequalities.secondordercone.linear | ProblemClass.constraint.inequalities.secondordercone.nonlinear)
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.secondordercone.linear;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Prune based on cone constraints
% ******************************************************
if ProblemClass.constraint.inequalities.secondordercone.linear & ~socp_are_really_qc & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.secondordercone.linear | solvers(i).constraint.inequalities.semidefinite.linear | solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.secondordercone.nonlinear & ~socp_are_really_qc & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.secondordercone.nonlinear | solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.rotatedsecondordercone & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.rotatedsecondordercone | solvers(i).constraint.inequalities.secondordercone.linear | solvers(i).constraint.inequalities.semidefinite.linear;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.powercone & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.powercone;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Prune based on element-wise inequality constraints
% ******************************************************
if ProblemClass.constraint.inequalities.elementwise.sigmonial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.elementwise.sigmonial;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.elementwise.polynomial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex | solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.elementwise.quadratic.nonconvex & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial | solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.elementwise.quadratic.convex | (ProblemClass.constraint.inequalities.secondordercone.linear & socp_are_really_qc) & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial | solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex | solvers(i).constraint.inequalities.elementwise.quadratic.convex | solvers(i).constraint.inequalities.secondordercone.linear | solvers(i).constraint.inequalities.semidefinite.linear;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.inequalities.elementwise.linear & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial | solvers(i).constraint.inequalities.semidefinite.quadratic | solvers(i).constraint.inequalities.elementwise.linear;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Prune based on element-wise constraints
% ******************************************************
if ProblemClass.constraint.equalities.sigmonial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.equalities.sigmonial;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.equalities.polynomial & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
indirect = solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex | solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial;
indirect = indirect | solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial;
direct = solvers(i).constraint.equalities.sigmonial | solvers(i).constraint.equalities.polynomial;
keep(i) = direct | indirect;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.equalities.quadratic & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
indirect = solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial | solvers(i).constraint.inequalities.elementwise.quadratic.nonconvex;
direct = solvers(i).constraint.equalities.sigmonial | solvers(i).constraint.equalities.polynomial | solvers(i).constraint.equalities.quadratic;
keep(i) = direct | indirect;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.equalities.linear & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
indirect = solvers(i).constraint.inequalities.elementwise.linear | solvers(i).constraint.inequalities.elementwise.sigmonial | solvers(i).constraint.inequalities.elementwise.polynomial;
direct = solvers(i).constraint.equalities.linear | solvers(i).constraint.equalities.sigmonial | solvers(i).constraint.equalities.polynomial;
keep(i) = direct | indirect;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Discrete data
% ******************************************************
if ProblemClass.constraint.integer & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.integer;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.binary & ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.integer | solvers(i).constraint.binary;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.sos1
keep = ones(length(solvers),1);
for i = 1:length(solvers)
%keep(i) = solvers(i).constraint.integer | solvers(i).constraint.binary | solvers(i).constraint.sos2;
keep(i) = solvers(i).constraint.sos2;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.sos2
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.integer | solvers(i).constraint.binary | solvers(i).constraint.sos2;
end
solvers = solvers(find(keep));
end
if ProblemClass.constraint.semicont
keep = ones(length(solvers),1);
for i = 1:length(solvers)
%keep(i) = solvers(i).constraint.integer | solvers(i).constraint.binary | solvers(i).constraint.sos2;
keep(i) = solvers(i).constraint.semivar;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Equalities with multiple monomoials (rule out GP)
% ******************************************************
if ProblemClass.constraint.equalities.multiterm
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.equalities.multiterm;
end
solvers = solvers(find(keep));
end
% FIXME
% No support for multiterm is YALMIPs current way of saying "GP solver". We
% use this flag to prune GPs based on objective too
if ~ProblemClass.gppossible
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.equalities.multiterm;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Complementarity constraints
% ******************************************************
if ProblemClass.constraint.complementarity.linear
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).constraint.complementarity.linear | solvers(i).constraint.integer | solvers(i).constraint.binary | solvers(i).constraint.equalities.polynomial | solvers(i).constraint.equalities.quadratic;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Interval data
% ******************************************************
if ProblemClass.interval
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = solvers(i).interval;
end
solvers = solvers(find(keep));
end
% ******************************************************
% Parametric problem
% ******************************************************
if ~forced_choice
keep = ones(length(solvers),1);
for i = 1:length(solvers)
keep(i) = (ProblemClass.parametric == solvers(i).parametric);
end
solvers = solvers(find(keep));
end
% ******************************************************
% Exponential cone representable (exp, log,...)
% ******************************************************
keep = ones(length(solvers),1);
if ~forced_choice
for i = 1:length(solvers)
keep(i) = (ProblemClass.exponentialcone <= solvers(i).exponentialcone) || (ProblemClass.exponentialcone <= solvers(i).evaluation);
end
solvers = solvers(find(keep));
end
% ******************************************************
% General functions (sin, cos,...)
% ******************************************************
keep = ones(length(solvers),1);
if ~forced_choice
for i = 1:length(solvers)
keep(i) = (ProblemClass.evaluation <= solvers(i).evaluation) || (ProblemClass.exponentialcone && solvers(i).exponentialcone);
end
solvers = solvers(find(keep));
end
% FIX : UUUUUUGLY
if isempty(solvers)
solver = [];
else
if length(options.solver)>0
solver = [];
% FIX : Re-use from above
opsolver = lower(options.solver);
splits = findstr(opsolver,',');
if isempty(splits)
names{1} = opsolver;
else
names = {};
start = 1;
for i = 1:length(splits)
names{i} = opsolver(start:splits(i)-1);
start = splits(i)+1;
end
names{end+1} = opsolver(start:end);
end
temp = solvers;
for i = 1:length(temp)
if length(temp(i).version)>0
temp(i).tag = lower([temp(i).tag '-' temp(i).version]);
end
end
for i = 1:length(names)
if isequal(names{i},'*')
solver = solvers(1);
break
else
j = find(strcmpi(lower({solvers.tag}),names{i}));
if ~isempty(j)
solver = solvers(j(1));
break
end
j = find(strcmpi(lower({temp.tag}),names{i}));
if ~isempty(j)
solver = solvers(j(1));
break
end
end
end
else
solver = solvers(1);
end
end
if isempty(solver)
if length(options.solver)>0 % User selected available solver, but it is not applicable
problem = -4;
else
problem = -2;
end
end
% FIX : Hack when chosing the wrong fmincon thingy
if ~isempty(solver)
c1 = (length(options.solver)==0 | isequal(lower(options.solver),'fmincon')) & isequal(lower(solver.tag),'fmincon') & isequal(solver.version,'geometric');
c2 = (length(options.solver)==0 | isequal(lower(options.solver),'snopt')) & isequal(lower(solver.tag),'snopt') & isequal(solver.version,'geometric');
if c1 | c2
if ~(ProblemClass.objective.sigmonial | ProblemClass.constraint.inequalities.elementwise.sigmonial)
solver.version = 'standard';
solver.call = strrep(solver.call,'gp','');
solver.objective.linear = 1;
solver.objective.quadratic.convex = 1;
solver.objective.quadratic.nonconvex = 1;
solver.objective.polynomial = 1;
solver.objective.sigmonial = 1;
solver.constraint.equalities.elementwise.linear = 1;
solver.constraint.equalities.elementwise.quadratic.convex = 1;
solver.constraint.equalities.elementwise.quadratic.nonconvex = 1;
solver.constraint.equalities.elementwise.polynomial = 1;
solver.constraint.equalities.elementwise.sigmonial = 1;
solver.constraint.inequalities.elementwise.linear = 1;
solver.constraint.inequalities.elementwise.quadratic.convex = 1;
solver.constraint.inequalities.elementwise.quadratic.nonconvex = 1;
solver.constraint.inequalities.elementwise.polynomial = 1;
solver.constraint.inequalities.elementwise.sigmonial = 1;
solver.constraint.inequalities.semidefinite.linear = 1;
solver.constraint.inequalities.semidefinite.quadratic = 1;
solver.constraint.inequalities.semidefinite.polynomial = 1;
solver.dual = 1;
solver.evaluation = 1;
end
end
end
function temp = expandSolverName(temp)
for i = 1:length(temp)
if length(temp(i).version)>0
temp(i).tag = lower([temp(i).tag '-' temp(i).version]);
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
build_recursive_scheme.m
|
.m
|
LMI-Matlab-master/yalmip/extras/build_recursive_scheme.m
| 4,784 |
utf_8
|
3552dcf000e115ccb8eebfa81ab0dc22
|
function model = build_recursive_scheme(model);
model.evaluation_scheme = [];
model.deppattern = model.monomtable | model.monomtable;
% Figure out arguments in all polynomials & sigmonials. This info is
% used on several places, so we might just as well save it
model.monomials = find(model.variabletype);
model.monomialMap = cell(length(model.monomials),1);
model.evaluation_scheme = [];
%M = model.monomtable(model.monomials,:);
MM= model.monomtable(model.monomials,:)';
for i = 1:length(model.monomials)
% model.monomialMap{i}.variableIndex = find(model.monomtable(model.monomials(i),:));
% model.monomialMap{i}.variableIndex = find(M(i,:));
model.monomialMap{i}.variableIndex = find(MM(:,i));
end
if ~isempty(model.evalMap)
remainingEvals = ones(1,length(model.evalVariables));
remainingMonoms = ones(1,length(model.monomials));
model = recursive_call(model,remainingEvals,remainingMonoms);
% Define a dependency structure
% (used to speed up Jacobian computations etc)
model.isevalVariable = zeros(1,size(model.monomtable,1));
model.isevalVariable(model.evalVariables) = 1;
compute_depenedency = 1:size(model.monomtable,1);
% remove purely linear variables, dependency is already computed
compute_depenedency = setdiff(compute_depenedency,setdiff(find(model.variabletype==0),model.evalVariables));
if isequal(model.evaluation_scheme{1}.group,'monom')
% This first level of monomials are simply defined by the monomial
% table, hence dependency is already computed
compute_depenedency = setdiff(compute_depenedency,model.monomials(model.evaluation_scheme{1}.variables));
end
for i = compute_depenedency
k = depends_on(model,i);
model.deppattern(i,k) = 1;
end
else
% Only monomials
model.evaluation_scheme{1}.group = 'monom';
model.evaluation_scheme{1}.variables = 1:nnz(model.variabletype);
end
function r = depends_on(model,k)
if model.variabletype(k)
vars = find(model.monomtable(k,:));
r=[];
for i = 1:length(vars)
r = [r depends_on(model,vars(i))];
end
elseif model.isevalVariable(k)%ismember(k,model.evalVariables)
j = find(k == model.evalVariables);
r = [];
for i = 1:length(model.evalMap{j}.variableIndex)
argument = model.evalMap{j}.variableIndex(i);
r = [r argument depends_on(model,argument)];
end
else
r = k;
end
function model = recursive_call(model,remainingEvals,remainingMonoms)
if ~any(remainingEvals) & ~any(remainingMonoms)
return
end
stillE = find(remainingEvals);
stillM = find(remainingMonoms);
% Extract arguments in first layer
if any(remainingEvals)
for i = 1:length(model.evalMap)
composite_eval_expression(i) = any(ismembcYALMIP(model.evalMap{i}.variableIndex,model.evalVariables(stillE)));
composite_eval_expression(i) = composite_eval_expression(i) | any(ismembcYALMIP(model.evalMap{i}.variableIndex,model.monomials(stillM)));
end
end
if any(remainingMonoms)
if issorted(model.evalVariables(stillE))
for i = 1:length(model.monomials)
% composite_monom_expression(i) = any(ismember(model.monomialMap{i}.variableIndex,model.monomials(stillM)));
% composite_monom_expression(i) = composite_monom_expression(i) | any(ismember(model.monomialMap{i}.variableIndex,model.evalVariables(stillE)));
composite_monom_expression(i) = any(ismembcYALMIP(model.monomialMap{i}.variableIndex,model.evalVariables(stillE)));
end
else
for i = 1:length(model.monomials)
% composite_monom_expression(i) = any(ismember(model.monomialMap{i}.variableIndex,model.monomials(stillM)));
% composite_monom_expression(i) = composite_monom_expression(i) | any(ismember(model.monomialMap{i}.variableIndex,model.evalVariables(stillE)));
composite_monom_expression(i) = any(ismember(model.monomialMap{i}.variableIndex,model.evalVariables(stillE)));
end
end
end
% Bottom layer
if ~isempty(model.monomials) & any(remainingMonoms)
if ~isempty(find(~composite_monom_expression & remainingMonoms))
model.evaluation_scheme{end+1}.group = 'monom';
model.evaluation_scheme{end}.variables = find(~composite_monom_expression & remainingMonoms);
end
remainingMonoms = composite_monom_expression & remainingMonoms;
end
% Bottom layer
if ~isempty(model.evalMap) & any(remainingEvals)
if ~isempty(find(~composite_eval_expression & remainingEvals));
model.evaluation_scheme{end+1}.group = 'eval';
model.evaluation_scheme{end}.variables = find(~composite_eval_expression & remainingEvals);
end
remainingEvals = composite_eval_expression & remainingEvals;
end
model = recursive_call(model,remainingEvals,remainingMonoms);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
dual2cell.m
|
.m
|
LMI-Matlab-master/yalmip/extras/dual2cell.m
| 546 |
utf_8
|
18deb951cf9dacb4b2e3d2faf4166ccd
|
function X = dual2cell(dual_vec,K)
%DUAL2CELL Internal function for organizing dual data
row = 1;
X.f = dual_vec(row:row+K.f-1);
row = row + K.f;
X.l = dual_vec(row:row+K.l-1);
row = row + K.l;
for k = 1:length(K.q)
X.q{k} = dual_vec(row:row+K.q(k)-1);
row = row + K.q(k);
end
for k = 1:length(K.r)
X.r{k} = dual_vec(row:row+K.r(k)-1);
row = row + K.r(k);
end
for k = 1:length(K.s)
X.s{k} = mat(dual_vec(row:row+K.s(k)^2-1));
row = row + K.s(k)^2;
end
function Y = mat(X)
n = sqrt(length(X));
Y = reshape(X,n,n);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
amplexpr.m
|
.m
|
LMI-Matlab-master/yalmip/extras/amplexpr.m
| 2,162 |
utf_8
|
0a47dd2e95c44a17fd78af99ed8950d6
|
function symb_pvec = amplexpr(pvec)
%AMPLEXPR Converts SDPVAR variable to AMPL string
for pi = 1:size(pvec,1)
for pj = 1:size(pvec,2)
p = pvec(pi,pj);
if isa(p,'double')
symb_p = num2str(p);
else
LinearVariables = depends(p);
x = recover(LinearVariables);
exponent_p = full(exponents(p,x));
names = cell(length(LinearVariables),1);
for i = 1:length(LinearVariables)
names{i}=['x[' num2str(LinearVariables(i)) ']'];
end
symb_p = '';
if all(exponent_p(1,:)==0)
symb_p = num2str(getbasematrix(p,0));
exponent_p = exponent_p(2:end,:);
end
for i = 1:size(exponent_p,1)
coeff = getbasematrixwithoutcheck(p,i);
switch full(coeff)
case 1
coeff='+';
case -1
coeff = '-';
otherwise
if coeff >0
coeff = ['+' num2str2(coeff)];
else
coeff=num2str2(coeff);
end
end
if strcmp(symb_p,'') & (strcmp(coeff,'+') | strcmp(coeff,'-'))
symb_p = [symb_p coeff symbmonom(names,exponent_p(i,:))];
else
symb_p = [symb_p coeff '*' symbmonom(names,exponent_p(i,:))];
end
end
if symb_p(1)=='+'
symb_p = symb_p(2:end);
end
end
symb_p = strrep(symb_p,'+*','+');
symb_p = strrep(symb_p,'-*','-');
symb_pvec{pi,pj} = symb_p;
end
end
function s = symbmonom(names,monom)
s = '';
for j = 1:length(monom)
if monom(j)>0
if strcmp(s,'')
s = [s names{j}];
else
s = [s '*' names{j}];
end
end
if monom(j)>1
s = [s '^' num2str(monom(j))];
end
end
function s = num2str2(x)
s = num2str(x);
if isequal(s,'1')
s = '';
end
if isequal(s,'-1')
s = '-';
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
saveampl.m
|
.m
|
LMI-Matlab-master/yalmip/extras/saveampl.m
| 7,486 |
utf_8
|
0b44bf1f619d5b35fc97f2c1e9b865f5
|
function solution = saveampl(varargin)
%SAVEAMPL Saves a problem definition in AMPL format
%
% SAVEAMPL(F,h,'filename') Saves the problem min(h(x)), F(x)>0 to the file filename
% SAVEAMPL(F,h) A "Save As"- box will be opened
%
% YALMIP is currently able to save problems with linear and non-linear
% element-wise inequality and equality constraints. Integer and binary
% variables are also supported.
%
% Note that YALMIP changes the variable names. Continuous variables
% are called x, binary are called y while z denotes integer variables.
F = varargin{1};
h = varargin{2};
% Expand nonlinear operators
options = sdpsettings;
[F2,failure,cause] = expandmodel(F,h,options);
if failure % Convexity propgation failed
interfacedata = [];
recoverdata = [];
solver = '';
diagnostic.solvertime = 0;
diagnostic.problem = 14;
diagnostic.info = yalmiperror(14,cause);
return
end
%% FIXME: SYNC with expandmodel etc. Same in compileinterfacedata
setupBounds(F,options,yalmip('extvariables'));
solver.constraint.equalities.polynomial=0;
solver.constraint.binary=1;
solver.constraint.integer=0;
[F] = modelComplementarityConstraints(F,solver,[]);
%%
nvars = yalmip('nvars');
vars = depends(F);
vars = unique([vars depends(h)]);
binvars = yalmip('binvariables');
integervars = yalmip('intvariables');
for i = 1:length(F)
if is(F(i),'binary')
binvars = [binvars depends(F(i))];
elseif is(F(i),'integer')
integervars = [integervars depends(F(i))];
end
end
binvars = intersect(binvars,vars);
integervars = intersect(integervars,vars);
vars = setdiff(vars,union(integervars,binvars));
integervars = setdiff(integervars,binvars);
obj = amplexpr(h,vars,binvars,integervars);
constraints = {};
if ~isempty(F)
for i = 1:length(F)
if is(F(i),'element-wise')
C = sdpvar(F(i));C=C(:);
dummy = amplexpr(C,vars,binvars,integervars);
for j = 1:length(C)
if ~isempty(dummy{j})
constraints{end+1} = ['0 <= ' dummy{j}];
end
end
elseif is(F(i),'socp')
C = sdpvar(F(i));C=C(:);
dummy = amplexpr(C(1)^2-C(2:end)'*C(2:end),vars,binvars,integervars);
constraints{end+1} = ['0 <= ' dummy{1}];
dummy = amplexpr(C(1),vars,binvars,integervars);
constraints{end+1} = ['0 <= ' dummy{1}];
elseif is(F(i),'equality')
C = sdpvar(F(i));C=C(:);
dummy = amplexpr(C,vars,binvars,integervars);
for j = 1:length(C)
constraints{end+1} = ['0 == ' dummy{j}];
end
end
end
end
% Is a filename supplied
if nargin<3
[filename, pathname] = uiputfile('*.mod', 'Save AMPL format file');
if isa(filename,'double')
return % User cancelled
else
% Did the user change the extension
if isempty(findstr(filename,'.'))
filename = [pathname filename '.mod'];
else
filename = [pathname filename];
end
end
else
filename = varargin{3};
end
fid = fopen(filename,'w');
try
% fprintf(fid,['option randseed 0;\r\n']);
if length(vars)>0
fprintf(fid,['var x {1..%i};\r\n'],length(vars));
end
if length(binvars)>0
fprintf(fid,['var y {1..%i} binary ;\r\n'],length(binvars));
end
if length(integervars)>0
fprintf(fid,['var z {1..%i} integer ;\r\n'],length(integervars));
end
fprintf(fid,['minimize obj: ' obj{1} ';'],max(vars));
fprintf(fid,'\r\n');
if length(constraints)>0
for i = 1:length(constraints)
constraints{i} = strrep(constraints{i},'mpower_internal','');
fprintf(fid,['subject to constr%i: ' constraints{i} ';'],i);
fprintf(fid,'\r\n');
end
end
fprintf(fid,'solve;\r\n');
if length(vars)>0
fprintf(fid,'display x;\r\n');
end
if length(binvars)>0
fprintf(fid,'display y;\r\n');
end
if length(integervars)>0
fprintf(fid,'display z;\r\n');
end
fprintf(fid,'display obj;\r\n');
catch
fclose(fid);
end
fclose(fid);
function symb_pvec = amplexpr(pvec,vars,binvars,integervars)
extVariables = yalmip('extvariables');
for pi = 1:size(pvec,1)
for pj = 1:size(pvec,2)
p = pvec(pi,pj);
if isa(p,'double')
symb_p = num2str(p,12);
elseif isinf(getbasematrix(p,0))
symb_p = [];
else
LinearVariables = depends(p);
x = recover(LinearVariables);
exponent_p = full(exponents(p,x));
names = cell(length(LinearVariables),1);
for i = 1:length(LinearVariables)
v1 = find(vars==LinearVariables(i));
if ~isempty(v1)
names{i}=['x[' num2str(find(vars==LinearVariables(i))) ']'];
else
v1 = find(binvars==LinearVariables(i));
if ~isempty(v1)
names{i}=['y[' num2str(find(binvars==LinearVariables(i))) ']'];
else
names{i}=['z[' num2str(find(integervars==LinearVariables(i))) ']'];
end
end
end
for i = 1:length(LinearVariables)
v1 = find(extVariables==LinearVariables(i));
if ~isempty(v1)
e = yalmip('extstruct',extVariables(v1));
inner = amplexpr(e.arg{1},depends(e.arg{1}),binvars,integervars);
names{i} = [e.fcn '(' inner{1} ')'];
names{i} = strrep(names{i},'mpower_internal','');
end
end
symb_p = '';
if all(exponent_p(1,:)==0)
symb_p = num2str(full(getbasematrix(p,0)),12);
exponent_p = exponent_p(2:end,:);
end
for i = 1:size(exponent_p,1)
coeff = getbasematrixwithoutcheck(p,i);
switch full(coeff)
case 1
coeff='+';
case -1
coeff = '-';
otherwise
if coeff >0
coeff = ['+' num2str2(coeff)];
else
coeff=[num2str2(coeff)];
end
end
if strcmp(symb_p,'') & (strcmp(coeff,'+') | strcmp(coeff,'-'))
symb_p = [symb_p coeff symbmonom(names,exponent_p(i,:))];
else
symb_p = [symb_p coeff '*' symbmonom(names,exponent_p(i,:))];
end
end
if symb_p(1)=='+'
symb_p = symb_p(2:end);
end
end
if ~isempty(symb_p)
symb_p = strrep(symb_p,'+*','+');
symb_p = strrep(symb_p,'-*','-');
end
symb_pvec{pi,pj} = symb_p;
end
end
function s = symbmonom(names,monom)
s = '';
for j = 1:length(monom)
if monom(j)
if strcmp(s,'')
s = [s names{j}];
else
s = [s '*' names{j}];
end
if monom(j)~=1
s = [s '^' num2str(monom(j))];
end
end
end
function s = num2str2(x)
s = num2str(full(x),12);
if isequal(s,'1')
s = '';
end
if isequal(s,'-1')
s = '-';
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
monolist.m
|
.m
|
LMI-Matlab-master/yalmip/extras/monolist.m
| 7,193 |
utf_8
|
dfe7495e41d589eb47d0d0df0acc3890
|
function new_x = monolist(x,dmax,dmin)
% MONOLIST Generate monomials
%
% y = MONOLIST(x,dmax,dmin)
%
% Returns the monomials [1 x(1) x(1)^2 ... x(1)^dmax(1) x(2) x(1)x(2) etc...]
%
% >>sdpvar x y z
% >>sdisplay(monolist([x y z],4))
%
% Input
% x : Vector with SDPVAR variables
% dmax : Integers > 0
%
% See also POLYNOMIAL, DEGREE
% Flatten
x = reshape(x,1,length(x));
x_orig = x;
if nargin == 3
if length(dmin)>1 || any(dmin > dmax) || ~isequal(dmin,fix(dmin))
error('dmin has to be an integer scalar larger than dmax');
end
elseif nargin == 2
dmin = 0;
end
if (length(dmax)==1 | all(dmax(1)==dmax)) & islinear(x) & ~isa(x,'ncvar')
dmax = dmax(1);
% Powers in monomials
powers = monpowers(length(x),dmax);
powers = powers(find(sum(powers,2)>=dmin),:);
% Use fast method for x^alpha
if isequal(getbase(x),[zeros(length(x),1) eye(length(x))])
new_x = recovermonoms(powers,x);
return
end
% Monolist on dense vectors is currently extremely slow, but also
% needed in some applications (stability analysis using SOS) For
% performance issue, the code below is hard-coded for special cases
% FIX : Urgent, find underlying indexing...
% Vectorize quadratic and quadrtic case
if dmax==2 & length(x)>1
V=x.'*[1 x];
ind=funkyindicies(length(x));
new_x = [1 V(ind(:)).'].';
return
elseif (length(x)==4 & dmax==6)
ind =[ 1 2 3 4 5 6 7 8,
9 10 11 12 13 14 15 16,
17 18 19 20 21 22 23 24,
25 26 27 28 29 30 31 32,
33 34 49 50 51 52 86 53,
54 55 89 56 57 91 58 92,
126 59 60 61 95 62 63 97,
64 98 132 65 66 100 67 101,
135 68 102 136 170 185 186 187,
188 222 256 189 190 191 225 259,
192 193 227 261 194 228 262 296,
330 364 195 196 197 231 265 198,
199 233 267 200 234 268 302 336,
370 201 202 236 270 203 237 271,
305 339 373 204 238 272 306 340,
374 408 442 476 510 525 526 527,
528 562 596 630 529 530 531 565,
599 633 532 533 567 601 635 534,
568 602 636 670 704 738 772 806,
840 535 536 537 571 605 639 538,
539 573 607 641 540 574 608 642,
676 710 744 778 812 846 541 542,
576 610 644 543 577 611 645 679,
713 747 781 815 849 544 578 612,
646 680 714 748 782 816 850 884,
918 952 986 1020 1054 1088 1122 1156,
1190 0 0 0 0 0 0 0];
ind = ind';
ind = ind(find(ind));
v=monolist(x,3);
V=v(2:end)*v.';
new_x = [1;V(ind(:))];
return
elseif dmax==4 & (1<=length(x)) & length(x)<=4 %& length(x)>1
v=monolist(x,2);
V=v(2:end)*v.';
% Cone to generate indicies
%p = sdpvar(n,1);
%v = monolist(p,2);
%V = v(2:end)*v';V=V(:);
%m = monolist(p,4)
%ind = [];
%for i = 2:length(m)
% ind = [ind min(find(~any(V-m(i))))];
%end
switch length(x)
case 1
new_x = [1; V([1 2 4 6]')];
return
case 2
new_x = [1;V([1 2 3 4 5 8 9 10 15 18 19 20 25 30]')];
return;
case 3
new_x=[1;V([1 2 3 4 5 6 7 8 9 13 14 15 24 16 17 26 18 27 36 40 41 42 51 60 43 44 53 62 45 54 63 72 81 90]')];
return
case 4
new_x=[1;V([ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 19 20 21 35 22 23 37 24 38 52 25 26 40 27 41 55 28 42 56 70 75 76 77 91 105 78 79 93 107 80 94 108 122 136 150 81 82 96 110 83 97 111 125 139 153 84 98 112 126 140 154 168 182 196 210]')];
return
otherwise
end
end
% Na, we have things like (c'x)^alpha
% precalc x^p
for i = 1:length(x)
temp = x(i);
precalc{i,1} = temp;
for j = 2:1:dmax
temp = temp*x(i);
precalc{i,j} = temp;
end
end
new_x = [];
for i = 1:size(powers,1) % All monomials
temp = 1;
for j = 1:size(powers,2) % All variables
if powers(i,j)>0
temp = temp*precalc{j,powers(i,j)};
end
end
new_x = [new_x temp];
end
else
dmax = dmax(:)*ones(1,length(x_orig));
x = [1 x];
% Lame loop to generate all combinations
new_x = 1;
for j = 1:1:max(dmax)
temp = [];
for i = 1:length(x)
temp = [temp x(i)*new_x];
end
new_x = temp;
new_x = fliplr(unique(new_x));
new_degrees = degree(new_x,x(2:end));
remv = [];
for i = 1:length(dmax);
if new_degrees(i)>=dmax(i)
x = recover(setdiff(getvariables(x),getvariables(x_orig(i))));
x = [1;x(:)];
remv = [remv i];
end
end
dmax = dmax(setdiff(1:length(dmax),remv));
end
end
new_x = reshape(new_x(:),length(new_x),1);
if dmin > 0
for i = 1:length(new_x)
if degree(new_x(i)) < dmin
keep(i) = 0;
else
keep(i) = 1;
end
end
if any(keep==0)
new_x = new_x(find(keep));
end
end
function ind = funkyindicies(n)
M=reshape(1:n*(n+1),n,n+1);
ind = M(:,1)';
for i = 1:n
ind = [ind M(i,2:i+1)];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
eliminatevariables.m
|
.m
|
LMI-Matlab-master/yalmip/extras/eliminatevariables.m
| 11,708 |
utf_8
|
cb8bbf991713a6188ea388790a03a949
|
function [model,keptvariables,infeasible] = eliminatevariables(model,varindex,value)
keptvariables = 1:length(model.c);
rmvmonoms = model.rmvmonoms;
newmonomtable = model.newmonomtable;
% Assign evaluation-based values
if length(model.evalParameters > 0)
alls = union(varindex,model.evalParameters);
[dummy,loc] = ismember(varindex,alls);
remappedvalue = zeros(length(alls),1);
remappedvalue(loc) = value;
for i = 1:length(model.evalMap)
j = find(model.evalMap{i}.variableIndex == varindex);
if ~isempty(j)
p = value(j);
[dummy,loc] = ismember(model.evalMap{i}.computes,alls);
remappedvalue(loc) = feval(model.evalMap{i}.fcn,p);
end
end
value = remappedvalue;
% We only eliminate in models where the operators dissapear after
% parameters are fixed
model.evalMap = [];
model.evalVariables = [];
end
% Evaluate fixed monomial terms
aux = model.precalc.aux;
if ~isempty(model.precalc.jj1)
z = value(model.precalc.jj1).^rmvmonoms(model.precalc.index1);
aux(model.precalc.index1) = z;
end
% Assign simple linear terms
if ~isempty(model.precalc.jj2)
aux(model.precalc.index2) = value(model.precalc.jj2);
end
monomvalue = prod(aux,2);
removethese = model.removethese;
keepingthese = model.keepingthese;
value = monomvalue(removethese);
monomgain = monomvalue(keepingthese);
if ~isempty(model.F_struc)
model.F_struc(:,1) = model.F_struc(:,1)+model.F_struc(:,1+removethese)*value;
model.F_struc(:,1+removethese) = [];
model.F_struc = model.F_struc*diag(sparse([1;monomgain]));
end
infeasible = 0;
if model.K.f > 0
candidates = find(~any(model.F_struc(1:model.K.f,2:end),2));
%candidates = find(sum(abs(model.F_struc(1:model.K.f,2:end)),2) == 0);
if ~isempty(candidates)
% infeasibles = find(model.F_struc(candidates,1)~=0);
if find(model.F_struc(candidates,1)~=0,1)%;~isempty(infeasibles)
infeasible = 1;
return
else
model.F_struc(candidates,:) = [];
model.K.f = model.K.f - length(candidates);
end
end
end
if model.K.l > 0
candidates = find(~any(model.F_struc(model.K.f + (1:model.K.l),2:end),2));
%candidates = find(sum(abs(model.F_struc(model.K.f + (1:model.K.l),2:end)),2) == 0);
if ~isempty(candidates)
%if find(model.F_struc(model.K.f + candidates,1)<0,1)
if any(model.F_struc(model.K.f + candidates,1)<-1e-14)
infeasible = 1;
return
else
model.F_struc(model.K.f + candidates,:) = [];
model.K.l = model.K.l - length(candidates);
end
end
end
if model.K.q(1) > 0
removeqs = [];
removeRows = [];
top = model.K.f + model.K.l + 1;
F_struc = model.F_struc(top:top+sum(model.K.q)-1,:);
top = 1;
if all(any(F_struc(:,2:end),2))
% There is still something on every row in all SOCPs, we don't have
% to search for silly SOCPS ||0|| <= constant
else
for i = 1:length(model.K.q)
rows = top:top+model.K.q(i)-1;
v = F_struc(rows,:);
if nnz(v(:,2:end))==0
if norm(v(2:end,1)) > v(1,1)
infeasible = 1;
return
else
removeqs = [removeqs;i];
removeRows = [removeRows;model.K.f+model.K.l+rows];
end
end
top = top + model.K.q(i);
end
model.K.q(removeqs)=[];
model.F_struc(removeRows,:)=[];
if isempty(model.K.q)
model.K.q = 0;
end
end
end
if model.K.s(1) > 0
% Nonlinear semidefinite program with parameter
top = model.K.f + model.K.l + sum(model.K.q) + 1;
removeqs = [];
removeRows = [];
for i = 1:length(model.K.s)
n = model.K.s(i);
rows = top:top+n^2-1;
v = model.F_struc(rows,:);
if nnz(v)==0
removeqs = [removeqs;i];
removeRows = [removeRows;rows];
elseif nnz(v(:,2:end))==0
Q = reshape(v(:,1),n,n);
used = find(any(Q));Qred=Q(:,used);Qred = Qred(used,:);
[~,p] = chol(Qred);
if p
infeasible = 1;
return
else
removeqs = [removeqs;i];
removeRows = [removeRows;rows];
end
end
top = top + n^2;
end
model.K.s(removeqs)=[];
model.F_struc(removeRows,:)=[];
if isempty(model.K.s)
model.K.s = 0;
end
end
model.f = model.f + model.c(removethese)'*value;
model.c(removethese)=[];
if nnz(model.Q)>0
model.c = model.c + 2*model.Q(keepingthese,removethese)*value;
end
if nnz(model.Q)==0
model.Q = spalloc(length(model.c),length(model.c),0);
else
model.Q(removethese,:) = [];
model.Q(:,removethese) = [];
end
model.c = model.c.*monomgain;
keptvariables(removethese) = [];
model.lb(removethese)=[];
model.ub(removethese)=[];
newmonomtable(:,removethese) = [];
newmonomtable(removethese,:) = [];
if ~isequal(newmonomtable,model.precalc.newmonomtable)%~isempty(removethese)
skipped = [];
alreadyAdded = zeros(1,size(newmonomtable,1));
%[ii,jj,kk] = unique(newmonomtable*gen_rand_hash(0,size(newmonomtable,2),1),'rows','stable');
[ii,jj,kk,skipped] = stableunique(newmonomtable*gen_rand_hash(0,size(newmonomtable,2),1));
S = sparse(kk,1:length(kk),1);
% skipped = setdiff(1:length(kk),jj);
model.precalc.S = S;
model.precalc.skipped = skipped;
model.precalc.newmonomtable = newmonomtable;
model.precalc.blkOneS = blkdiag(1,S');
else
S = model.precalc.S;
skipped = model.precalc.skipped;
end
model.c = S*model.c;
%model.F_struc2 = [model.F_struc(:,1) (S*model.F_struc(:,2:end)')'];
if ~isempty(model.F_struc)
model.F_struc = model.F_struc*model.precalc.blkOneS;%blkdiag(1,S');
end
%norm(model.F_struc-model.F_struc2)
model.lb(skipped) = [];
model.ub(skipped) = [];
newmonomtable(skipped,:) = [];
newmonomtable(:,skipped) = [];
if nnz(model.Q)==0
model.Q = spalloc(length(model.c),length(model.c),0);
else
model.Q(:,skipped)=[];
model.Q(skipped,:)=[];
end
keptvariables(skipped) = [];
model.monomtable = newmonomtable;
model = compressModel(model);
x0wasempty = isempty(model.x0);
model.x0 = zeros(length(model.c),1);
% Try to reduce to QP
[model,keptvariables,newmonomtable] = setupQuadratics(model,keptvariables,newmonomtable);
if nnz(model.Q) > 0
if model.solver.objective.quadratic.convex == 0 & model.solver.objective.quadratic.nonconvex == 0
error('The objective instantiates as a quadratic after fixing parameters, but this is not directly supported by the solver. YALMIP will not reformulate models if they structurally change in call to optimizer. A typical trick to circumvent this is to define a new set of variable e, use the quadratic function e''e, and add an equality constraint e = something. The SOCP formulation can then be done a-priori by YALMIP.');
end
end
if x0wasempty
model.x0 = [];
end
% Remap indicies
if ~isempty(model.integer_variables)
temp=ismember(keptvariables,model.integer_variables);
model.integer_variables = find(temp);
end
if ~isempty(model.binary_variables)
temp=ismember(keptvariables,model.binary_variables);
model.binary_variables = find(temp);
end
if ~isempty(model.semicont_variables)
temp=ismember(keptvariables,model.semicont_variables);
model.semicont_variables = find(temp);
end
% Check if there are remaining strange terms. This occurs in #152
% FIXME: Use code above recursively instead...
if ~model.solver.objective.sigmonial & any(model.variabletype == 4)
% Bugger. There are signomial terms left, despite elimination, and the
% solver does not handle this. YALMIP has introduced an intermediate
% variable which is a nasty function of the parameter.
signomials = find(model.variabletype == 4);
involved = [];
for i = 1:length(signomials)
m = model.monomtable(signomials(i),:);
involved = [involved;find(m ~= fix(m) | m < 0)];
end
involved = unique(involved);
[lb,ub] = findulb(model.F_struc,model.K,model.lb,model.ub);
if all(lb(involved) == ub(involved))
% Now add equality constraints to enforce
for i = signomials
m = model.monomtable(i,:);
involved = find(m ~= fix(m) | m < 0);
gain = lb(involved).^m(involved);
s = zeros(1,size(model.F_struc,2));
multiplies = setdiff(find(m),involved);
s(i+1) = 1;
s(multiplies+1) = -gain;
model.F_struc = [s;model.F_struc];
model.K.f = model.K.f + 1;
end
else
error('Did not manage to instatiate model. Complicating terms remaining');
end
end
function model = compressModel(model)
model.variabletype = zeros(size(model.monomtable,1),1)';
nonlinear = sum(model.monomtable,2)~=1 | sum(model.monomtable~=0,2)~=1;
if ~isempty(nonlinear)
model.variabletype(nonlinear) = 3;
quadratic = sum(model.monomtable,2)==2;
model.variabletype(quadratic) = 2;
bilinear = max(model.monomtable,[],2)<=1;
model.variabletype(bilinear & quadratic) = 1;
sigmonial = any(0>model.monomtable,2) | any(model.monomtable-fix(model.monomtable),2);
model.variabletype(sigmonial) = 4;
end
function [model,keptvariables,newmonomtable] = setupQuadratics(model,keptvariables,newmonomtable);
if any(model.variabletype) & all(model.variabletype <= 2)
monomials = find(model.variabletype);
if nnz(model.F_struc(:,1+monomials))==0
if all(isinf(model.lb(monomials)))
if all(isinf(model.ub(monomials)))
% OK, the quadratic/bilinear terms only enter in objective,
% so let us try to construct Q
if isempty(model.precalc.Qmap)
ii = [];
jj = [];
kk = [];
for k = monomials(:)'
i = find(model.monomtable(k,:));
if model.variabletype(k)==1
model.Q(i(1),i(2)) = model.Q(i(1),i(2)) + model.c(k)/2;
model.Q(i(2),i(1)) = model.Q(i(1),i(2));
ii = [ii;i(1)];
jj = [jj;i(2)];
kk = [kk;k];
else
model.Q(i,i) = model.Q(i,i) + model.c(k);
ii = [ii;i];
jj = [jj;i];
kk = [kk;k];
end
end
model.precalc.Qmap.M = sparse(sub2ind(size(model.Q),ii,jj),kk,1,prod(size(model.Q)),length(model.c));
model.precalc.Qmap.monomials = monomials;
model.precalc.Qmap.monomtable = model.monomtable;
else
m = model.precalc.Qmap.M*sparse(model.c);
m = reshape(m,sqrt(length(m)),[]);
model.Q = (m+m')/2;
end
model.c(monomials)=[];
model.F_struc(:,1+monomials) = [];
model.lb(monomials) = [];
model.ub(monomials) = [];
newmonomtable(monomials,:) = [];
newmonomtable(:,monomials) = [];
model.monomtable = newmonomtable;
model.Q(:,monomials) = [];
model.Q(monomials,:) = [];
model.x0(monomials) = [];
model.variabletype(monomials)=[];
keptvariables(monomials) = [];
end
end
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
savecplexlp.m
|
.m
|
LMI-Matlab-master/yalmip/extras/savecplexlp.m
| 3,862 |
utf_8
|
d62ee5da3ba7f3c01ad267cdafef9bf6
|
function filename = savecplexlp(varargin)
%SAVCPLEXLP Saves a problem definition in CPLEX-LP format
%
% SAVCPLEXLP(F,h,'filename') Saves the problem min(h(x)), F(x)>0 to the file filename
% SAVCPLEXLP(F,h) A "Save As"- box will be opened
%
F = varargin{1};
h = varargin{2};
[aux1,aux2,aux3,model] = export(F,h);
% Check so that it really is an LP
% if any(any(model.Q)) | any(model.variabletype)
% Only check the variabletype
if any(model.variabletype)
error('This is not an LP or QP');
end
c = model.c;
Q = 2*full(model.Q);
b = model.F_struc(:,1);
A = -model.F_struc(:,2:end);
if model.K.f>0
Aeq = A(1:model.K.f,:);
beq = b(1:model.K.f,:);
A(1:model.K.f,:) = [];
b(1:model.K.f) = [];
else
Aeq = [];
beq = [];
end
lb = model.lb;
ub = model.ub;
[lb,ub,A,b] = remove_bounds_from_Ab(A,b,lb,ub);
[lb,ub,Aeq,beq] = remove_bounds_from_Aeqbeq(Aeq,beq,lb,ub);
% Is a filename supplied
if nargin<3
[filename, pathname] = uiputfile('*.lp', 'Save LP format file');
if isa(filename,'double')
return % User cancelled
else
% Did the user change the extension
if isempty(findstr(filename,'.'))
filename = [pathname filename '.lp'];
else
filename = [pathname filename];
end
end
else
filename = varargin{3};
end
fid = fopen(filename,'w');
obj = strrep(lptext(c(:)'),'+ -','-');
fprintf(fid,['Minimize\r\n obj: ' obj(1:end-2) '']);
if any(any(Q))
obj = qptext(Q);
fprintf(fid,[' + [' obj(1:end-2) '] / 2']);
end
fprintf(fid,'\r\n');
fprintf(fid,['\r\n']);
fprintf(fid,['Subject To\r\n']);
for i = 1:length(b)
rowtext = lptext(-A(i,:));
rhs = sprintf('%0.20g',full(-b(i)));
rowtext = [rowtext(1:end-2) ' >= ' rhs];
fprintf(fid,[' c%i: ' strrep(rowtext,'+ -','-') ''],i);
fprintf(fid,'\r\n');
end
for i = 1:length(beq)
rowtext = lptext(-Aeq(i,:));
rowtext = [rowtext(1:end-2) '== ' sprintf('%0.20g',full(-beq(i)))];
fprintf(fid,[' eq%i: ' strrep(rowtext,'+ -','-') ''],i);
fprintf(fid,'\r\n');
end
if length(c)>length(model.binary_variables)
fprintf(fid,['\r\nBounds\r\n']);
for i = 1:length(c)
% if ~ismember(i,model.binary_variables)
if isinf(lb(i)) & isinf(ub(i))
fprintf(fid,[' x%i free\n\r'],i);
elseif lb(i)==0 & isinf(ub(i))
% Standard non-negative variable
elseif isinf(ub(i))
s = strrep(sprintf(['%0.20g <= x%i \r\n'],[lb(i) i ]),'Inf','inf');
fprintf(fid,s);
else
s = strrep(sprintf(['%0.20g <= x%i <= %0.20g \r\n'],[lb(i) i ub(i)]),'Inf','inf');
fprintf(fid,s);
end
% end
end
end
if length(model.binary_variables)>0
fprintf(fid,['\r\n']);
fprintf(fid,['Binary\r\n']);
for i = 1:length(model.binary_variables)
fprintf(fid,[' x%i\r\n'],model.binary_variables(i));
end
end
if length(model.integer_variables)>0
fprintf(fid,['\r\n']);
fprintf(fid,['Integer\r\n']);
for i = 1:length(model.integer_variables)
fprintf(fid,[' x%i\r\n'],model.integer_variables(i));
end
end
fprintf(fid,['\r\nEnd']);
fclose(fid);
function rowtext = lptext(a)
[aux,poss,vals] = find(a);
rowtext = sprintf('%0.20g x%d + ',reshape([vals(:) poss(:)]',[],1));
%rowtext = strrep(rowtext,'+ -','- ');
%rowtext(isspace(rowtext))=[];
%rowtext = strrep(rowtext,'+-','-');
%rowtext = strrep(rowtext,'-1x','-x');
%rowtext = strrep(rowtext,'+1x','+x');
function rowtext = qptext(Q)
n=size(Q,2);
q = diag(Q);
if any(q)
i = find(q);
rowtext = sprintf('%0.20g x%d ^2 + ',reshape([q(i) i]',[],1));
end
for i=1:n
for j=i+1:n
if ~(Q(i,j)+Q(j,i)==0)
rowtext = [rowtext sprintf('%0.20g x%d * x%d + ',Q(i,j)+Q(j,i),i,j)];
end
end
end
rowtext = strrep(rowtext,'+ -','- ');
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
solvesdp_multiple.m
|
.m
|
LMI-Matlab-master/yalmip/extras/solvesdp_multiple.m
| 5,574 |
utf_8
|
c5412bd27722e2bcb8fe758c99a95fb7
|
function diagnostic = solvesdp_multiple(varargin);
yalmiptime = clock;
h = varargin{2};
varargin{2} = sum(recover(depends(h)));
if ~is(h,'linear')
error('Parts of your matrix objective is not linear (multiple solutions can currently only be obtained for linear objectives)');
end
if is(h,'complex')
error('Parts of your matrix objective is complex-valued (which makes no sense since complex numbers have no natural ordering');
end
if nargin<3
ops = sdpsettings('saveyalmipmodel',1);
varargin{3} = ops;
else
ops = varargin{3};
varargin{3}.saveyalmipmodel = 1;
end
varargin{3}.pureexport = 1;
yalmiptime = clock;
model = solvesdp(varargin{:});
diagnostic.yalmiptime = etime(clock,yalmiptime);
yalmiptime = clock;
h_variables = getvariables(h);
h_base = getbase(h);
for i = 1:length(h)
model.f = h_base(i,1);
model.c = mapObjective(h_variables,model.used_variables,h_base(i,2:end));
% *************************************************************************
% TRY TO SOLVE PROBLEM
% *************************************************************************
if ops.debug
eval(['output = ' model.solver.call '(model);']);
else
try
eval(['output = ' model.solver.call '(model);']);
catch
output.Primal = zeros(length(model.c),1)+NaN;
output.Dual = [];
output.Slack = [];
output.solvertime = nan;
output.solverinput = [];
output.solveroutput = [];
output.problem = 9;
output.infostr = yalmiperror(output.problem,lasterr);
end
end
if ops.dimacs
try
b = -model.c;
c = model.F_struc(:,1);
A = -model.F_struc(:,2:end)';
x = output.Dual;
y = output.Primal;
% FIX this nonlinear crap (return variable type in
% compilemodel)
if options.relax == 0 & any(full(sum(model.monomtable,2)~=0))
if ~isempty(find(sum(model.monomtable | model.monomtable,2)>1))
z=real(exp(model.monomtable*log(y+eps)));
y = z;
end
end
if isfield(output,'Slack')
s = output.Slack;
else
s = [];
end
dimacs = computedimacs(b,c,A,x,y,s,model.K);
catch
dimacs = [nan nan nan nan nan nan];
end
else
dimacs = [nan nan nan nan nan nan];
end
% ********************************
% ORIGINAL COORDINATES
% ********************************
if isempty(output.Primal)
output.Primal = zeros(size(model.recoverdata.H,2),1);
end
output.Primal(:,i) = model.recoverdata.x_equ+model.recoverdata.H*output.Primal;
% ********************************
% OUTPUT
% ********************************
diagnostic.yalmiptime = diagnostic.yalmiptime + etime(clock,yalmiptime)-output.solvertime;
diagnostic.solvertime(:,i) = output.solvertime;
try
diagnostic.info = output.infostr;
catch
diagnostic.info = yalmiperror(output.problem,model.solver.tag);
end
diagnostic.problem(:,i) = output.problem;
diagnostic.dimacs(:,i) = dimacs;
% Some more info is saved internally
solution_internal = diagnostic;
solution_internal.variables = model.recoverdata.used_variables(:);
solution_internal.optvar = output.Primal(:,i);
if ~isempty(model.parametric_variables)
diagnostic.mpsol = output.solveroutput;
options.savesolveroutput = actually_save_output;
end;
if model.options.savesolveroutput
diagnostic.solveroutput = output.solveroutput;
end
if model.options.savesolverinput
diagnostic.solverinput = output.solverinput;
end
if model.options.saveyalmipmodel
diagnostic.yalmipmodel = model;
end
if ops.warning && warningon && isempty(findstr(output.infostr,'No problems detected'))
disp(['Warning: ' output.infostr]);
end
if ismember(output.problem,ops.beeponproblem)
try
beep; % does not exist on all ML versions
catch
end
end
% And we are done! Save the result
if ~isempty(output.Primal)
yalmip('setsolution',solution_internal,i);
end
if model.options.saveduals & model.solver.dual
if isempty(model.Fremoved) | (nnz(model.Q)>0)
try
setduals(F,output.Dual,model.K);
catch
end
else
try
% Duals related to equality constraints/free variables
% have to be recovered b-A*x-Ht == 0
b = -model.oldc;
A = -model.oldF_struc(1+model.oldK.f:end,2:end)';
H = -model.oldF_struc(1:model.oldK.f,2:end)';
x = output.Dual;
b_equ = b-A*x;
newdual = H\b_equ;
setduals(model.Fremoved + F,[newdual;output.Dual],model.oldK);
catch
% this is a new feature...
disp('Dual recovery failed. Please report this issue.');
end
end
end
end
function newbase = mapObjective(local_vars,global_vars,base)
newbase = spalloc(length(global_vars),1,nnz(base));
for i = 1:length(local_vars)
j = find(local_vars(i)==global_vars);
newbase(j) = base(i);
end
function yesno = warningon
s = warning;
yesno = isequal(s,'on');
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
computedimacs.m
|
.m
|
LMI-Matlab-master/yalmip/extras/computedimacs.m
| 2,052 |
utf_8
|
87d06eb1f6270fd74593f205c3343f1d
|
function dimacs = computedimacs(b,c,A,xin,y,s,K);
% COMPUTEDIMACS
%
% min <C,X> s.t AX = b, X > 0
% max b'y s.t S-C+A'y =0, S > 0
% If no primal exist, fake till later
if isempty(xin)
x = c*0;
else
x = xin;
end
if isempty(s)
s = c-A'*y;
end
xres = inf;
sres = inf;
% Not officially defined in DIMACS
if K.f>0
sres = -min(norm(s(1:K.f),inf));
end
% Errors in linear cone
if K.l>0
xres = min(x(1+K.f:K.f+K.l));
sres = min(s(1+K.f:K.f+K.l));
end
% Errors in quadratic cone
if K.q(1)>0
top = K.f+K.l;
for i = 1:length(K.q)
X = x(1+top:top+K.q(i));
S = s(1+top:top+K.q(i));
xres = min(xres,X(1)-norm(X(2:end)));
sres = min(sres,S(1)-norm(S(2:end)));
top = top + K.q(i);
end
end
% Errors in semidefinite cone
if K.s(1)>0
top = K.f+K.l+K.q+K.r;
for i = 1:length(K.s)
X = reshape(x(1+top:top+K.s(i)^2),K.s(i),K.s(i));
S = reshape(s(1+top:top+K.s(i)^2),K.s(i),K.s(i));
xres = min(xres,min(eig(full(X))));
sres = min(sres,min(eig(full(S))));
top = top + K.s(i)^2;
end
end
err1 = norm(b-A*x)/(1 + norm(b,inf));
err2 = max(0,-xres)/(1 + norm(b,inf));
err3 = conenorm(s-(c-A'*y),K)/(1+norm(c,inf));
%err3 = norm(s-(c-A'*y))/(1+norm(c,inf)); % Used by some solvers
err4 = max(0,-sres)/(1+max(abs(c)));
err5 = (c'*x-b'*y)/(1+abs(c'*x)+abs(b'*y));
err6 = x'*(c-A'*y)/(1+abs(c'*x)+abs(b'*y));
% No primal was computed
if isempty(xin)
err1 = nan;
err2 = nan;
err5 = nan;
err6 = nan;
end
dimacs = [err1 err2 err3 err4 err5 err6];
function t = conenorm(s,K)
% Implementation of the norm described on
% http://plato.asu.edu/dimacs/node3.html
t = 0;
if K.f + K.l>0
t = t + norm(s(1:K.f+K.l));
end
top = 1+K.f+K.l;
if K.q(1)>0
for i = 1:length(K.q)
t = t + norm(s(top:top+K.q(i)-1));
top = top + K.q(i);
end
end
if K.s(1)>0
for i = 1:length(K.s)
S = reshape(s(top:top+K.s(i)^2-1),K.s(i),K.s(i));
t = t + norm(S,'fro');
top = top + K.s(i)^2;
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
binmodel.m
|
.m
|
LMI-Matlab-master/yalmip/extras/binmodel.m
| 9,313 |
utf_8
|
0128e2f618a9bc78ea94707dd7fa1499
|
function varargout = binmodel(varargin)
%BINMODEL Converts nonlinear mixed binary expression to linear model
%
% Applied to individual terms p defined on domain D
% [plinear1,..,plinearN,Cuts] = BINMODEL(p1,...,pN,D)
%
% Alternative on complete set of constraint
% F = BINMODEL(F)
%
% binmodel is used to convert nonlinear expressions involving a mixture of
% continuous and binary variables to the correponding linear model, using
% auxilliary variables and constraints to model nonlinearities.
%
% The input arguments are polynomial SDPVAR objects, or constraints
% involving such terms. If all involved variables are binary (defined using
% BINVAR), arbitrary polynomials can be linearized.
%
% If an input contains continuous variables, the continuous variables
% may only enter linearly in products with the binary variables (i.e.
% degree w.r.t continuous variables should be at most 1). More over, all
% continuous variables must be explicitly bounded. When submitting only the
% terms, the domain must be explicitly sent as the last argument. When the
% argument is a set of constraints, it is assumed that the domain is
% included and can be extracted.
%
% Example
% binvar a b
% sdpvar x y
% [plinear1,plinear2,Cuts] = binmodel(a^3+b,a*b);
% [plinear1,plinear2,Cuts] = binmodel(a^3*x+b*y,a*b*x, -2 <=[x y] <=2);
%
% F = binmodel([a^3*x+b*y + a*b*x >= 3, -2 <=[x y] <=2]);
%
% See also BINARY, BINVAR, SOLVESDP
if isa(varargin{1},'lmi') || isa(varargin{1},'constraint')
varargout{1} = binmodel_constraint(varargin{:});
return
end
all_linear = 1;
p = [];
n_var = 0;
Foriginal = [];
for i = 1:nargin
switch class(varargin{i})
case {'sdpvar','ndsdpvar'}
dims{i} = size(varargin{i});
p = [p;varargin{i}(:)];
if degree(varargin{i}(:)) > 1
all_linear = 0;
end
n_var = n_var + 1;
case {'lmi','constraint'}
Foriginal = Foriginal + varargin{i};
otherwise
error('Arguments should be SDPVAR or SET objects')
end
end
if length(Foriginal)>0
nv = yalmip('nvars');
yalmip('setbounds',1:nv,repmat(-inf,nv,1),repmat(inf,nv,1));
LU = getbounds(Foriginal);
extstruct = yalmip('extstruct');
extendedvariables = yalmip('extvariables');
for i = 1:length(extstruct)
switch extstruct(i).fcn
case 'abs'
LU = extract_bounds_from_abs_operator(LU,extstruct,extendedvariables,i);
case 'norm'
LU = extract_bounds_from_norm_operator(LU,extstruct,extendedvariables,i);
case 'min_internal'
LU = extract_bounds_from_min_operator(LU,extstruct,extendedvariables,i);
case 'max_internal'
LU = extract_bounds_from_max_operator(LU,extstruct,extendedvariables,i);
otherwise
end
end
yalmip('setbounds',1:nv,LU(:,1),LU(:,2));
end
if all_linear
varargout = varargin;
return
end
plinear = p;
F = Foriginal;
% Get stuff
vars = getvariables(p);
basis = getbase(p);
[mt,vt] = yalmip('monomtable');
allbinary = yalmip('binvariables');
allinteger = yalmip('intvariables');
% Fix data (monom table not guaranteed to be square)
if size(mt,1) > size(mt,2)
mt(end,size(mt,1)) = 0;
end
non_binary = setdiff(1:size(mt,2),allbinary);
if any(sum(mt(vars,non_binary),2) > 1)
error('Expression has to be linear in the continuous variables')
violatingmonoms = find(sum(mt(vars,non_binary),2) > 1);
cuts = [];
replacelinear = [];
for i = 1:length(violatingmonoms)
[~,idx,pwr] = find(mt(vars(violatingmonoms(i)),non_binary));
% [~,idxb,pwrb] = find(mt(vars(violatingmonoms),allbinary));
if isequal(pwr,2)
[~,idxb,pwrb] = find(mt(vars(violatingmonoms(i)),allbinary));
if isequal(pwrb,1)
w = sdpvar(1);
replacelinear = [replacelinear;getvariables(w)];
cuts = [cuts, recover(non_binary(idx))*recover(allbinary(idxb)) == w];
cuts = [cuts, LU(non_binary(idx),1) <= w <= LU(non_binary(idx),2)];
else
error('Expression has to be linear in the continuous variables')
end
else
error('Expression has to be linear in the continuous variables')
end
end
b = getbase(p);
v = getvariables(p);
v(violatingmonoms) = replacelinear;
p = b*[1;recover(v)];
varargin{1} = p;
varargin{end} = [varargin{end},cuts];
[varargout{1:nargout}] = binmodel(varargin{:});
return
end
% These are the original monomials
vecvar = recover(vars);
linear = find(vt(vars) == 0);
quadratic = find(vt(vars) == 2);
bilinear = find(vt(vars) == 1);
polynomial = find(vt(vars) == 3);
% replace x^2 with x (can only be binary expression, since we check for
% continuous nonlinearities above)
if ~isempty(quadratic)
[ii,jj] = find(mt(vars(quadratic),:));
z_quadratic = recover(jj);
else
quadratic = [];
z_quadratic = [];
end
% replace x*y with z, x>z, x>z, 1+z>x+y
if ~isempty(bilinear)
[jj,ii] = find(mt(vars(bilinear),:)');
xi = jj(1:2:end);
yi = jj(2:2:end);
x = recover(xi);
y = recover(yi);
if all(ismember(xi,allbinary)) & all(ismember(yi,allbinary))
% fast case for binary*binary
z_bilinear = binvar(length(bilinear),1);
F = [F, binary(z_bilinear), x >= z_bilinear, y >= z_bilinear, 1+z_bilinear >= x + y, 0 <= z_bilinear <= 1];
else
z_bilinear = sdpvar(length(bilinear),1);
theseAreBinaries = find(ismember(xi,allbinary) & ismember(yi,allbinary));
z_bilinear(theseAreBinaries) = binvar(length(theseAreBinaries),1);
for i = 1:length(bilinear)
if ismember(xi(i),allbinary) & ismember(yi(i),allbinary)
F = [F, x(i) >= z_bilinear(i), y(i) >= z_bilinear(i), 1+z_bilinear(i) >= x(i) + y(i), 0 <= z_bilinear(i) <= 1];
elseif ismember(xi(i),allbinary)
F = [F, binary_times_cont(x(i),y(i), z_bilinear(i))];
else
F = [F, binary_times_cont(y(i),x(i), z_bilinear(i))];
end
end
end
else
bilinear = [];
z_bilinear = [];
end
%general case a bit slower
if ~isempty(polynomial)
z_polynomial = sdpvar(length(polynomial),1);
xvar = [];
yvar = [];
for i = 1:length(z_polynomial)
% Get the monomial powers, clear out the
the_monom = mt(vars(polynomial(i)),:);
if any(the_monom(non_binary))
% Tricky case, x*polynomial(binary)
% Start by first modeling the binary part
the_binary_monom = the_monom;the_binary_monom(non_binary) = 0;
[ii,jj] = find(the_binary_monom);
x = recover(jj);
F = [F, x >= z_polynomial(i), length(x)-1+z_polynomial(i) >= sum(x), 0 <= z_polynomial(i) <= 1];
% Now define the actual variable
temp = z_polynomial(i);z_polynomial(i) = sdpvar(1,1);
the_real_monom = the_monom;the_real_monom(allbinary)=0;
[ii,jj] = find(the_real_monom);
x = recover(jj);
F = F + binary_times_cont(temp,x,z_polynomial(i));
else
% simple case, just binary terms
[ii,jj] = find(the_monom);
x = recover(jj);
F = [F, x >= z_polynomial(i), length(x)-1+z_polynomial(i) >= sum(x), 0 <= z_polynomial(i) <= 1];
end
end
else
z_polynomial = [];
polynomial = [];
end
ii = [linear quadratic bilinear polynomial];
jj = ones(length(ii),1);
kk = [recover(vars(linear));z_quadratic;z_bilinear;z_polynomial];
vecvar = sparse(ii(:),jj(:),kk(:));
% Recover the whole thing
plinear = basis*[1;vecvar];
% And now get the original sizes
top = 1;
for i = 1:n_var
varargout{i} = reshape(plinear(top:top+prod(dims{i})-1),dims{i});
top = top + prod(dims{i});
end
varargout{end+1} = F;
function F = binary_times_cont(d,y, z)
[M,m,infbound] = derivebounds(y);
if infbound
error('Some of your continuous variables are not explicitly bounded.')
end
F = [(1-d)*M >= y - z >= m*(1-d), d*m <= z <= d*M, min(0,m) <= z <= max(0,M)];
function Fnew = binmodel_constraint(F);
F = lmi(F);
old_x = [];
for i = 1:length(F)
xi = sdpvar(F(i));
old_x = [old_x;xi(:)];
end
[new_x,Cut] = binmodel(old_x,F);
Fnew = [];
top = 1;
for i = 1:length(F)
m = prod(size(sdpvar(F(i))));
xi = new_x(top:top + m-1);
xo = old_x(top:top + m-1);
top = top + m;
if ~isequal(xi,xo)
switch settype(F(i))
case 'elementwise'
Fnew = [Fnew, xi >= 0];
case 'equality'
Fnew = [Fnew, xi == 0];
case 'socc'
Fnew = [Fnew, cone(xi)];
case 'sdp'
Fnew = [Fnew, reshape(xi,sqrt(m),sqrt(m)) >= 0];
otherwise
error('Type of constraint not supported in binmodel');
end
else
Fnew = [Fnew, subsref(F,struct('type','()','subs',{{i}}))];
end
end
% The internal function merges the original constraints into Cut
% remove them completely, and then add the original noncomplicating again
Cut = Cut - F;
Fnew = [Fnew,Cut];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
derivedualBoundsParameterFree.m
|
.m
|
LMI-Matlab-master/yalmip/extras/derivedualBoundsParameterFree.m
| 2,514 |
utf_8
|
56f518715fc81d312aae626a72ea92bb
|
function [dualUpper,L,U] = derivedualBoundsParameterFree(H,c,A,b,E,f,ops,parametricDomain)
if isempty(A)
dualUpper = [];
L = [];
U = [];
return
end
n = length(c);
m = length(b);
me = length(f);
x = sdpvar(n,1);
Lambda = sdpvar(m,1);
mu = sdpvar(me,1);
% Homogenization
alpha = sdpvar(1);
F = [];
% Start by computing primal lower bounds
if nargin < 7
ops = sdpsettings('verbose',0);
end
ops2 = ops;
ops2.verbose = max(0,ops.verbose-1);;
all_bounded = 1;
if ops.verbose
disp(['*Computing ' num2str(length(x)) ' primal bounds (required for dual bounds)']);
end
z = recover(unique([depends(c);depends(b)]));
xz = [x;z];
nz = length(z);
nTOT = n + length(z);
rhs = 0;
if ~isempty(b)
rhs = rhs + A'*Lambda;
end
if ~isempty(f)
rhs = rhs + E'*mu;
end
[c0,C] = deParameterize(c,z);
[b0,B] = deParameterize(b,z);
delta = binvar(length(b),1);
UpperBound = .1;
parametricDomainH = homogenize(sdpvar(parametricDomain),alpha) >= 0;
w1 = binvar(length(Lambda),1);
w2 = binvar(length(Lambda),1);
eta1 = sdpvar(length(Lambda),1);
eta2 = sdpvar(length(Lambda),1);
v = sdpvar(size(A,2),1);
Model = [parametricDomainH,H*x + alpha*c0 + C*z + rhs==0,
delta >= Lambda >= 0,
1-delta >= b0*alpha+B*z-A*x>=0,
sum(Lambda) >= alpha*UpperBound,
% sum(delta)<=1,
];
Model = [Model, Lambda + A*v + eta2-eta1 == 0,
0 <= eta1 <= w1, 0 <= delta - Lambda <= 1-w1,
0 <= eta2 <= w2, 0 <= Lambda <= 1-w2];
solvesdp(Model,-alpha)
while double(alpha) >= 1e-5
UpperBound = UpperBound*1.1;
Model = [parametricDomainH,H*x + alpha*c0 + C*z + rhs==0,
delta >= Lambda >= 0,
1-delta >= b0*alpha+B*z-A*x>=0,
sum(Lambda) >= alpha*UpperBound];
Model = [Model, Lambda + A*v + eta2-eta1 == 0,
0 <= eta1 <= w1, 0 <= delta - Lambda <= 1-w1,
0 <= eta2 <= w2, 0 <= Lambda <= 1-w2];
solvesdp(Model,-alpha);
end
dualUpper = min(U,UpperBound);
function [c0,C] = deParameterize(c,z);
n = length(c);
c0C = full(getbase(c));
c0 = c0C(:,1);
C = c0C(:,2:end);
if nnz(C)==0
C = spalloc(n,length(z),0);
else
if length(z)>0 & size(C,2) < length(z)
C = [];
for i = 1:length(z)
C = [C getbasematrix(c,getvariables(z(i)))];
end
end
end
if isempty(C)
C = zeros(length(C),length(z));
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
derandomize.m
|
.m
|
LMI-Matlab-master/yalmip/extras/derandomize.m
| 3,645 |
utf_8
|
14a3a6bc4823e6b81182566b82f8e393
|
function Fderandomized = derandomize(F)
chanceDeclarations = find(is(F,'chance'));
randomDeclarations = find(is(F,'random'));
if isempty(randomDeclarations)
error('Cannot derandomize, cannot find declaration of random variables');
end
keep = ones(length(F),1);
keep(randomDeclarations)=0;
keep(chanceDeclarations)=0;
randomVariables = extractRandomDefinitions(F(randomDeclarations));
groupedChanceConstraints = groupchanceconstraints(F);
Fderandomized = deriveChanceModel(groupedChanceConstraints,randomVariables)
Fderandomized = Fderandomized + F(find(keep));
function Fderandomized = deriveChanceModel(groupedChanceConstraints,randomVariables);
Fderandomized = [];
for ic = 1:length(groupedChanceConstraints)
if length(groupedChanceConstraints{ic})>1
error('Joint chance still not supported');
end
if ~is(groupedChanceConstraints{ic},'elementwise')
error('Only elementwise chance constraints supported')
end
X = sdpvar(groupedChanceConstraints{ic});
if length(X)>1
error('Only single elementwise chance constraints supported')
end
% OK, simple linear inequality
allVars = depends(X);
wVars = [];for j = 1:length(randomVariables);wVars = [wVars getvariables(randomVariables{j}.variables)];end
xVars = setdiff(allVars,wVars);
x = recover(xVars);
w = recover(wVars);
b = [];
A = [];
% Some pre-calc
xw = [x;w];
xind = find(ismembc(getvariables(xw),getvariables(x)));
wind = find(ismembc(getvariables(xw),getvariables(w)));
[Qs,cs,fs,dummy,nonquadratic] = vecquaddecomp(X,xw);
c_wTbase = [];
AAA = [];
ccc = [];
for i = 1:length(X)
Q = Qs{i};
c = cs{i};
f = fs{i};
if nonquadratic
error('Constraints can be at most quadratic, with the linear term uncertain');
end
Q_ww = Q(wind,wind);
Q_xw = Q(xind,wind);
Q_xx = Q(xind,xind);
c_x = c(xind);
c_w = c(wind);
%b = [b;f + c_w'*w];
%A = [A;-c_x'-w'*2*Q_xw'];
% A = [A -c_x-2*Q_xw*w];
AAA = [AAA;sparse(-2*Q_xw)];
ccc = [ccc;-sparse(c_x)];
b = [b;f];
c_wTbase = [c_wTbase;c_w'];
end
% b = b + c_wTbase*w;
% A = reshape(ccc + AAA*w,size(c_x,1),[]);
j = 1;
confidencelevel = struct(groupedChanceConstraints{ic}).clauses{1}.confidencelevel;
theMean = randomVariables{j}.distribution.parameters{1};
covariance = randomVariables{j}.distribution.parameters{2};
gamma = icdf('normal',confidencelevel,0,1);
switch randomVariables{j}.distribution.name
case 'normal'
theMean = randomVariables{j}.distribution.parameters{1};
covariance = randomVariables{j}.distribution.parameters{2};
gamma = icdf('normal',confidencelevel,0,1);
if isa(covariance,'sdpvar')
error('Covariance cannot be an SDPVAR in normal distribution. Maybe you meant to use factorized covariance in ''normalf''');
end
Fderandomized = [Fderandomized, b + c_wTbase*theMean - (ccc + AAA*theMean)'*x >= gamma*norm(chol(covariance)*(AAA'*x+c_wTbase'))];
case 'normalf'
theMean = randomVariables{j}.distribution.parameters{1};
covariance = randomVariables{j}.distribution.parameters{2};
gamma = icdf('normal',confidencelevel,0,1);
Fderandomized = [Fderandomized, b + c_wTbase*theMean - (ccc + AAA*theMean)'*x >= gamma*norm(covariance*(AAA'*x+c_wTbase'))];
otherwise
error('Distribution not supported');
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdisplay.m
|
.m
|
LMI-Matlab-master/yalmip/extras/sdisplay.m
| 10,497 |
utf_8
|
f90455026b9451c20d71013181d0348a
|
function symb_pvec = sdisplay(pvec,symbolicname)
%SDISPLAY Symbolic display of SDPVAR expression
%
% Note that the symbolic display only work if all
% involved variables are explicitely defined as
% scalar variables.
%
% Variables that not are defined as scalars
% will be given the name ryv(i). ryv means
% recovered YALMIP variables, i indicates the
% index in YALMIP (i.e. the result from getvariables)
%
% If you want to change the generic name ryv, just
% pass a second string argument
%
% EXAMPLES
% sdpvar x y
% sdisplay(x^2+y^2)
% ans =
% 'x^2+y^2'
%
% t = sdpvar(2,1);
% sdisplay(x^2+y^2+t'*t)
% ans =
% 'x^2+y^2+ryv(5)^2+ryv(6)^2'
r1=1:size(pvec,1);
r2=1:size(pvec,2);
for pi = 1:size(pvec,1)
for pj = 1:size(pvec,2)
p = pvec(pi,pj);
if isa(p,'double')
symb_p = num2str(p,10);
else
LinearVariables = depends(p);
x = recover(LinearVariables);
[exponent_p,ordered_list] = exponents(p,x);
exponent_p = full(exponent_p);
names = cell(length(x),1);
% First, some boooring stuff. we need to
% figure out the symbolic names and connect
% these names to YALMIPs variable indicies
W = evalin('caller','whos');
for i = 1:size(W,1)
if strcmp(W(i).class,'sdpvar') || strcmp(W(i).class,'ncvar')
% Get the SDPVAR variable
thevars = evalin('caller',W(i).name);
% Distinguish 4 cases
% 1: Sclalar varible x
% 2: Vector variable x(i)
% 3: Matrix variable x(i,j)
% 4: Variable not really defined
if is(thevars,'scalar') && is(thevars,'linear') && length(getvariables(thevars))==1 & isequal(getbase(thevars),[0 1])
index_in_p = find(ismember(LinearVariables,getvariables(thevars)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
if isempty(already)
already = 0;
end
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
% Case 1
names{index_in_p}=W(i).name;
end
elseif is(thevars,'lpcone')
if size(thevars,1)==size(thevars,2)
% Case 2
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for ii = indicies
index_in_p = find(ismember(LinearVariables,vars(ii)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
if isempty(already)
already = 0;
end
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
B = reshape(getbasematrix(thevars,vars(ii)),size(thevars,1),size(thevars,2));
[ix,jx,kx] = find(B);
ix=ix(1);
jx=jx(1);
names{index_in_p}=[W(i).name '(' num2str(ix) ',' num2str(jx) ')'];
end
end
else
% Case 3
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for ii = indicies
index_in_p = find(ismember(LinearVariables,vars(ii)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
if isempty(already)
already = 0;
end
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
names{index_in_p}=[W(i).name '(' num2str(ii) ')'];
end
end
end
elseif is(thevars,'sdpcone')
% Case 3
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for ii = indicies
index_in_p = find(ismember(LinearVariables,vars(ii)));
if ~isempty(index_in_p)
already = ~isempty(names{index_in_p});
if already
already = ~strfind(names{index_in_p},'internal');
end
else
already = 0;
end
if ~isempty(index_in_p) & ~already
B = reshape(getbasematrix(thevars,vars(ii)),size(thevars,1),size(thevars,2));
[ix,jx,kx] = find(B);
ix=ix(1);
jx=jx(1);
names{index_in_p}=[W(i).name '(' num2str(ix) ',' num2str(jx) ')'];
end
end
else
% Case 4
vars = getvariables(thevars);
indicies = find(ismember(vars,LinearVariables));
for i = indicies
index_in_p = find(ismember(LinearVariables,vars(i)));
if ~isempty(index_in_p) & isempty(names{index_in_p})
names{index_in_p}=['internal(' num2str(vars(i)) ')'];
end
end
end
end
end
% Okay, now got all the symbolic names compiled.
% Time to construct the expression
% The code below is also a bit fucked up at the moment, due to
% the experimental code with noncommuting stuff
% Remove 0 constant
symb_p = '';
if size(ordered_list,1)>0
nummonoms = size(ordered_list,1);
if full(getbasematrix(p,0)) ~= 0
symb_p = num2str(full(getbasematrix(p,0)));
end
elseif all(exponent_p(1,:)==0)
symb_p = num2str(full(getbasematrix(p,0)),10);
exponent_p = exponent_p(2:end,:);
nummonoms = size(exponent_p,1);
else
nummonoms = size(exponent_p,1);
end
% Loop through all monomial terms
for i = 1:nummonoms
coeff = full(getbasematrixwithoutcheck(p,i));
switch coeff
case 1
coeff='+';
case -1
coeff = '-';
otherwise
if isreal(coeff)
if coeff >0
coeff = ['+' num2str2(coeff)];
else
coeff=[num2str2(coeff)];
end
else
coeff = ['+' '(' num2str2(coeff) ')' ];
end
end
if isempty(ordered_list)
symb_p = [symb_p coeff symbmonom(names,exponent_p(i,:))];
else
symb_p = [symb_p coeff symbmonom_noncommuting(names,ordered_list(i,:))];
end
end
% Clean up some left overs, lazy coding...
symb_p = strrep(symb_p,'+*','+');
symb_p = strrep(symb_p,'-*','-');
if symb_p(1)=='+'
symb_p = symb_p(2:end);
end
if symb_p(1)=='*'
symb_p = symb_p(2:end);
end
end
symb_pvec{pi,pj} = symb_p;
end
end
if prod(size(symb_pvec))==1 & nargout==0
display(symb_pvec{1,1});
clear symb_pvec
end
function s = symbmonom(names,monom)
s = '';
for j = 1:length(monom)
if abs( monom(j))>0
if isempty(names{j})
names{j} = ['internal(' num2str(j) ')'];
end
s = [s '*' names{j}];
if monom(j)~=1
s = [s '^' num2str(monom(j))];
end
end
end
function s = symbmonom_noncommuting(names,monom)
s = '';
j = 1;
while j <= length(monom)
if abs( monom(j))>0
if isempty(names{monom(j)})
names{monom(j)} = ['internal(' num2str(j) ')'];
end
s = [s '*' names{monom(j)}];
power = 1;
k = j;
while j<length(monom) & monom(j) == monom(j+1)
power = power + 1;
j = j + 1;
%if j == (length(monom)-1)
% j = 5;
%end
end
if power~=1
s = [s '^' num2str(power)];
end
end
j = j + 1;
end
function s = num2str2(x)
s = evalc('disp(x)');
s(s==10)=[];
s(s==32)=[];
%disp(full(x))
%s = num2str(full(x),10);
if isequal(s,'1')
s = '';
end
if isequal(s,'-1')
s = '-';
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
yalmip.m
|
.m
|
LMI-Matlab-master/yalmip/extras/yalmip.m
| 55,094 |
utf_8
|
5973f49d728e3b655ac45234688eea26
|
function varargout = yalmip(varargin)
%YALMIP Returns various information about YALMIP
%
% YALMIP can be used to check version numbers and
% find the SDPVAR and SET objects available in workspace
%
% EXAMPLES
% V = YALMIP('version') % Returns version
% YALMIP('nvars') % Returns total number of declared variables
% YALMIP('info') % Display basic info.
% YALMIP('solver','tag') % Sets the solver 'solvertag' (see sdpsettings) as default solver
%
%
% If you want information on how to use YALMIP, you are advised to check out
% http://users.isy.liu.se/johanl/yalmip/
%
% See also YALMIPTEST, YALMIPDEMO
persistent prefered_solver internal_sdpvarstate internal_setstate
if nargin==0
help yalmip
return
end
if isempty(internal_sdpvarstate)
if exist('OCTAVE_VERSION', 'builtin')
more off
end
internal_sdpvarstate.monomtable = spalloc(0,0,0); % Polynomial powers table
internal_sdpvarstate.hashedmonomtable = []; % Hashed polynomial powers table
internal_sdpvarstate.hash = [];
internal_sdpvarstate.boundlist = [];
internal_sdpvarstate.variabletype = spalloc(0,0,0); % Pre-calc linear/quadratic/polynomial/sigmonial
internal_sdpvarstate.intVariables = []; % ID of integer variables
internal_sdpvarstate.binVariables = []; % ID of binary variables
internal_sdpvarstate.semicontVariables = [];
internal_sdpvarstate.uncVariables = []; % ID of uncertain variables (not used)
internal_sdpvarstate.parVariables = []; % ID of parametric variables (not used)
internal_sdpvarstate.extVariables = []; % ID of extended variables (for max,min,norm,sin, etc)
internal_sdpvarstate.auxVariables = []; % ID of auxilliary variables (introduced when modelling extended variables)
internal_sdpvarstate.auxVariablesW = []; % ID of uncertain auxilliary variables (introduced when modelling uncertain extended variables)
internal_sdpvarstate.logicVariables = []; % ID of extended logic variables (for or, nnz, alldifferent etc)
internal_sdpvarstate.complexpair = [];
internal_sdpvarstate.internalconstraints = [];
internal_sdpvarstate.ExtendedMap = [];
internal_sdpvarstate.ExtendedMapHashes = [];
internal_sdpvarstate.DependencyMap = sparse(0);
internal_sdpvarstate.DependencyMapUser = sparse(0);
internal_sdpvarstate.sosid = 0;
internal_sdpvarstate.sos_index = [];
internal_sdpvarstate.sos_data = [];
internal_sdpvarstate.sos_ParV = [];
internal_sdpvarstate.sos_Q = [];
internal_sdpvarstate.sos_v = [];
internal_sdpvarstate.optSolution{1}.info = 'Initialized by YALMIP';
internal_sdpvarstate.optSolution{1}.variables = [];
internal_sdpvarstate.optSolution{1}.optvar =[];
internal_sdpvarstate.optSolution{1}.values =[];
internal_sdpvarstate.activeSolution = 1;
internal_sdpvarstate.nonCommutingTable = [];
internal_sdpvarstate.nonHermitiannonCommutingTable = [];
try
warning off Octave:possible-matlab-short-circuit-operator
catch
end
end
if isempty(internal_setstate)
internal_setstate.LMIid = 0;
internal_setstate.duals_index = [];
internal_setstate.duals_data = [];
internal_setstate.duals_associated_index = [];
internal_setstate.duals_associated_data = [];
end
switch varargin{1}
case 'clearsolution'
internal_sdpvarstate.optSolution{1}.variables = [];
internal_sdpvarstate.optSolution{1}.optvar =[];
internal_sdpvarstate.optSolution{1}.values =[];
internal_sdpvarstate.activeSolution = 1;
case 'monomtable'
varargout{1} = internal_sdpvarstate.monomtable;
n = size(internal_sdpvarstate.monomtable,1);
if size(internal_sdpvarstate.monomtable,2) < n
% Normalize the monomtalbe. Some external functions presume the
% table is square
varargout{1}(n,n) = 0;
internal_sdpvarstate.monomtable = varargout{1};
need_new = size(internal_sdpvarstate.monomtable,1) - length(internal_sdpvarstate.hash);
internal_sdpvarstate.hash = [internal_sdpvarstate.hash ; 3*gen_rand_hash(size(internal_sdpvarstate.monomtable,1),need_new,1)];
internal_sdpvarstate.hashedmonomtable = internal_sdpvarstate.monomtable*internal_sdpvarstate.hash;
end
if nargout == 2
varargout{2} = internal_sdpvarstate.variabletype;
elseif nargout == 4
varargout{2} = internal_sdpvarstate.variabletype;
varargout{3} = internal_sdpvarstate.hashedmonomtable;
varargout{4} = internal_sdpvarstate.hash;
end
case 'setmonomtable'
% New monom table
internal_sdpvarstate.monomtable = varargin{2};
if nargin>=4
% User has up-dated the hash tables him self.
internal_sdpvarstate.hashedmonomtable=varargin{4};
internal_sdpvarstate.hash = varargin{5};
end
if size(internal_sdpvarstate.monomtable,2)>length(internal_sdpvarstate.hash)
need_new = size(internal_sdpvarstate.monomtable,1) - length(internal_sdpvarstate.hash);
internal_sdpvarstate.hash = [internal_sdpvarstate.hash ; 3*gen_rand_hash(size(internal_sdpvarstate.monomtable,1),need_new,1)];
end
if size(internal_sdpvarstate.monomtable,1)>size(internal_sdpvarstate.hashedmonomtable,1)
% Need to add some hash values
need_new = size(internal_sdpvarstate.monomtable,1) - size(internal_sdpvarstate.hashedmonomtable,1);
temp = internal_sdpvarstate.monomtable(end-need_new+1:end,:);
internal_sdpvarstate.hashedmonomtable = [internal_sdpvarstate.hashedmonomtable;temp*internal_sdpvarstate.hash];
end
if nargin >= 3 && ~isempty(varargin{3})
internal_sdpvarstate.variabletype = varargin{3};
if length(internal_sdpvarstate.variabletype) ~=size(internal_sdpvarstate.monomtable,1)
error('ASSERT')
end
else
internal_sdpvarstate.variabletype = zeros(size(internal_sdpvarstate.monomtable,1),1)';
nonlinear = ~(sum(internal_sdpvarstate.monomtable,2)==1 & sum(internal_sdpvarstate.monomtable~=0,2)==1);
if ~isempty(nonlinear)
%mt = internal_sdpvarstate.monomtable;
internal_sdpvarstate.variabletype(nonlinear) = 3;
quadratic = sum(internal_sdpvarstate.monomtable,2)==2;
internal_sdpvarstate.variabletype(quadratic) = 2;
bilinear = max(internal_sdpvarstate.monomtable,[],2)<=1;
internal_sdpvarstate.variabletype(bilinear & quadratic) = 1;
sigmonial = any(0>internal_sdpvarstate.monomtable,2) | any(internal_sdpvarstate.monomtable-fix(internal_sdpvarstate.monomtable),2);
internal_sdpvarstate.variabletype(sigmonial) = 4;
end
end
case 'variabletype'
varargout{1} = internal_sdpvarstate.variabletype;
case {'addextendedvariable','addEvalVariable'}
varargin{2}
disp('Obsolete use of the terms addextendedvariable and addEvalVariable');
error('Obsolete use of the terms addextendedvariable and addEvalVariable');
case 'defineVectorizedUnitary'
varargin{2} = strrep(varargin{2},'sdpvar/',''); % Clean due to different behaviour of the function mfilename in ML 5,6 and 7
% Is this operator variable already defined
correct_operator = [];
if ~isempty(internal_sdpvarstate.ExtendedMap)
OperatorName = varargin{2};
Arguments = {varargin{3:end}};
this_hash = create_trivial_hash(firstSDPVAR(Arguments));
correct_operator = find([internal_sdpvarstate.ExtendedMapHashes == this_hash]);
if ~isempty(correct_operator)
correct_operator = correct_operator(strcmp(OperatorName,{internal_sdpvarstate.ExtendedMap(correct_operator).fcn}));
end
for i = correct_operator
if this_hash == internal_sdpvarstate.ExtendedMap(i).Hash
if isequalwithequalnans(Arguments, {internal_sdpvarstate.ExtendedMap(i).arg{1:end-1}});
if length(internal_sdpvarstate.ExtendedMap(i).computes)>1
varargout{1} = recover(internal_sdpvarstate.ExtendedMap(i).computes);
else
varargout{1} = internal_sdpvarstate.ExtendedMap(i).var;
end
varargout{1} = setoperatorname(varargout{1},varargin{2});
return
end
end
end
else
this_hash = create_trivial_hash(firstSDPVAR({varargin{3:end}}));
end
X = varargin{3:end};
if is(X,'unitary')
allXunitary = 1;
else
allXunitary = 0;
end
y = sdpvar(numel(X),1);
allNewExtended = [];
allNewExtendedIndex = [];
allPreviouslyDefinedExtendedToIndex = [];
allPreviouslyDefinedExtendedFromIndex = [];
if ~isempty(internal_sdpvarstate.ExtendedMap)
correct_operator = find(strcmp(varargin{2},{internal_sdpvarstate.ExtendedMap(:).fcn}));
end
z = sdpvar(numel(X),1); % Standard format y=f(z),z==arg
internal_sdpvarstate.auxVariables = [ internal_sdpvarstate.auxVariables getvariables(z)];
internal_sdpvarstate.auxVariables = [ internal_sdpvarstate.auxVariables getvariables(y)];
vec_hashes = create_trivial_vechash(X);
vec_isdoubles = create_vecisdouble(X);
if isempty(correct_operator)
availableHashes = [];
else
availableHashes = [internal_sdpvarstate.ExtendedMap(correct_operator).Hash];
end
if isempty(availableHashes) && length(vec_hashes)>1 && all(diff(sort(vec_hashes))>0)
simpleAllDifferentNew = 1;
else
simpleAllDifferentNew = 0;
end
for i = 1:numel(X)
% we have to search through all scalar operators
% to find this single element
found = 0;
Xi = [];
if ~simpleAllDifferentNew
if vec_isdoubles(i)
found = 1;
y(i) = X(i);
else
if ~isempty(correct_operator)
this_hash = vec_hashes(i);
correct_hash = correct_operator(find(this_hash == availableHashes));
if ~isempty(correct_hash)
Xi = X(i);
end
for j = correct_hash(:)'
if isequal(Xi,internal_sdpvarstate.ExtendedMap(j).arg{1},1)
allPreviouslyDefinedExtendedToIndex = [allPreviouslyDefinedExtendedToIndex i];
allPreviouslyDefinedExtendedFromIndex = [allPreviouslyDefinedExtendedFromIndex j];
found = 1;
break
end
end
end
end
end
if ~found
yi = y(i);
if isempty(Xi)
Xi = X(i);
end
internal_sdpvarstate.ExtendedMap(end+1).fcn = varargin{2};
if allXunitary
internal_sdpvarstate.ExtendedMap(end).arg = {Xi,[]};
else
if is(Xi,'unitary')
internal_sdpvarstate.ExtendedMap(end).arg = {Xi,[]};
else
internal_sdpvarstate.ExtendedMap(end).arg = {Xi,z(i)};
end
end
internal_sdpvarstate.ExtendedMap(end).var = yi;
internal_sdpvarstate.ExtendedMap(end).computes = getvariables(yi);
new_hash = create_trivial_hash(Xi);
internal_sdpvarstate.ExtendedMap(end).Hash = new_hash;
internal_sdpvarstate.ExtendedMapHashes = [internal_sdpvarstate.ExtendedMapHashes new_hash];
allNewExtendedIndex = [allNewExtendedIndex i];
availableHashes = [availableHashes new_hash];
correct_operator = [correct_operator length( internal_sdpvarstate.ExtendedMap)];
end
end
y(allPreviouslyDefinedExtendedToIndex) = [internal_sdpvarstate.ExtendedMap(allPreviouslyDefinedExtendedFromIndex).var];
allNewExtended = y(allNewExtendedIndex);
y_vars = getvariables(allNewExtended);
internal_sdpvarstate.extVariables = [internal_sdpvarstate.extVariables y_vars];
y = reshape(y,size(X,1),size(X,2));
y = setoperatorname(y,varargin{2});
varargout{1} = y;
yV = getvariables(y);
yB = getbase(y);yB = yB(:,2:end);
xV = getvariables(X);
xB = getbase(X);xB = xB(:,2:end);
internal_sdpvarstate.DependencyMap(max(yV),max(xV))=sparse(0);
for i = 1:length(yV)
internal_sdpvarstate.DependencyMap(yV(find(yB(i,:))),xV(find(xB(i,:))))=1;
end
%yalmip('setdependence',getvariables(y),getvariables(X));
return
case {'define','definemulti'}
if strcmpi(varargin{1},'define')
multioutput = 0;
nout = [1 1];
else
multioutput = 1;
nout = varargin{end};
varargin = {varargin{1:end-1}};
end
varargin{2} = strrep(varargin{2},'sdpvar/',''); % Clean due to different behaviour of the function mfilename in ML 5,6 and 7
% Is this operator variable already defined
correct_operator = [];
if ~isempty(internal_sdpvarstate.ExtendedMap)
OperatorName = varargin{2};
Arguments = {varargin{3:end}};
this_hash = create_trivial_hash(firstSDPVAR(Arguments));
correct_operator = find([internal_sdpvarstate.ExtendedMapHashes == this_hash]);
if ~isempty(correct_operator)
correct_operator = correct_operator(strcmp(OperatorName,{internal_sdpvarstate.ExtendedMap(correct_operator).fcn}));
end
for i = correct_operator
% if this_hash == internal_sdpvarstate.ExtendedMap(i).Hash
if isequalwithequalnans(Arguments, {internal_sdpvarstate.ExtendedMap(i).arg{1:end-1}});
if length(internal_sdpvarstate.ExtendedMap(i).computes)>1
varargout{1} = recover(internal_sdpvarstate.ExtendedMap(i).computes);
else
varargout{1} = internal_sdpvarstate.ExtendedMap(i).var;
end
varargout{1} = setoperatorname(varargout{1},varargin{2});
return
end
% end
end
else
this_hash = create_trivial_hash(firstSDPVAR({varargin{3:end}}));
end
switch varargin{2}
case {'max_internal'}
% MAX is a bit special since we need one
% new variable for each column...
% (can be implemented standard way, but this is better
% for performance, and since MAX is so common...
X = varargin{3:end};
[n,m] = size(X);
if min([n m]) == 1
y = sdpvar(1,1);
internal_sdpvarstate.ExtendedMap(end+1).fcn = varargin{2};
internal_sdpvarstate.ExtendedMap(end).arg = {varargin{3:end},[]};
internal_sdpvarstate.ExtendedMap(end).var = y;
internal_sdpvarstate.ExtendedMap(end).computes = getvariables(y);
internal_sdpvarstate.extVariables = [internal_sdpvarstate.extVariables getvariables(y)];
internal_sdpvarstate.ExtendedMap(end).Hash = this_hash;
internal_sdpvarstate.ExtendedMapHashes = [internal_sdpvarstate.ExtendedMapHashes this_hash];
else
y = sdpvar(1,m);
for i = 1:m
internal_sdpvarstate.ExtendedMap(end+1).fcn = varargin{2};
internal_sdpvarstate.ExtendedMap(end).arg = {X(:,i),[]};
internal_sdpvarstate.ExtendedMap(end).var = y(i);
internal_sdpvarstate.ExtendedMap(end).computes = getvariables(y(i));
new_hash = create_trivial_hash(X(:,i));
internal_sdpvarstate.ExtendedMap(end).Hash = new_hash;
internal_sdpvarstate.ExtendedMapHashes = [internal_sdpvarstate.ExtendedMapHashes new_hash];
end
internal_sdpvarstate.extVariables = [internal_sdpvarstate.extVariables getvariables(y)];
end
y = setoperatorname(y,varargin{2});
case {'abs'}
% ABS is a bit special since we need one
% new variable for each element...
X = varargin{3:end};
y = sdpvar(numel(X),1);
allNewExtended = [];
allNewExtendedIndex = [];
allPreviouslyDefinedExtendedToIndex = [];
allPreviouslyDefinedExtendedFromIndex = [];
if ~isempty(internal_sdpvarstate.ExtendedMap)
correct_operator = find(strcmp(varargin{2},{internal_sdpvarstate.ExtendedMap(:).fcn}));
end
if numel(X)==1
found = 0;
if ~isempty(correct_operator)
this_hash = create_trivial_hash(X);
for j = correct_operator;% find(correct_operator)
if this_hash == internal_sdpvarstate.ExtendedMap(j).Hash
if isequal(X,internal_sdpvarstate.ExtendedMap(j).arg{1},1)
% y = internal_sdpvarstate.ExtendedMap(j).var;
allPreviouslyDefinedExtendedToIndex = [1];
allPreviouslyDefinedExtendedFromIndex = [j];
found = 1;
break
end
end
end
end
if ~found
internal_sdpvarstate.ExtendedMap(end+1).fcn = varargin{2};
internal_sdpvarstate.ExtendedMap(end).arg = {X,binvar(1),[]};
internal_sdpvarstate.ExtendedMap(end).var = y;
internal_sdpvarstate.ExtendedMap(end).computes = getvariables(y);
new_hash = create_trivial_hash(X);
internal_sdpvarstate.ExtendedMap(end).Hash = new_hash;
internal_sdpvarstate.ExtendedMapHashes = [internal_sdpvarstate.ExtendedMapHashes new_hash];
allNewExtended = y;
allNewExtendedIndex = 1;
end
else
aux_bin = binvar(numel(X),1);
vec_hashes = create_trivial_vechash(X);
vec_isdoubles = create_vecisdouble(X);
for i = 1:numel(X)
% This is a bummer. If we scalarize the abs-operator,
% we have to search through all scalar abs-operators
% to find this single element
found = 0;
Xi = X(i);
if vec_isdoubles(i)%isa(Xi,'double')
found = 1;
y(i) = abs(X(i));
else
if ~isempty(correct_operator)
this_hash = vec_hashes(i);
for j = correct_operator
if this_hash == internal_sdpvarstate.ExtendedMap(j).Hash
if isequal(Xi,internal_sdpvarstate.ExtendedMap(j).arg{1},1)
allPreviouslyDefinedExtendedToIndex = [allPreviouslyDefinedExtendedToIndex i];
allPreviouslyDefinedExtendedFromIndex = [allPreviouslyDefinedExtendedFromIndex j];
found = 1;
break
end
end
end
end
end
if ~found
yi = y(i);
internal_sdpvarstate.ExtendedMap(end+1).fcn = varargin{2};
internal_sdpvarstate.ExtendedMap(end).arg = {Xi,aux_bin(i),[]};
internal_sdpvarstate.ExtendedMap(end).var = yi;
internal_sdpvarstate.ExtendedMap(end).computes = getvariables(yi);
new_hash = create_trivial_hash(Xi);
internal_sdpvarstate.ExtendedMap(end).Hash = new_hash;
internal_sdpvarstate.ExtendedMapHashes = [internal_sdpvarstate.ExtendedMapHashes new_hash];
allNewExtendedIndex = [allNewExtendedIndex i];
% Add this to the list of possible matches.
% Required for repeated elements in argument
% (such as a symmetric matrix)
correct_operator = [correct_operator length(internal_sdpvarstate.ExtendedMap)];
end
end
end
y(allPreviouslyDefinedExtendedToIndex) = [internal_sdpvarstate.ExtendedMap(allPreviouslyDefinedExtendedFromIndex).var];
allNewExtended = y(allNewExtendedIndex);
y_vars = getvariables(allNewExtended);
internal_sdpvarstate.extVariables = [internal_sdpvarstate.extVariables y_vars];
y = reshape(y,size(X,1),size(X,2));
y = setoperatorname(y,varargin{2});
otherwise
% This is the standard operators. INPUTS -> 1 scalar output
if isequal(varargin{2},'or') || isequal(varargin{2},'xor') || isequal(varargin{2},'and')
y = binvar(1,1);
else
y = sdpvar(nout(1),nout(2));
end
if ~strcmpi({'sort'},varargin{2})
% Oh fuck is this ugly. Sort assumes ordering on some
% variables, and thus assumes no z in between. This
% will be generalized when R^n -> R^m is supported for
% real
% Actually, we can skip these normalizing variables for
% everything which isn't based on callbacks. This saves
% a lot of setup time on huge models
if ~(strcmp(varargin{2},'norm') || strcmp(varargin{2},'abs'))
z = sdpvar(size(varargin{3},1),size(varargin{3},2),'full'); % Standard format y=f(z),z==arg
internal_sdpvarstate.auxVariables = [ internal_sdpvarstate.auxVariables getvariables(z)];
else
z = [];
end
internal_sdpvarstate.auxVariables = [ internal_sdpvarstate.auxVariables getvariables(y)];
else
z = [];
end
for i = 1:nout
% Avoid subsref to save time
if nout == 1
yi = y;
else
yi = y(i);
end
internal_sdpvarstate.ExtendedMap(end+1).fcn = varargin{2};
internal_sdpvarstate.ExtendedMap(end).arg = {varargin{3:end},z};
internal_sdpvarstate.ExtendedMap(end).var = yi;
internal_sdpvarstate.ExtendedMap(end).computes = getvariables(y);
internal_sdpvarstate.ExtendedMap(end).Hash = this_hash;
internal_sdpvarstate.ExtendedMapHashes = [internal_sdpvarstate.ExtendedMapHashes this_hash];
internal_sdpvarstate.extVariables = [internal_sdpvarstate.extVariables getvariables(yi)];
end
y = setoperatorname(y,varargin{2});
end
for i = 3:length(varargin)
if isa(varargin{i},'sdpvar')
yalmip('setdependence',getvariables(y),getvariables(varargin{i}));
end
end
varargout{1} = flush(clearconic(y));
return
case 'setdependence'
if ~isempty(varargin{2}) && ~isempty(varargin{3})
if isa(varargin{2},'sdpvar')
varargin{2} = getvariables(varargin{2});
end
if isa(varargin{3},'sdpvar')
varargin{3} = getvariables(varargin{3});
end
% This dies not work since the arguments have different
% ordering. Try for instance x=sdpvar(2),[x>=0,abs(x)>=0]
% nx = max(size(internal_sdpvarstate.DependencyMap,1),max(varargin{2}));
% ny = max(size(internal_sdpvarstate.DependencyMap,2),max(varargin{3}));
% index = sub2ind([nx ny], varargin{2},varargin{3});
% if size(internal_sdpvarstate.DependencyMap,1) < nx || size(internal_sdpvarstate.DependencyMap,2) < ny
% internal_sdpvarstate.DependencyMap(nx,ny) = 0;
% end
% internal_sdpvarstate.DependencyMap(index) = 1;
internal_sdpvarstate.DependencyMap(varargin{2},varargin{3}) = 1;
n = size(internal_sdpvarstate.monomtable,1);
if size(internal_sdpvarstate.DependencyMap,1) < n
internal_sdpvarstate.DependencyMap(n,1)=0;
end
if size(internal_sdpvarstate.DependencyMap,2) < n
internal_sdpvarstate.DependencyMap(end,n)=0;
end
end
case 'setdependenceUser'
if ~isempty(varargin{2}) && ~isempty(varargin{3})
if isa(varargin{2},'sdpvar')
varargin{2} = getvariables(varargin{2});
end
if isa(varargin{3},'sdpvar')
varargin{3} = getvariables(varargin{3});
end
internal_sdpvarstate.DependencyMapUser(varargin{2},varargin{3}) = 1;
n = size(internal_sdpvarstate.monomtable,1);
if size(internal_sdpvarstate.DependencyMapUser,1) < n
internal_sdpvarstate.DependencyMapUser(n,1)=0;
end
if size(internal_sdpvarstate.DependencyMapUser,2) < n
internal_sdpvarstate.DependencyMapUser(end,n)=0;
end
end
case 'getdependence'
varargout{1} = internal_sdpvarstate.DependencyMap;
n = size(internal_sdpvarstate.monomtable,1);
if size(varargout{1},1) < n || size(varargout{1},2)<n
varargout{1}(n,n) = 0;
end
case 'getdependenceUser'
varargout{1} = internal_sdpvarstate.DependencyMapUser;
n = size(internal_sdpvarstate.monomtable,1);
if size(varargout{1},1) < n || size(varargout{1},2)<n
varargout{1}(n,n) = 0;
end
case 'getarguments'
varargout{1} = yalmip('extstruct',getvariables(varargin{2}));
case 'auxvariables'
varargout{1} = internal_sdpvarstate.auxVariables;
case 'auxvariablesW'
varargout{1} = internal_sdpvarstate.auxVariablesW;
case 'extvariables'
varargout{1} = internal_sdpvarstate.extVariables;
case 'extstruct'
if nargin == 1
varargout{1} = internal_sdpvarstate.ExtendedMap;
elseif length(varargin{2})==1
found = 0;
varargout{1} = [];
i = 1;
while ~found && i <=length(internal_sdpvarstate.ExtendedMap)
if varargin{2} == getvariables(internal_sdpvarstate.ExtendedMap(i).var)
found = 1;
varargout{1} = internal_sdpvarstate.ExtendedMap(i);
end
i = i + 1;
end
else
% If requests several extended variables, returns as cell
found = zeros(1,length(varargin{2}));
varargout{1} = cell(0,length(varargin{2}));
i = 1;
while ~all(found) && i <=length(internal_sdpvarstate.ExtendedMap)
j = find(varargin{2} == getvariables(internal_sdpvarstate.ExtendedMap(i).var));
if ~isempty(j)
found(j) = 1;
varargout{1}{j} = internal_sdpvarstate.ExtendedMap(i);
end
i = i + 1;
end
end
case 'expvariables'
expvariables = [];
for i = 1:length(internal_sdpvarstate.ExtendedMap)
if any(strcmpi(internal_sdpvarstate.ExtendedMap(i).fcn,{'exp','pexp','log','slog','plog','logsumexp','kullbackleibler','entropy'}))
expvariables = [ expvariables internal_sdpvarstate.ExtendedMap(i).computes];
end
end
varargout{1} = expvariables;
case 'rankvariables'
i = 1;
rankvariables = [];
dualrankvariables = [];
for i = 1:length(internal_sdpvarstate.ExtendedMap)
if strcmpi('rank',internal_sdpvarstate.ExtendedMap(i).fcn)
rankvariables = [rankvariables getvariables(internal_sdpvarstate.ExtendedMap(i).var)];
end
if strcmpi('dualrank',internal_sdpvarstate.ExtendedMap(i).fcn)
dualrankvariables = [dualrankvariables getvariables(internal_sdpvarstate.ExtendedMap(i).var)];
end
end
varargout{1} = rankvariables;
varargout{2} = dualrankvariables;
case {'lmiid','ConstraintID'}
if not(isempty(internal_setstate.LMIid))
internal_setstate.LMIid = internal_setstate.LMIid+1;
varargout{1}=internal_setstate.LMIid;
else
internal_setstate.LMIid=1;
varargout{1}=internal_setstate.LMIid;
end
case 'setnonlinearvariables'
error('Internal error (ref. setnonlinearvariables). Report please.')
case {'clear'}
W = evalin('caller','whos');
for i = 1:size(W,1)
if strcmp(W(i).class,'sdpvar') || strcmp(W(i).class,'lmi')
evalin('caller', ['clear ' W(i).name ';']);
end
end
internal_setstate.LMIid = 0;
internal_setstate.duals_index = [];
internal_setstate.duals_data = [];
internal_setstate.duals_associated_index = [];
internal_setstate.duals_associated_data = [];
internal_sdpvarstate.sosid = 0;
internal_sdpvarstate.sos_index = [];
internal_sdpvarstate.sos_data = [];
internal_sdpvarstate.sos_ParV = [];
internal_sdpvarstate.sos_Q = [];
internal_sdpvarstate.sos_v = [];
internal_sdpvarstate.monomtable = spalloc(0,0,0);
internal_sdpvarstate.hashedmonomtable = [];
internal_sdpvarstate.hash = [];
internal_sdpvarstate.boundlist = [];
internal_sdpvarstate.variabletype = spalloc(0,0,0);
internal_sdpvarstate.intVariables = [];
internal_sdpvarstate.binVariables = [];
internal_sdpvarstate.semicontVariables = [];
internal_sdpvarstate.uncVariables = [];
internal_sdpvarstate.parVariables = [];
internal_sdpvarstate.extVariables = [];
internal_sdpvarstate.auxVariables = [];
internal_sdpvarstate.auxVariablesW = [];
internal_sdpvarstate.logicVariables = [];
;internal_sdpvarstate.complexpair = [];
internal_sdpvarstate.internalconstraints = [];
internal_sdpvarstate.ExtendedMap = [];
internal_sdpvarstate.ExtendedMapHashes = [];
internal_sdpvarstate.DependencyMap = sparse(0);
internal_sdpvarstate.DependencyMapUser = sparse(0);
internal_sdpvarstate.optSolution{1}.info = 'Initialized by YALMIP';
internal_sdpvarstate.optSolution{1}.variables = [];
internal_sdpvarstate.optSolution{1}.optvar = [];
internal_sdpvarstate.optSolution{1}.values = [];
internal_sdpvarstate.activeSolution = 1;
internal_sdpvarstate.nonCommutingTable = [];
case 'cleardual'
if nargin==1
internal_setstate.duals_index = [];
internal_setstate.duals_data = [];
internal_setstate.duals_associated_index = [];
internal_setstate.duals_associated_data = [];
else
if ~isempty(internal_setstate.duals_index)
internal_setstate.lmiid = varargin{2};
for i = 1:length(varargin{2})
j = find(internal_setstate.duals_index==internal_setstate.lmiid(i));
if ~isempty(j)
internal_setstate.duals_index = internal_setstate.duals_index([1:1:j-1 j+1:1:length(internal_setstate.duals_index)]);
internal_setstate.duals_data = {internal_setstate.duals_data{[1:1:j-1 j+1:1:length(internal_setstate.duals_data)]}};
end
end
end
end
case 'associatedual'
internal_setstate.duals_associated_index = [internal_setstate.duals_associated_index varargin{2}];
internal_setstate.duals_associated_data{end+1} = varargin{3};
case 'addcomplexpair'
internal_sdpvarstate.complexpair = [internal_sdpvarstate.complexpair;varargin{2}];
case 'getcomplexpair'
error('Please report this error!')
varargout{1} = internal_sdpvarstate.complexpair;
return
case 'setallsolution'
internal_sdpvarstate.optSolution{internal_sdpvarstate.activeSolution}.optvar = varargin{2}.optvar;
internal_sdpvarstate.optSolution{internal_sdpvarstate.activeSolution}.variables = varargin{2}.variables;
internal_sdpvarstate.optSolution{internal_sdpvarstate.activeSolution}.values = [];
return
case 'setvalues'
internal_sdpvarstate.optSolution{internal_sdpvarstate.activeSolution}.values = varargin{2};
case 'numbersolutions'
varargout{1} = length(internal_sdpvarstate.optSolution);
case 'selectsolution'
if length(internal_sdpvarstate.optSolution)>=varargin{2}
internal_sdpvarstate.activeSolution = varargin{2};
else
error('Solution not available');
end
case 'setsolution'
if nargin < 3
solutionIndex = 1;
else
solutionIndex = varargin{3};
end
internal_sdpvarstate.activeSolution = 1;
% Clear trailing solutions
if solutionIndex < length(internal_sdpvarstate.optSolution)
internal_sdpvarstate.optSolution = {internal_sdpvarstate.optSolution{1:solutionIndex}};
elseif solutionIndex > length(internal_sdpvarstate.optSolution)+1
for j = length(internal_sdpvarstate.optSolution)+1:solutionIndex
internal_sdpvarstate.optSolution{j}.optvar=[];
internal_sdpvarstate.optSolution{j}.variables=[];
internal_sdpvarstate.optSolution{j}.values=[];
end
elseif solutionIndex == length(internal_sdpvarstate.optSolution)+1
internal_sdpvarstate.optSolution{solutionIndex}.optvar=[];
internal_sdpvarstate.optSolution{solutionIndex}.variables=[];
internal_sdpvarstate.optSolution{solutionIndex}.values=[];
end
if isempty(internal_sdpvarstate.optSolution{solutionIndex}.variables)
internal_sdpvarstate.optSolution{solutionIndex} = varargin{2};
else
% Just save some stuff first
newSolution = varargin{2};
oldSolution = internal_sdpvarstate.optSolution{solutionIndex};
optSolution = varargin{2};
keep_these = find(~ismember(oldSolution.variables,newSolution.variables));
internal_sdpvarstate.optSolution{solutionIndex}.optvar = [oldSolution.optvar(keep_these);newSolution.optvar(:)];
internal_sdpvarstate.optSolution{solutionIndex}.variables = [oldSolution.variables(keep_these);newSolution.variables(:)];
end
% clear evaluated values (only used cache-wise)
internal_sdpvarstate.optSolution{solutionIndex}.values = [];
return
% case 'setsolution'
%
% if isempty(internal_sdpvarstate.optSolution.variables)
% internal_sdpvarstate.optSolution = varargin{2};
% else
% % Just save some stuff first
% newSolution = varargin{2};
% oldSolution = internal_sdpvarstate.optSolution;
% optSolution = varargin{2};
% keep_these = find(~ismember(oldSolution.variables,newSolution.variables));
% internal_sdpvarstate.optSolution.optvar = [oldSolution.optvar(keep_these);newSolution.optvar(:)];
% internal_sdpvarstate.optSolution.variables = [oldSolution.variables(keep_these);newSolution.variables(:)];
% end
% % clear evaluated values (only used cache-wise)
% internal_sdpvarstate.optSolution.values = [];
% return
case 'addauxvariables'
internal_sdpvarstate.auxVariables = [internal_sdpvarstate.auxVariables varargin{2}(:)'];
case 'addauxvariablesW'
internal_sdpvarstate.auxVariablesW = [internal_sdpvarstate.auxVariablesW varargin{2}(:)'];
case 'getsolution'
varargout{1} = internal_sdpvarstate.optSolution{internal_sdpvarstate.activeSolution};
return
case 'setdual'
internal_setstate.duals_index = varargin{2};
internal_setstate.duals_data = varargin{3};
if ~isempty(internal_setstate.duals_associated_index)
if ~isempty(intersect(internal_setstate.duals_index,internal_setstate.duals_associated_index))
for i = 1:length(internal_setstate.duals_index)
itshere = find(internal_setstate.duals_associated_index==internal_setstate.duals_index(i));
if ~isempty(itshere)
assign(internal_setstate.duals_associated_data{itshere},internal_setstate.duals_data{i});
end
end
end
end
case 'dual'
if isempty(internal_setstate.duals_index)
varargout{1}=[];
else
LMIid = varargin{2};
index_to_dual = find(LMIid==internal_setstate.duals_index);
if isempty(index_to_dual)
varargout{1}=[];
else
varargout{1} = internal_setstate.duals_data{index_to_dual};
end
end
case 'clearsos'
if nargin==1
internal_sdpvarstate.sos_index = [];
internal_sdpvarstate.sos_data = [];
internal_sdpvarstate.sos_ParV = [];
internal_sdpvarstate.sos_Q = [];
internal_sdpvarstate.sos_v = [];
end
case 'setsos'
if ~isempty(internal_sdpvarstate.sos_index)
where = find(internal_sdpvarstate.sos_index==varargin{2});
if ~isempty(where)
internal_sdpvarstate.sos_index(where) = varargin{2};
internal_sdpvarstate.sos_data{where} = varargin{3};
internal_sdpvarstate.sos_ParV{where} = varargin{4};
internal_sdpvarstate.sos_Q{where} = varargin{5};
internal_sdpvarstate.sos_v{where} = varargin{6};
else
internal_sdpvarstate.sos_index(end+1) = varargin{2};
internal_sdpvarstate.sos_data{end+1} = varargin{3};
internal_sdpvarstate.sos_ParV{end+1} = varargin{4};
internal_sdpvarstate.sos_Q{end+1} = varargin{5};
internal_sdpvarstate.sos_v{end+1} = varargin{6};
end
else
internal_sdpvarstate.sos_index(end+1) = varargin{2};
internal_sdpvarstate.sos_data{end+1} = varargin{3};
internal_sdpvarstate.sos_ParV{end+1} = varargin{4};
internal_sdpvarstate.sos_Q{end+1} = varargin{5};
internal_sdpvarstate.sos_v{end+1} = varargin{6};
end
case 'sosid'
if not(isempty(internal_sdpvarstate.sosid))
internal_sdpvarstate.sosid = internal_sdpvarstate.sosid+1;
varargout{1}=internal_sdpvarstate.sosid;
else
internal_sdpvarstate.sosid=1;
varargout{1}=internal_sdpvarstate.sosid;
end
case 'getsos'
if isempty(internal_sdpvarstate.sos_index)
varargout{1}=[];
varargout{2}=[];
varargout{3}=[];
varargout{4}=[];
else
SOSid = varargin{2};
index_to_sos = find(SOSid==internal_sdpvarstate.sos_index);
if isempty(index_to_sos)
varargout{1}=[];
varargout{2}=[];
varargout{3}=[];
varargout{4}=[];
else
varargout{1} = internal_sdpvarstate.sos_data{index_to_sos};
varargout{2} = internal_sdpvarstate.sos_ParV{index_to_sos};
varargout{3} = internal_sdpvarstate.sos_Q{index_to_sos};
varargout{4} = internal_sdpvarstate.sos_v{index_to_sos};
% FIX
end
end
case 'getinternalsetstate'
varargout{1} = internal_setstate; % Get internal state, called from saveobj
case 'setinternalsetstate'
internal_setstate = varargin{2}; % Set internal state, called from loadobj
case 'getinternalsdpvarstate'
varargout{1} = internal_sdpvarstate; % Get internal state, called from saveobj
case 'setinternalsdpvarstate'
internal_sdpvarstate = varargin{2}; % Set internal state, called from loadobj
% Back-wards compability....
if ~isfield(internal_sdpvarstate,'extVariables')
internal_sdpvarstate.extVariables = [];
end
if ~isfield(internal_sdpvarstate,'ExtendedMap')
internal_sdpvarstate.ExtendedMap = [];
end
if ~isfield(internal_sdpvarstate,'ExtendedMapHashes')
internal_sdpvarstate.ExtendedMapHashes = [];
end
if ~isfield(internal_sdpvarstate,'variabletype')
internal_sdpvarstate.variabletype = ~(sum(internal_sdpvarstate.monomtable,2)==1 & sum(internal_sdpvarstate.monomtable~=0,2)==1);
end
if ~isfield(internal_sdpvarstate,'hash')
internal_sdpvarstate.hash=[];
internal_sdpvarstate.hashedmonomtable=[];
end
% Re-compute some stuff for safety
internal_sdpvarstate.variabletype = internal_sdpvarstate.variabletype(:)';
internal_sdpvarstate.variabletype = spalloc(size(internal_sdpvarstate.monomtable,1),1,0)';
nonlinear = ~(sum(internal_sdpvarstate.monomtable,2)==1 & sum(internal_sdpvarstate.monomtable~=0,2)==1);
if ~isempty(nonlinear)
mt = internal_sdpvarstate.monomtable;
internal_sdpvarstate.variabletype(nonlinear) = 3;
quadratic = sum(internal_sdpvarstate.monomtable,2)==2;
internal_sdpvarstate.variabletype(quadratic) = 2;
bilinear = max(internal_sdpvarstate.monomtable,[],2)<=1;
internal_sdpvarstate.variabletype(bilinear & quadratic) = 1;
sigmonial = any(0>internal_sdpvarstate.monomtable,2) | any(internal_sdpvarstate.monomtable-fix(internal_sdpvarstate.monomtable),2);
internal_sdpvarstate.variabletype(sigmonial) = 4;
end
[n,m] = size(internal_sdpvarstate.monomtable);
if n>m
internal_sdpvarstate.monomtable(n,n) = 0;
end
if size(internal_sdpvarstate.monomtable,2)>length(internal_sdpvarstate.hash)
% Need new hash-keys
internal_sdpvarstate.hash = [internal_sdpvarstate.hash ; 3*gen_rand_hash(size(internal_sdpvarstate.monomtable,1),need_new,1)];
end
if size(internal_sdpvarstate.monomtable,1)>size(internal_sdpvarstate.hashedmonomtable,1)
% Need to add some hash values
need_new = size(internal_sdpvarstate.monomtable,1) - size(internal_sdpvarstate.hashedmonomtable,1);
internal_sdpvarstate.hashedmonomtable = [internal_sdpvarstate.hashedmonomtable;internal_sdpvarstate.monomtable(end-need_new+1:end,:)*internal_sdpvarstate.hash];
end
case {'version','ver'}
varargout{1} = '20150919';
case 'setintvariables'
internal_sdpvarstate.intVariables = varargin{2};
case 'intvariables'
varargout{1} = internal_sdpvarstate.intVariables;
case 'setbinvariables'
internal_sdpvarstate.binVariables = varargin{2};
case 'binvariables'
varargout{1} = internal_sdpvarstate.binVariables;
case 'quantvariables'
varargout{1} = [internal_sdpvarstate.binVariables internal_sdpvarstate.intVariables];
case 'setsemicontvariables'
internal_sdpvarstate.semicontVariables = varargin{2};
case 'semicontvariables'
varargout{1} = internal_sdpvarstate.semicontVariables;
case 'setuncvariables'
internal_sdpvarstate.uncVariables = varargin{2};
case 'uncvariables'
varargout{1} = internal_sdpvarstate.uncVariables;
case 'setparvariables'
internal_sdpvarstate.parVariables = varargin{2};
case 'parvariables'
varargout{1} = internal_sdpvarstate.parVariables;
case 'nonCommutingVariables'
if isempty(internal_sdpvarstate.nonCommutingTable)
varargout{1} = [];
else
varargout{1} = find(isnan(internal_sdpvarstate.nonCommutingTable(:,1)));
end
case 'nonCommutingTable'
if nargin == 2
internal_sdpvarstate.nonCommutingTable = varargin{2};
else
varargout{1} = internal_sdpvarstate.nonCommutingTable;
end
case 'nonlinearvariables'
error('Internal error (ref. nonlinear variables). Report!')
varargout{1} = internal_sdpvarstate.nonlinearvariables;
if nargout==2
varargout{2} = internal_sdpvarstate.nonlinearvariablesCompressed;
end
%
case {'addinternal'}
internal_sdpvarstate.internalconstraints{end+1} = varargin{1};
% case {'setnvars'}
% sdpvar('setnvars',varargin{2});
case {'nvars'}
varargout{1} = size(internal_sdpvarstate.monomtable,1);
% varargout{1} = sdpvar('nvars');
case {'info'}
[version,release] = yalmip('version');
currentversion = num2str(version(1));
i = 1;
while i<length(version)
i = i+1;
currentversion = [currentversion '.' num2str(version(i))];
end
info_str = ['- - - - YALMIP ' currentversion ' ' num2str(release) ' - - - -'];
disp(' ');
disp(char(repmat(double('*'),1,length(info_str))));
disp(info_str)
disp(char(repmat(double('*'),1,length(info_str))));
disp(' ');
disp(['Variable Size'])
spaces = [' '];
ws = evalin('caller','whos');
n = 0;
for i = 1:size(ws,1)
if strcmp(ws(i).class,'sdpvar')
n = n+1;
wsname = ws(i).name;
wssize = [num2str(ws(i).size(1)) 'x' num2str(ws(i).size(2))];
disp([wsname spaces(1:13-length(wsname)) wssize]);
end
end
if n == 0
disp('No SDPVAR objects found');
end
disp(' ');
disp(['LMI']);
n = 0;
for i = 1:size(ws,1)
if strcmp(ws(i).class,'lmi')
n = n+1;
wsname = ws(i).name;
disp([wsname]);
end
end
if n == 0
disp('No SET objects found');
end
case 'getbounds'
if ~isfield(internal_sdpvarstate,'boundlist')
internal_sdpvarstate.boundlist = inf*repmat([-1 1],size(internal_sdpvarstate.monomtable,1),1);
elseif isempty(internal_sdpvarstate.boundlist)
internal_sdpvarstate.boundlist = inf*repmat([-1 1],size(internal_sdpvarstate.monomtable,1),1);
end
indicies = varargin{2};
if max(indicies)>size(internal_sdpvarstate.boundlist,1)
need_new = max(indicies)-size(internal_sdpvarstate.boundlist,1);
internal_sdpvarstate.boundlist = [internal_sdpvarstate.boundlist;inf*repmat([-1 1],size(internal_sdpvarstate.monomtable,1),1)];
end
varargout{1} = internal_sdpvarstate.boundlist(indicies,:);
varargout{2} = internal_sdpvarstate.boundlist(indicies,:);
case 'setbounds'
if ~isfield(internal_sdpvarstate,'boundlist')
internal_sdpvarstate.boundlist = inf*repmat([-1 1],size(internal_sdpvarstate.monomtable,1),1);
elseif isempty(internal_sdpvarstate.boundlist)
internal_sdpvarstate.boundlist = inf*repmat([-1 1],size(internal_sdpvarstate.monomtable,1),1);
end
indicies = varargin{2};
if size(internal_sdpvarstate.boundlist,1)<min(indicies)
internal_sdpvarstate.boundlist = [internal_sdpvarstate.boundlist;repmat([-inf inf],max(indicies)-size(internal_sdpvarstate.boundlist,1),1)];
end
internal_sdpvarstate.boundlist(indicies,1) = -inf ;
internal_sdpvarstate.boundlist(indicies,2) = inf;
internal_sdpvarstate.boundlist(indicies(:),1) = varargin{3};
internal_sdpvarstate.boundlist(indicies(:),2) = varargin{4};
varargout{1}=0;
case 'extendedmap'
varargout{1} = internal_sdpvarstate.ExtendedMap;
case 'logicextvariables'
logicextvariables = [];
for i = 1:length(internal_sdpvarstate.ExtendedMap)
% if ismember(internal_sdpvarstate.ExtendedMap(i).fcn,{'or','and'})
if isequal(internal_sdpvarstate.ExtendedMap(i).fcn,'or') || isequal(internal_sdpvarstate.ExtendedMap(i).fcn,'and')
logicextvariables = [logicextvariables internal_sdpvarstate.extVariables(i)];
end
end
varargout{1} = logicextvariables;
case 'logicVariables'
varargout{1} = internal_sdpvarstate.logicVariables;
case 'addlogicvariable'
% This code essentially the same as the addextended code. The only
% difference is that we keep track of logic variables in order to
% know when we have to collect bounds for the big-M relaxations.
varargin{2} = strrep(varargin{2},'sdpvar/','');
% Is this operator variable already defined
if ~isempty(internal_sdpvarstate.ExtendedMap)
i = 1;
while i<=length(internal_sdpvarstate.ExtendedMap)
if isequal(varargin{2},internal_sdpvarstate.ExtendedMap(i).fcn) && isequal({varargin{3:end}}, {internal_sdpvarstate.ExtendedMap(i).arg{1:end-1}})
varargout{1} = internal_sdpvarstate.ExtendedMap(i).var;
return
end
i = i + 1;
end
end
% This is the standard operators. INPUTS -> 1 scalar output
y = sdpvar(1,1);
internal_sdpvarstate.ExtendedMap(end+1).fcn = varargin{2};
internal_sdpvarstate.ExtendedMap(end).arg = {varargin{3:end}};
internal_sdpvarstate.ExtendedMap(end).var = y;
internal_sdpvarstate.extVariables = [internal_sdpvarstate.extVariables getvariables(y)];
internal_sdpvarstate.logicVariables = [internal_sdpvarstate.logicVariables getvariables(y)];
varargout{1} = y;
return
case 'setNonHermitianNonCommuting'
internal_sdpvarstate.nonHermitiannonCommutingTable(varargin{2}) = 1;
case 'solver'
if (nargin==2)
if isa(varargin{2},'char')
solver = varargin{2};
prefered_solver = solver;
else
error('Second argument should be a string with solver name');
end
else
if isempty(prefered_solver)
varargout{1}='';
else
varargout{1} = prefered_solver;
end
end
otherwise
if isa(varargin{1},'char')
disp(['The command ''' varargin{1} ''' is not valid in YALMIP.m']);
else
disp('The first argument should be a string');
end
end
function h = create_vecisdouble(x)
B = getbase(x);
h = ~any(B(:,2:end),2);
function h = create_trivial_hash(x)
try
h = sum(getvariables(x)) + sum(sum(getbase(x)));
catch
h = 0;
end
function h = create_trivial_vechash(x)
try
B = getbase(x);
h = sum(B')'+(B | B)*[0;getvariables(x)'];
catch
h = 0;
end
function X = firstSDPVAR(List)
X = [];
for i = 1:length(List)
if isa(List{i},'sdpvar')
X = List{i};
break
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
gams2yalmip.m
|
.m
|
LMI-Matlab-master/yalmip/extras/gams2yalmip.m
| 13,976 |
utf_8
|
4e1639693ca899bd14a7436ffb74839c
|
function varargout = gams2yalmip(fileName,filenameOut);
% GAMS2YALMIP Converts GAMS model to YALMIP
%
% [F,h] = GAMS2YALMIP(gamsfile,yalmipfile) converts the GAMS model in
% the file 'gamsfile' to a YALMIP mpodel
%
% Input
% GAMSFILE : Char with filename for GAMS model
% YALMIPFILE : Char with filename for YALMIP model (optional)
%
% Output
% F : LMI object with constraints (optional)
% h : SDPVAR object with objective (optional)
% Author Based on original implementation by M. Kojima (readGMS.m)
writetofile = (nargout == 0) | (nargin>1);
fileName = [fileName '.gms'];
fileName = strrep(fileName,'.gms.gms','.gms');
% Reading the GAMs file "fileName"
fileIDX = fopen(fileName,'r');
if fileIDX==-1
error('File not found')
end
if writetofile
if nargin == 2
filenameOut = [filenameOut '.m'];
filenameOut = strrep(filenameOut,'.m.m','.m');
else
filenameOut = strrep(fileName,'.gms','.m');
end
fileOUT = fopen(filenameOut,'wb');
if fileOUT==-1
error('Could not create output-file')
end
end
statusSW = 1;
noOfEquations = 0;
pp = 1;
posVarNames = [];
negVarNames = [];
lastline = '';
while statusSW == 1
[statusSW,oneLine] = getOneLine(fileIDX);
if statusSW == 1
lastline = oneLine;
[keyword,oneLine] = strtok(oneLine);
if strcmp('Variables',keyword)
varNames = [];
p = 0;
[varNames,p,moreSW] = getListOfNames(oneLine,varNames,p);
while moreSW == 1
[statusSW,oneLine] = getOneLine(fileIDX);
[varNames,p,moreSW] = getListOfNames(oneLine,varNames,p);
end
noOfVariables = size(varNames,2);
lbd = -inf* ones(1,noOfVariables);
ubd = inf* ones(1,noOfVariables);
fixed = lbd;
elseif strcmp('Positive',keyword)
[keyword,oneLine] = strtok(oneLine);
if strcmp('Variables',keyword)
p = 0;
[posVarNames,p,moreSW] = getListOfNames(oneLine,posVarNames,p);
while moreSW == 1
[statusSW,oneLine] = getOneLine(fileIDX);
[posVarNames,p,moreSW] = getListOfNames(oneLine,posVarNames,p);
end
end
elseif strcmp('Negative',keyword)
[keyword,oneLine] = strtok(oneLine);
if strcmp('Variables',keyword)
p = 0;
[negVarNames,p,moreSW] = getListOfNames(oneLine,negVarNames,p);
while moreSW == 1
[statusSW,oneLine] = getOneLine(fileIDX);
[negVarNames,p,moreSW] = getListOfNames(oneLine,negVarNames,p);
end
end
elseif strcmp('Equations',keyword)
equationNames = [];
p = 0;
[equationNames,p,moreSW] = getListOfNames(oneLine,equationNames,p);
while moreSW == 1
[statusSW,oneLine] = getOneLine(fileIDX);
[equationNames,p,moreSW] = getListOfNames(oneLine,equationNames,p);
end
noOfEquations = size(equationNames,2);
listOfEquations = [];
elseif pp <= noOfEquations
if strcmp(strcat(equationNames{pp},'..'),keyword)
oneLinetmp = oneLine; % to remove blank around *
while ~isempty(strfind(oneLinetmp,' *')) | ~isempty(strfind(oneLinetmp,'* '))
if ~isempty(strfind(oneLinetmp, ' *'))
loca = strfind(oneLinetmp,' *');
loca = loca -1;
oneLinetmp=strcat(oneLinetmp(1:loca),oneLinetmp(loca+2:size(oneLinetmp,2)));
elseif ~isempty(strfind(oneLinetmp, '* '))
loca = strfind(oneLinetmp,'* ');
oneLinetmp=strcat(oneLinetmp(1:loca),oneLinetmp(loca+2:size(oneLinetmp,2)));
end
end
oneLine = oneLinetmp;
listOfEquations{pp} = oneLine;
pp = pp+1;
end
elseif (0 < noOfEquations) & (noOfEquations < pp)
goon = 1;
while goon
[oneVarName,bound] = strtok(keyword,'. ');
for i=1:noOfVariables
if strcmp(oneVarName,varNames{i})
asciiVal = strtok(oneLine,' =;');
if strcmp(bound,'.lo') %| strcmp(bound,'.l')
lbd(1,i) = str2num(asciiVal);
elseif strcmp(bound,'.up') %| strcmp(bound,'.u')
ubd(1,i) = str2num(asciiVal);
elseif strcmp(bound,'.fx')
fixed(1,i) = str2num(asciiVal);
end
end
end
if strfind(oneLine,';')
oneLine = oneLine(min(strfind(oneLine,';'))+1:end);
[keyword,oneLine] = strtok(oneLine);
goon = ~isequal('',keyword);
else
goon = 0;
end
end
end
end
end
% Figure out objective from last line
minimize = 1;
dirstart = strfind(lastline,'minimizing ');
obj = '[]';
if ~isempty(dirstart)
[aux,obj] = strtok(lastline(dirstart:end));
else
dirstart = strfind(lastline,'maximizing ');
if ~isempty(dirstart)
[aux,obj] = strtok(lastline(dirstart:end));
minimize = -1;
else
minimize = 0;
end
end
obj = strrep(strrep(obj,';',''),' ','');
objective_in_equations = 0;
for i = 1:length(listOfEquations)
% If the objective variable is found in several equations, we define it
% as a variable, and add all constraints, instead of assigninging it
% from the typical objvar + f(x) =E= 0 expression
if ~isempty(strfind(listOfEquations{i},obj))
objective_in_equations = objective_in_equations +1;
end
end
if objective_in_equations>1
treat_obj_as_var = 1;
else
treat_obj_as_var = 0;
end
if writetofile
fprintf(fileOUT,['%% Model generated from ' fileName '\n']);
[d] = yalmip('ver');
fprintf(fileOUT,['%% Created ' datestr(now) ' using YALMIP R' d '\n\n']);
fprintf(fileOUT,'%% Setup a clean YALMIP environment \n');
fprintf(fileOUT,'yalmip(''clear'') \n\n');
%fprintf(fileOUT,'%% Define non-standard operators \n');
%fprintf(fileOUT,'sqr = @(x) x.*x;\n\n');
% Define all variables, except objvar
fprintf(fileOUT,'%% Define all variables \n');
end
for i = 1:length(varNames)
eval([varNames{i} ' = sdpvar(1);']);
if writetofile & (~isequal(varNames{i},obj) | treat_obj_as_var)
fprintf(fileOUT,[varNames{i} ' = sdpvar(1);\n']);
end
end
if writetofile
fprintf(fileOUT,'\n');
end
if minimize
if ~treat_obj_as_var
if writetofile & objective_in_equations<=1
fprintf(fileOUT,'%% Define objective function \n');
end
% find objvar + ... == 0
for i = 1:length(listOfEquations)
if strfind(listOfEquations{i},obj)
%objeq = strrep(listOfEquations{i},'=E=','==');
objeqL = listOfEquations{i}(1:strfind( listOfEquations{i},'=E=')-1);
objeqR = listOfEquations{i}(strfind( listOfEquations{i},'=E=')+3:end);
objeqR = strrep(objeqR,';','');
% put objective on left side
if strfind(objeqR,obj)
temp = objeqL;
objeqL = objeqR;
objeqR = objeqL;
end
k = strfind(objeqL,obj);
prevplus = strfind(objeqL(1:k-1),'+');
prevminus = strfind(objeqL(1:k-1),'-');
if isempty(prevplus) & isempty(prevminus)
thesign = 1;
else
prevsign = objeqL(max([prevplus prevminus]));
if isequal(prevsign,'+')
thesign = 1;
else
thesign = -1;
end
end
thesign = thesign*minimize;
obj = [strrep(objeqL,obj,'0') '-( ' objeqR ')'];
obj = strrep(obj,'**','^');
obj = strrep(obj,'sqrt(','sqrtm(');
obj = strrep(obj,'errorf(','erf(');
% obj = strrep(strrep(strrep(obj,'( 0)','0'),'0 -0','0'),'+ 0 ','');
% obj = strrep(strrep(strrep(obj,'( 0)','0'),'0 -0','0'),'+ 0)','');
obj = strrep(obj,' + ','+');
obj = strrep(obj,'+0)',')');
obj = strrep(obj,'POWER','power');
obj(obj==' ') = '';
if writetofile
if thesign == -1
fprintf(fileOUT,['objective = ' obj ';\n']);
else
obj = ['-(' obj ')'];
obj = strrep(obj,'+0)',')');
obj = strrep(obj,'- ','-');
fprintf(fileOUT,['objective = ' obj ';\n']);
end
end
objsdp = (-thesign)*eval(obj);
listOfEquations = {listOfEquations{1:i-1},listOfEquations{i+1:end}};
break
end
end
if writetofile
fprintf(fileOUT,'\n');
end
end
end
% Convert to YALMIP syntax
for i = 1:length(listOfEquations)
listOfEquations{i} = strrep(listOfEquations{i},'=E=','==');
listOfEquations{i} = strrep(listOfEquations{i},'=L=','<=');
listOfEquations{i} = strrep(listOfEquations{i},'=G=','>=');
end
% Add variable bounds
for i = 1:length(varNames)
if any(strcmp(varNames{i},posVarNames))
lbd(i) = 0;
end
if any(strcmp(varNames{i},negVarNames))
ubd(i) = 0;
end
if ~isequal(varNames{i},obj) | treat_obj_as_var
string = '';
if ~isinf(fixed(i))
string = [string num2str(fixed(i)) ' == ' varNames{i}];
elseif ~isinf(lbd(i))
string = [string num2str(lbd(i)) ' <= ' varNames{i}];
if ~isinf(ubd(i))
string = [string ' <= ' num2str(ubd(i))];
end
elseif ~isinf(ubd(i))
string = [string varNames{i} ' <= ' num2str(ubd(i)) ];
end
if ~isequal(string,'')
listOfEquations{end+1} = string;
end
end
end
if length(listOfEquations)>0
if writetofile
fprintf(fileOUT,'%% Define constraints \n');
end
F = ([]);
if writetofile
fprintf(fileOUT,['F = ([]);' '\n']);
end
for i = 1:length(listOfEquations)
listOfEquations{i} = strrep(listOfEquations{i},';','');
% string = ['F = F + (' listOfEquations{i} ',' '''' listOfEquations{i} '''' ');'];
string = ['F = [F, ' strtrim(listOfEquations{i}) '];'];
string = strrep(string,'**','^');
string = strrep(string,'sqrt(','sqrtm(');
string = strrep(string,'errorf(','erf(');
string = strrep(string,'+',' + ');
string = strrep(string,' ','');
string = strrep(string,' ','');
string = strrep(string,' - ','-');
string = strrep(string,'POWER','power');
string = strtrim(string);
string(string==' ') = '';
eval(string);
if writetofile
fprintf(fileOUT,[string '\n']);
end
end
if writetofile
fprintf(fileOUT,'\n');
end
else
F = ([]);
if writetofile
fprintf(fileOUT,'%% Define constraints \n');
end
if writetofile
fprintf(fileOUT,['F = ([]);' '\n']);
end
end
if writetofile
fprintf(fileOUT,'%% Solve problem\n');
if treat_obj_as_var
fprintf(fileOUT,'sol = solvesdp(F,objvar,sdpsettings(''solver'',''bmibnb'',''allownonconvex'',1));\n');
else
fprintf(fileOUT,'sol = solvesdp(F,objective,sdpsettings(''solver'',''bmibnb'',''allownonconvex'',1));\n');
end
fprintf(fileOUT,'mbg_assertfalse(sol.problem)\n');
fprintf(fileOUT,'mbg_asserttolequal(double(objective), , 1e-2);');
fclose(fileOUT);
end
if nargout > 0
varargout{1} = F;
if nargout > 1
varargout{2} = objsdp;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [statusSW,oneLine] = getOneLine(dataFID);
flowCTRL = 0;
oneLine = '';
while (feof(dataFID)==0) & (flowCTRL== 0)
inputLine = fgetl(dataFID);
% inputLine
len = length(inputLine);
if (len > 0) & (inputLine(1)~='*')
p=1;
while (p<=len) & (inputLine(p)==' ')
p = p+1;
end
if (p<=len) % & (inputLine(p) ~= '*')
% oneLine
% inputLine
% Kojima 11/06/04; to meet MATLAB 5.2
if isempty(oneLine)
oneLine = inputLine(p:len);
else
oneLine = strcat(oneLine,inputLine(p:len));
end
% Kojima 11/06/04; to meet MATLAB 5.2
% temp = strfind(inputLine,';');
temp = findstr(inputLine,';');
if isempty(temp) == 0
flowCTRL=1;
end
end
end
end
if flowCTRL==0
oneLine = '';
statusSW = -1;
else
statusSW = 1;
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [varNames,p,moreSW] = getListOfNames(oneLine,varNames,p);
while (length(oneLine) > 0)
[oneName,remLine] = strtok(oneLine,' ,');
if length(oneName) > 0
p = p+1;
varNames{p} = oneName;
end
oneLine = remLine;
end
lenLastVar = length(varNames{p});
if varNames{p}(lenLastVar) == ';'
moreSW = 0;
if lenLastVar == 1
p = p-1;
else
varNames{p} = varNames{p}(1:lenLastVar-1);
end
else
moreSW = 1;
end
return
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdpsettings.m
|
.m
|
LMI-Matlab-master/yalmip/extras/sdpsettings.m
| 30,773 |
utf_8
|
f22c426933af16967501a65e37de3fd2
|
function options = sdpsettings(varargin)
%SDPSETTINGS Create/alter solver options structure.
%
% OPTIONS = SDPSETTINGS with no input arguments returns
% setting structure with default values
%
% OPTIONS = SDPSETTINGS('NAME1',VALUE1,'NAME2',VALUE2,...) creates a
% solution options structure OPTIONS in which the named properties have
% the specified values. Any unspecified properties have default values.
% It is sufficient to type only the leading characters that uniquely
% identify the property. Case is ignored for property names.
%
% OPTIONS = SDPSETTINGS(OLDOPTS,'NAME1',VALUE1,...) alters an existing options
% structure OLDOPTS.
%
% The OPTIONS structure is a simple struct and can thus easily be
% manipulated after its creation
% OPTIONS = sdpsettings;OPTIONS.verbose = 0;
%
%
% SDPSETTINGS PROPERTIES
%
% GENERAL
%
% solver - Specify solver [''|sdpt3|sedumi|sdpa|pensdp|penbmi|csdp|dsdp|maxdet|lmilab|cdd|cplex|xpress|mosek|nag|quadprog|linprog|bnb|bmibnb|kypd|mpt|none ('')]
% verbose - Display-level [0|1|2|...(0)] (0-silent, 1-normal, >1-loud)
% usex0 - Use the current values obtained from double as initial iterate if solver supports that [0|1 (0)]
%
% showprogress - Show progress of YALMIP (suitable for large problems) [0|1 (0)]
% cachesolvers - Check for available solvers only first time solvesdp is called [0|1 (0)]
% warning - Shows a warning if a problems occurs when solving a problem (infeasibility, numerical problem etc.) [0|1 (1)]
% beeponproblem - Beeps when certain warning/error occurs [ integers -2|-1|1|2|3|4|5|6|7|8|9|10|11]
% saveduals - Dual variables are saved in YALMIP [0|1 (1)]
% saveyalmipmodel - Keep all data sent to solver interface [0|1 (0)]
% savesolverinput - Keep all data sent to solver [0|1 (0)]
% savesolveroutput - Keep all data returned from solver [0|1 (0)]
% removeequalities - Let YALMIP remove equality constraints [-1|0|1 (0)] (-1:with double inequalities, 0:don't, 1:by QR decomposition, 2:basis from constraints)
% convertconvexquad - Convert convex quadratic constraints to second order cones [0|1 (1)]
% radius - Add radius constraint on all pimal variables ||x||<radius [double >=0 (inf)]
% shift - Add small perturbation to (try to) enforce strict feasibility [double >=0 (0)]
% relax - Disregard integrality constraint and/or relax nonlinear terms [0 | 1 (both) 2 (relax integrality) 3 (relax nonlinear terms) (0)]
% allowmilp - Allow introduction of binary variables to model nonlinear operators [0 | 1 (0)]
% expand - Expand nonlinear operators [0|1 (1)]. Should always be true except in rare debugging cases.
% plot - Options when plotting sets
%
% SUM-OF-SQUARES
%
% sos, see help solvesos
%
% BRANCH AND BOUND for mixed integer programs
%
% options.bnb, see help bnb
%
% BRANCH AND BOUND for polynomial programs
%
% options.bmibnb, see help bmibnb
%
% EXTERNAL SOLVERS
%
% See solver manuals.
% Print out possible values of properties.
if (nargin == 0) && (nargout == 0)
help sdpsettings
return;
end
if (nargin>0) && isstruct(varargin{1})
options = varargin{1};
Names = recursivefieldnames(options);
paramstart = 2;
else
Names = {};
paramstart = 1;
options = setup_core_options;
Names = appendOptionNames(Names,options);
% Internal solver frameworks
options.bilevel = setup_bilevel_options;
Names = appendOptionNames(Names,options.bilevel,'bilevel');
options.bmibnb = setup_bmibnb_options;
Names = appendOptionNames(Names,options.bmibnb,'bmibnb');
options.bnb = setup_bnb_options;
Names = appendOptionNames(Names,options.bnb,'bnb');
options.cutsdp = setup_cutsdp_options;
Names = appendOptionNames(Names,options.cutsdp,'cutsdp');
options.kkt = setup_kkt_options;
Names = appendOptionNames(Names,options.kkt,'kkt');
options.moment = setup_moment_options;
Names = appendOptionNames(Names,options.moment,'moment');
options.mp = setup_mp_options;
Names = appendOptionNames(Names,options.mp,'mp');
options.mpcvx = setup_mpcvx_options;
Names = appendOptionNames(Names,options.mpcvx,'mpcvx');
options.plot = setup_plot_options;
Names = appendOptionNames(Names,options.plot,'plot');
options.robust = setup_robust_options;
Names = appendOptionNames(Names,options.robust,'robust');
options.sos = setup_sos_options;
Names = appendOptionNames(Names,options.sos,'sos');
% External solvers
options.baron = setup_baron_options;
Names = appendOptionNames(Names,options.baron,'baron');
options.bintprog = setup_bintprog_options;
Names = appendOptionNames(Names,options.bintprog,'bintprog');
options.bonmin = setup_bonmin_options;
Names = appendOptionNames(Names,options.bonmin,'bonmin');
options.cdd = setup_cdd_options;
Names = appendOptionNames(Names,options.cdd,'cdd');
options.cbc = setup_cbc_options;
Names = appendOptionNames(Names,options.cbc,'cbc');
options.clp = setup_clp_options;
Names = appendOptionNames(Names,options.clp,'clp');
options.cplex = setup_cplex_options;
Names = appendOptionNames(Names,options.cplex,'cplex');
options.csdp = setup_csdp_options;
Names = appendOptionNames(Names,options.csdp,'csdp');
options.dsdp = setup_dsdp_options;
Names = appendOptionNames(Names,options.dsdp,'dsdp');
options.ecos = setup_ecos_options;
Names = appendOptionNames(Names,options.ecos,'ecos');
options.filtersd = setup_filtersd_options;
Names = appendOptionNames(Names,options.filtersd,'filtersd');
options.fmincon = setup_fmincon_options;
Names = appendOptionNames(Names,options.fmincon,'fmincon');
options.fminsearch = setup_fminsearch_options;
Names = appendOptionNames(Names,options.fminsearch,'fminsearch');
options.frlib = setup_frlib_options;
Names = appendOptionNames(Names,options.frlib,'frlib');
options.glpk = setup_glpk_options;
Names = appendOptionNames(Names,options.glpk,'glpk');
options.gurobi = setup_gurobi_options;
Names = appendOptionNames(Names,options.gurobi,'gurobi');
options.ipopt = setup_ipopt_options;
Names = appendOptionNames(Names,options.ipopt,'ipopt');
options.intlinprog = setup_intlinprog_options;
Names = appendOptionNames(Names,options.intlinprog,'intlinprog');
options.knitro = setup_knitro_options;
Names = appendOptionNames(Names,options.knitro,'knitro');
options.linprog = setup_linprog_options;
Names = appendOptionNames(Names,options.linprog,'linprog');
options.lmilab = setup_lmilab_options;
Names = appendOptionNames(Names,options.lmilab,'lmilab');
options.lmirank = setup_lmirank_options;
Names = appendOptionNames(Names,options.lmirank,'lmirank');
options.logdetppa = setup_logdetppa_options;
Names = appendOptionNames(Names,options.logdetppa,'logdetppa');
options.lpsolve = setup_lpsolve_options;
Names = appendOptionNames(Names,options.lpsolve,'lpsolve');
options.lsqnonneg = setup_lsqnonneg_options;
Names = appendOptionNames(Names,options.lsqnonneg,'lsqnonneg');
options.lsqlin = setup_lsqlin_options;
Names = appendOptionNames(Names,options.lsqlin,'lsqlin');
options.kypd = setup_kypd_options;
Names = appendOptionNames(Names,options.kypd,'kypd');
options.nag = setup_nag_options;
Names = appendOptionNames(Names,options.nag,'nag');
options.mosek = setup_mosek_options;
Names = appendOptionNames(Names,options.mosek,'mosek');
options.nomad = setup_nomad_options;
Names = appendOptionNames(Names,options.nomad,'nomad');
options.ooqp = setup_ooqp_options;
Names = appendOptionNames(Names,options.ooqp,'ooqp');
options.penbmi = setup_penbmi_options;
Names = appendOptionNames(Names,options.penbmi,'penbmi');
options.penlab = setup_penlab_options;
Names = appendOptionNames(Names,options.penlab,'penlab');
options.pensdp = setup_pensdp_options;
Names = appendOptionNames(Names,options.pensdp,'pensdp');
options.qpoases = setup_qpoases_options;
Names = appendOptionNames(Names,options.qpoases,'qpoases');
options.qsopt = setup_qsopt_options;
Names = appendOptionNames(Names,options.qsopt,'qsopt');
options.quadprog = setup_quadprog_options;
Names = appendOptionNames(Names,options.quadprog,'quadprog');
options.quadprogbb = setup_quadprogbb_options;
Names = appendOptionNames(Names,options.quadprogbb,'quadprogbb');
options.scip = setup_scip_options;
Names = appendOptionNames(Names,options.scip,'scip');
options.scs = setup_scs_options;
Names = appendOptionNames(Names,options.scs,'scs');
options.sdpa = setup_sdpa_options;
Names = appendOptionNames(Names,options.sdpa,'sdpa');
options.sdplr = setup_sdplr_options;
Names = appendOptionNames(Names,options.sdplr,'sdplr');
options.sdpt3 = setup_sdpt3_options;
Names = appendOptionNames(Names,options.sdpt3,'sdpt3');
options.sdpnal = setup_sdpnal_options;
Names = appendOptionNames(Names,options.sdpnal,'sdpnal');
options.sedumi = setup_sedumi_options;
Names = appendOptionNames(Names,options.sedumi,'sedumi');
options.sparsepop = setup_sparsepop_options;
Names = appendOptionNames(Names,options.sparsepop,'sparsepop');
options.sparsecolo = setup_sparsecolo_options;
Names = appendOptionNames(Names,options.sparsecolo,'sparsecolo');
options.vsdp = setup_vsdp_options;
Names = appendOptionNames(Names,options.vsdp,'vsdp');
options.xpress = setup_xpress_options;
Names = appendOptionNames(Names,options.xpress,'xpress');
end
names = lower(Names);
i = paramstart;
% A finite state machine to parse name-value pairs.
if rem(nargin-i+1,2) ~= 0
error('Arguments must occur in name-value pairs.');
end
expectval = 0; % start expecting a name, not a value
while i <= nargin
arg = varargin{i};
if ~expectval
if ~ischar(arg)
error(sprintf('Expected argument %d to be a string property name.', i));
end
lowArg = lower(arg);
j = strmatch(lowArg,names);
if isempty(j) % if no matches
error(sprintf('Unrecognized property name ''%s''.', arg));
elseif length(j) > 1 % if more than one match
% Check for any exact matches (in case any names are subsets of others)
k = strmatch(lowArg,names,'exact');
if (length(k) == 1)
j = k;
else
msg = sprintf('Ambiguous property name ''%s'' ', arg);
msg = [msg '(' deblank(Names{j(1)})];
for k = j(2:length(j))'
msg = [msg ', ' deblank(Names{k})];
end
msg = sprintf('%s).', msg);
error(msg);
end
end
expectval = 1; % we expect a value next
else
eval(['options.' Names{j} '= arg;']);
expectval = 0;
end
i = i + 1;
end
if expectval
error(sprintf('Expected value for property ''%s''.', arg));
end
function [solverops] = trytoset(solver)
try
try
evalc(['solverops = ' solver '(''defaults'');']);
catch
solverops = optimset(solver);
end
catch
solverops = optimset;
end
% if isequal(solver, 'quadprog') && isfield(solverops, 'Algorithm') && ~isempty(solverops.Algorithm)
% solverops.Algorithm = 'active-set';
% end
%
% if any(strcmp(solvernames,'LargeScale'))
% if isequal(solver, 'quadprog')
% solverops.LargeScale = 'off';
% end
% else
% solvernames{end+1} = 'LargeScale';
% solverops.LargeScale = 'off';
% end
function cNames = recursivefieldnames(options,append);
if nargin == 1
append = '';
end
cNames = fieldnames(options);
for i = 1:length(cNames)
eval(['temporaryOptions = options.' cNames{i} ';']);
if isa(temporaryOptions,'struct')
cNames = [cNames;recursivefieldnames(temporaryOptions,[cNames{i}])];
end
end
for i = 1:length(cNames)
if nargin==1
else
cNames{i} = [append '.' cNames{i}];
end
end
function Names = appendOptionNames(Names,options,solver)
if ~isempty(options)
if ~isa(options,'struct')
% Hide warning
evalc(['options = struct(options);']);
end
cNames = recursivefieldnames(options);
if nargin == 3
prefix = [solver '.'];
else
prefix = '';
end
for i = 1:length(cNames)
Names{end+1} = [prefix cNames{i}];
end
end
function options = setup_core_options
options.solver = '';
options.verbose = 1;
options.debug = 0;
options.usex0 = 0;
options.warning = 1;
options.cachesolvers = 0;
options.showprogress = 0;
options.saveduals = 1;
options.removeequalities = 0;
options.savesolveroutput = 0;
options.savesolverinput = 0;
options.saveyalmipmodel = 0;
options.convertconvexquad = 1;
options.assertgpnonnegativity = 1;
options.thisisnotagp = 0;
options.radius = inf;
options.relax = 0;
options.dualize = 0;
options.usex0 = 0;
options.savedebug = 0;
options.debug = 0;
options.expand = 1;
options.allowmilp = 1;
options.allownonconvex = 1;
options.shift = 0;
options.dimacs = 0;
options.beeponproblem = [-5 -4 -3 -2 -1];
function bilevel = setup_bilevel_options
bilevel.algorithm = 'internal';
bilevel.maxiter = 1e4;
bilevel.outersolver = '';
bilevel.innersolver = '';
bilevel.rootcuts = 0;
bilevel.solvefrp = 0;
bilevel.relgaptol = 1e-3;
bilevel.feastol = 1e-6;
bilevel.compslacktol = 1e-8;
function bmibnb = setup_bmibnb_options
bmibnb.branchmethod = 'best';
bmibnb.branchrule = 'omega';
bmibnb.cut.multipliedequality = 0;
bmibnb.cut.convexity = 0;
bmibnb.cut.evalvariable = 1;
bmibnb.cut.bilinear = 1;
bmibnb.cut.monomial = 1;
bmibnb.cut.complementarity = 1;
bmibnb.sdpcuts = 0;
bmibnb.lpreduce = 1;
bmibnb.lowrank = 0;
bmibnb.diagonalize = 1;
bmibnb.lowersolver = '';
bmibnb.uppersolver = '';
bmibnb.lpsolver = '';
bmibnb.target = -inf;
bmibnb.lowertarget = inf;
bmibnb.vartol = 1e-3;
bmibnb.relgaptol = 1e-2;
bmibnb.absgaptol = 1e-2;
bmibnb.pdtol = -1e-6;
bmibnb.eqtol = 1e-6;
bmibnb.maxiter = 100;
bmibnb.maxtime = 3600;
bmibnb.roottight = 1;
bmibnb.numglobal = inf;
bmibnb.localstart = 'relaxed';
bmibnb.presolvescheme = [];
bmibnb.strengthscheme = [1 2 1 3 1 4 1 6 1 5 1 4 1 6 1 4 1];
function bnb = setup_bnb_options
bnb.branchrule = 'max';
bnb.method = 'depthbest';
bnb.verbose = 1;
bnb.solver = '';
bnb.uppersolver = 'rounder';
bnb.presolve = 0;
bnb.inttol = 1e-4;
bnb.feastol = 1e-7;
bnb.gaptol = 1e-4;
bnb.weight = [];
bnb.nodetight = 0;
bnb.nodefix = 0;
bnb.ineq2eq = 0;
bnb.plotbounds = 0;
bnb.rounding = {'ceil','floor','round','shifted round','fix'};
bnb.round = 1;
bnb.maxiter = 300;
bnb.prunetol = 1e-4;
bnb.multiple = 0;
bnb.profile = 0;
function cutsdp = setup_cutsdp_options
cutsdp.solver = '';
cutsdp.maxiter = 100;
cutsdp.cutlimit = inf;
cutsdp.feastol = -1e-8;
cutsdp.recoverdual = 0;
cutsdp.variablebound = inf;
cutsdp.nodefix = 0;
cutsdp.nodetight = 0;
cutsdp.activationcut = 1;
cutsdp.maxprojections = 3;
cutsdp.projectionthreshold = .1;
cutsdp.switchtosparse = 1000;
cutsdp.resolver = [];
function frlib = setup_frlib_options
frlib.approximation = 'd';
frlib.reduce = 'auto';
frlib.solver = '';
frlib.solverPreProcess = '';
frlib.useQR = 0;
frlib.removeDualEq = 1;
function kkt = setup_kkt_options
kkt.dualbounds = 1;
kkt.dualpresolve.passes = 1;
kkt.dualpresolve.lplift = 1;
kkt.minnormdual = 0;
kkt.licqcut = 0;
function moment = setup_moment_options
moment.order = [];
moment.blockdiag = 0;
moment.solver = '';
moment.refine = 0;
moment.extractrank = 0;
moment.rceftol = -1;
function mpcvx = setup_mpcvx_options
mpcvx.solver = '';
mpcvx.absgaptol = 0.25;
mpcvx.relgaptol = 0.01;
mpcvx.plot = 0;
mpcvx.rays = 'n*20';
function mp = setup_mp_options
mp.algorithm = 1;
mp.simplify = 0;
mp.presolve = 0;
mp.unbounded = 0;
function plot = setup_plot_options
plot.edgecolor = 'k';
plot.wirestyle = '-';
plot.wirecolor = 'k';
plot.linewidth = 0.5;
plot.shade = 1;
plot.waitbar = 1;
function robust = setup_robust_options
robust.lplp = 'enumeration';
robust.coniconic.tau_degree = 2;
robust.coniconic.gamma_degree = 0;
robust.coniconic.Z_degree = 2;
robust.auxreduce = 'none';
robust.reducedual = 0;
robust.reducesemiexplicit = 0;
robust.polya = nan;
function sos = setup_sos_options
sos.model = 0;
sos.newton = 1;
sos.congruence = 2;
sos.scale = 1;
sos.numblkdg = 0;
sos.postprocess = 0;
sos.csp = 0;
sos.extlp = 1;
sos.impsparse = 0;
sos.sparsetol = 1e-5;
sos.inconsistent = 0;
sos.clean = eps;
sos.savedecomposition = 1;
sos.traceobj = 0;
sos.reuse = 1;
function bpmpd = setup_bpmpd_options
try
bpmpd.opts = bpopt;
catch
bpmpd.opts =[];
end
function cbc = setup_cbc_options
try
cbc = cbcset;
catch
cbc.tolint = 1e-4;
cbc.maxiter = 10000;
cbc.maxnodes = 100000;
end
function cdd = setup_cdd_options
cdd.method = 'criss-cross';
function clp = setup_clp_options
try
clp = clpset;
catch
clp.solver = 1;
clp.maxnumiterations = 99999999;
clp.maxnumseconds = 3600;
clp.primaltolerance = 1e-7;
clp.dualtolerance = 1e-7;
clp.primalpivot = 1;
clp.dualpivot = 1;
end
function cplex = setup_cplex_options
try
cplex = cplexoptimset('cplex');
cplex.output.clonelog = 0;
catch
cplex.presol = 1;
cplex.niter = 1;
cplex.epgap = 1e-4;
cplex.epagap = 1e-6;
cplex.relobjdif = 0.0;
cplex.objdif = 0.0;
cplex.tilim = 1e75;
cplex.logfile = 0;
cplex.param.double = [];
cplex.param.int = [];
end
function ecos = setup_ecos_options
try
ecos = ecosoptimset;
ecos.mi_maxiter = 1000;
ecos.mi_abs_eps = 1e-6;
ecos.mi_rel_eps = 1e-3;
catch
ecos = [];
end
function filtersd = setup_filtersd_options
filtersd.maxiter = 1500;
filtersd.maxtime = 1000;
filtersd.maxfeval = 10000;
function glpk = setup_glpk_options
glpk.lpsolver = 1;
glpk.scale = 1;
glpk.dual = 0;
glpk.price = 1;
glpk.relax = 0.07;
glpk.tolbnd = 1e-7;
glpk.toldj = 1e-7;
glpk.tolpiv = 1e-9;
glpk.round = 0;
glpk.objll = -1e12;
glpk.objul = 1e12;
glpk.itlim = 1e4;
glpk.tmlim = -1;
glpk.branch = 2;
glpk.btrack = 2;
glpk.tolint = 1e-6;
glpk.tolobj = 1e-7;
glpk.presol = 1;
glpk.save = 0;
function gurobi = setup_gurobi_options
gurobi.BarIterLimit = inf;
gurobi.Cutoff = inf;
gurobi.IterationLimit = inf;
gurobi.NodeLimit = inf;
gurobi.SolutionLimit = inf;
gurobi.TimeLimit = inf;
gurobi.BarConvTol = 1e-8;
gurobi.BarQCPConvTol = 1e-6;
gurobi.FeasibilityTol = 1e-6;
gurobi.IntFeasTol = 1e-6;
gurobi.MarkowitzTol = 0.0078125;
gurobi.MIPGap = 1e-4;
gurobi.MIPGapAbs = 1e-10;
gurobi.OptimalityTol = 1e-6;
gurobi.PSDTol = 1e-6;
gurobi.InfUnbdInfo = 0;
gurobi.NormAdjust = -1;
gurobi.ObjScale = 0;
gurobi.PerturbValue = 0.0002;
gurobi.Quad = -1;
gurobi.ScaleFlag = 1;
gurobi.Sifting = -1;
gurobi.SiftMethod = -1;
gurobi.SimplexPricing = -1;
gurobi.BarCorrectors = -1;
gurobi.BarHomogeneous = -1;
gurobi.BarOrder = -1;
gurobi.Crossover = -1;
gurobi.CrossoverBasis = 0;
gurobi.QCPDual = 0;
gurobi.BranchDir = 0;
gurobi.ConcurrentMIP = 1;
gurobi.Heuristics = 0.05;
gurobi.ImproveStartGap = 0;
gurobi.ImproveStartNodes = inf;
gurobi.ImproveStartTime = inf;
gurobi.MinRelNodes = 0;
gurobi.MIPFocus = 0;
gurobi.MIQCPMethod = -1;
gurobi.NodefileDir = '.';
gurobi.NodefileStart = inf;
gurobi.NodeMethod = 1;
gurobi.PumpPasses = 0;
gurobi.RINS = -1;
gurobi.SolutionNumber = 0;
gurobi.SubMIPNodes = 500;
gurobi.Symmetry = -1;
gurobi.VarBranch = -1;
gurobi.ZeroObjNodes = 0;
gurobi.TuneOutput = 2;
gurobi.TuneResults = -1;
gurobi.TuneTimeLimit = -1;
gurobi.TuneTrials = 2;
gurobi.Cuts = -1;
gurobi.CliqueCuts = -1;
gurobi.CoverCuts = -1;
gurobi.FlowCoverCuts = -1;
gurobi.FlowPathCuts = -1;
gurobi.GUBCoverCuts = -1;
gurobi.ImpliedCuts = -1;
gurobi.MIPSepCuts = -1;
gurobi.MIRCuts = -1;
gurobi.ModKCuts = -1;
gurobi.NetworkCuts = -1;
gurobi.SubMIPCuts = -1;
gurobi.ZeroHalfCuts = -1;
gurobi.CutAggPasses = -1;
gurobi.CutPasses = -1;
gurobi.GomoryPasses = -1;
gurobi.AggFill = 10;
gurobi.Aggregate = 1;
gurobi.DisplayInterval = 5;
gurobi.DualReductions = 1;
gurobi.FeasRelaxBigM = 1e6;
gurobi.IISMethod = -1;
gurobi.LogFile = '';
gurobi.Method = -1;
gurobi.NumericFocus = 0;
gurobi.PreCrush = 0;
gurobi.PreDepRow = -1;
gurobi.PreDual = -1;
gurobi.PreMIQPMethod = -1;
gurobi.PreQLinearize = -1;
gurobi.PrePasses = -1;
gurobi.Presolve = -1;
gurobi.PreSparsify = 0;
gurobi.ResultFile = '';
gurobi.Threads = 0;
function intlinprog = setup_intlinprog_options
try
intlinprog = optimoptions('intlinprog');
% if ~isa(intlinprog,'struct');
% evalc(['intlinprog = struct(intlinprog);']);
% end
catch
intlinprog = [];
end
function kypd = setup_kypd_options
kypd.solver = '';
kypd.lyapunovsolver = 'schur';
kypd.reduce = 0;
kypd.transform = 0;
kypd.rho = 1;
kypd.tol = 1e-8;
kypd.lowrank = 0;
function lmilab = setup_lmilab_options
lmilab.reltol = 1e-3;
lmilab.maxiter = 100;
lmilab.feasradius = 1e9;
lmilab.L = 10;
function lmirank = setup_lmirank_options
lmirank.solver = '';
lmirank.maxiter = 100;
lmirank.maxiter = 1000;
lmirank.eps = 1e-9;
lmirank.itermod = 1;
function logdetppa = setup_logdetppa_options
logdetppa.tol = 1e-6;
logdetppa.sig = 10;
logdetppa.maxiter = 100;
logdetppa.maxitersub = 30;
logdetppa.precond = 1;
logdetppa.maxitpsqmr = 100;
logdetppa.stagnate_check_psqmr = 0;
logdetppa.scale_data = 2;
logdetppa.plotyes = 0;
logdetppa.use_proximal = 1;
logdetppa.switch_alt_newton_tol = 1e-2;
function lpsolve = setup_lpsolve_options
lpsolve.scalemode = 0;
function nag = setup_nag_options
nag.featol = sqrt(eps);
nag.itmax = 500;
nag.bigbnd = 1e10;
nag.orthog = 0;
function penbmi = setup_penbmi_options
penbmi.DEF = 1;
penbmi.PBM_MAX_ITER = 50;
penbmi.UM_MAX_ITER = 100;
penbmi.OUTPUT = 1;
penbmi.DENSE = 1; %!0
penbmi.LS = 0;
penbmi.XOUT = 0;
penbmi.UOUT = 0;
penbmi.NWT_SYS_MODE = 0;
penbmi.PREC_TYPE = 0;
penbmi.DIMACS = 0;
penbmi.TR_MODE = 0;
penbmi.U0 = 1;
penbmi.MU = 0.7;
penbmi.MU2 = 0.5; %!0.1
penbmi.PRECISION = 1e-6; %!1e-7
penbmi.P_EPS = 1e-4; %!1e-6
penbmi.UMIN = 1e-14;
penbmi.ALPHA = 1e-2;
penbmi.P0 = 0.1; %!0.01
penbmi.PEN_UP = 0.5; %!0
penbmi.ALPHA_UP = 1.0;
penbmi.PRECISION_2 = 1e-6; %!1e-7
penbmi.CG_TOL_DIR = 5e-2;
function ops = setup_penlab_options
try
ops = penlab.defopts(1);
catch
ops = [];
end
function pennlp = setup_pennlp_options
pennlp.maxit = 100;
pennlp.nwtiters = 100;
pennlp.hessianmode = 0;
pennlp.autoscale = 1;
pennlp.convex = 0;
pennlp.eqltymode = 1;
pennlp.ignoreinit = 0;
pennlp.ncmode = 0;
pennlp.nwtstopcrit = 2;
pennlp.penalty = 0;
pennlp.nwtmode = 0;
pennlp.prec = 0;
pennlp.cmaxnzs =-1;
pennlp.autoini = 1;
pennlp.ipenup = 1;
pennlp.precision = 1e-7;
pennlp.uinit = 1;
pennlp.pinit = 1;
pennlp.alpha = 0.01;
pennlp.mu = 0.5;
pennlp.dpenup = 0.1;
pennlp.peps = 1e-8;
pennlp.umin = 1e-12;
pennlp.preckkt = 1e-1;
pennlp.cgtolmin = 5e-2;
pennlp.cgtolup = 1;
pennlp.uinitbox = 1;
pennlp.uinitnc = 1;
function pensdp = setup_pensdp_options
pensdp.DEF = 1;
pensdp.PBM_MAX_ITER = 50;
pensdp.UM_MAX_ITER = 100;
pensdp.OUTPUT = 1;
pensdp.DENSE = 0;
pensdp.LS = 0;
pensdp.XOUT = 0;
pensdp.UOUT = 0;
pensdp.U0 = 1;
pensdp.MU = 0.7;
pensdp.MU2 = 0.1;
pensdp.PBM_EPS = 1e-7;
pensdp.P_EPS = 1e-6;
pensdp.UMIN = 1e-14;
pensdp.ALPHA = 1e-2;
pensdp.P0 = 0.9;
function sparsecolo = setup_sparsecolo_options
sparsecolo.SDPsolver = '';
sparsecolo.domain = 2;
sparsecolo.range = 1;
sparsecolo.EQorLMI = 2;
function sparsepop = setup_sparsepop_options
sparsepop.relaxOrder = 1;
sparsepop.sparseSW = 1;
sparsepop.multiCliquesFactor = 1;
sparsepop.scalingSW = 1;
sparsepop.boundSW = 2;
sparsepop.eqTolerance = 0;
sparsepop.perturbation = 0;
sparsepop.reduceMomentMatSW = 1;
sparsepop.complementaritySW = 0;
sparsepop.reduceAMatSW = 1;
sparsepop.SDPsolver = 'sedumi';
sparsepop.SDPsolverSW = 1;
sparsepop.SDPsolverEpsilon = 1.0000e-009;
sparsepop.SDPsolverOutFile = 0;
sparsepop.sdpaDataFile = '';
sparsepop.matFile = '';
sparsepop.POPsolver = '';
sparsepop.detailedInfFile = '';
sparsepop.printFileName = 1;
sparsepop.errorBdIdx = '';
sparsepop.fValueUbd = '';
sparsepop.symbolicMath = 1;
sparsepop.mex = 0;
function sdpnal = setup_sdpnal_options
sdpnal.tol = 1e-6;
sdpnal.sigma = 10;
sdpnal.maxiter = 100;
sdpnal.maxitersub = 20;
sdpnal.AAtsolve = 2;
sdpnal.precond = 1;
sdpnal.maxitpsqmr = 100;
sdpnal.stagnate_check_psqmr = 0;
sdpnal.scale_data = 2;
sdpnal.plotyes = 0;
sdpnal.proximal = 1;
function sedumi = setup_sedumi_options
sedumi.alg = 2;
sedumi.beta = 0.5;
sedumi.theta = 0.25;
sedumi.free = 1;
sedumi.sdp = 0;
sedumi.stepdif= 0;
sedumi.w = [1 1];
sedumi.mu = 1.0;
sedumi.eps = 1e-9;
sedumi.bigeps = 1e-3;
sedumi.maxiter= 150;
sedumi.vplot = 0;
sedumi.stopat = -1;
sedumi.denq = 0.75;
sedumi.denf = 10;
sedumi.numtol = 5e-7;
sedumi.bignumtol = 0.9;
sedumi.numlvlv = 0;
sedumi.chol.skip = 1;
sedumi.chol.canceltol = 1e-12;
sedumi.chol.maxu = 5e5;
sedumi.chol.abstol = 1e-20;
sedumi.chol.maxuden= 5e2;
sedumi.cg.maxiter = 25;
sedumi.cg.restol = 5e-3;
sedumi.cg.refine = 1;
sedumi.cg.stagtol = 5e-14;
sedumi.cg.qprec = 0;
sedumi.maxradius = inf;
function sdpt3 = setup_sdpt3_options
sdpt3.vers = 1;
sdpt3.gam = 0;
sdpt3.predcorr = 1;
sdpt3.expon = 1;
sdpt3.gaptol = 1e-7;
sdpt3.inftol = 1e-7;
sdpt3.steptol = 1e-6;
sdpt3.maxit = 50;
sdpt3.stoplevel= 1;
sdpt3.sw2PC_tol = inf;
sdpt3.use_corrprim = 0;
sdpt3.printyes = 1;
sdpt3.scale_data = 0;
sdpt3.schurfun = [];
sdpt3.schurfun_parms = [];
sdpt3.randnstate = 0;
sdpt3.spdensity = 0.5;
sdpt3.rmdepconstr = 0;
sdpt3.CACHE_SIZE = 256;
sdpt3.LOOP_LEVEL = 8;
sdpt3.cachesize = 256;
sdpt3.linsys_options = 'raugmatsys';
sdpt3.smallblkdim = 30;
function quadprogbb = setup_quadprogbb_options
quadprogbb.max_time = 86400;
quadprogbb.fathom_tol = 1e-6;
quadprogbb.tol = 1e-8;
quadprogbb.use_quadprog = 1;
quadprogbb.use_single_processor = 0;
quadprogbb.max_time = inf;
function qpip = setup_qpip_options
qpip.mu = 0.0;
qpip.method = 1;
function qsopt = setup_qsopt_options
try
qsopt = optiset('solver','qsopt');
catch
qsopt.dual = 0;
qsopt.primalprice = 1;
qsopt.dualprice = 6;
qsopt.scale = 1;
qsopt.maxiter = 300000;
qsopt.maxtime = 10000.0;
end
function sdpa = setup_sdpa_options
sdpa.maxIteration = 100 ;
sdpa.epsilonStar = 1.0E-7;
sdpa.lambdaStar = 1.0E2 ;
sdpa.omegaStar = 2.0 ;
sdpa.lowerBound = -1.0E5 ;
sdpa.upperBound = 1.0E5 ;
sdpa.betaStar = 0.1 ;
sdpa.betaBar = 0.2 ;
sdpa.gammaStar = 0.9 ;
sdpa.epsilonDash = 1.0E-7 ;
sdpa.isSymmetric = 0 ;
function sdplr = setup_sdplr_options
sdplr.feastol = 1e-5;
sdplr.centol = 1e-1;
sdplr.dir = 1;
sdplr.penfac = 2;
sdplr.reduce = 0;
sdplr.limit = 3600;
sdplr.soln_factored = 0;
sdplr.maxrank = 0;
function vsdp = setup_vsdp_options
vsdp.solver = '';
vsdp.verifiedupper = 0;
vsdp.verifiedlower = 1;
vsdp.prove_D_infeasible = 0;
vsdp.prove_P_infeasible = 0;
function ipopt = setup_ipopt_options
try
ipopt = ipoptset;
ipopt.hessian_approximation = 'limited-memory';
ipopt.max_iter = 1500;
ipopt.max_cpu_time = 1000;
ipopt.tol = 1e-7;
catch
ipopt.mu_strategy = 'adaptive';
ipopt.tol = 1e-7;
ipopt.hessian_approximation = 'limited-memory';
end
function bonmin = setup_bonmin_options
try
bonmin = bonminset([],'noIpopt');
bonmin = rmfield(bonmin,'var_lin');
bonmin = rmfield(bonmin,'cons_lin');
catch
bonmin =[];
end
function nomad = setup_nomad_options
try
nomad = nomadset;
catch
nomad =[];
end
function ooqp = setup_ooqp_options
try
ooqp = ooqpset;
catch
ooqp = [];
end
function xpress = setup_xpress_options
try
xpress = xprsoptimset;
cNames = recursivefieldnames(xpress);
for i = 1:length(cNames)
xpress = setfield(xpress,cNames{i},[]);
end
catch
xpress =[];
end
function qpoases = setup_qpoases_options
try
qpoases = qpOASES_options;
catch
qpoases =[];
end
function baron = setup_baron_options
try
baron = baronset;
catch
baron = [];
end
function knitro = setup_knitro_options
try
knitro = optimset;
knitro.optionsfile = '';
catch
knitro.optionsfile = '';
end
function csdp = setup_csdp_options
try
% OPTI Toolbox interface
csdp = csdpset();
catch
csdp.axtol = 1e-8;
csdp.atytol = 1e-8;
csdp.objtol = 1e-8;
csdp.pinftol = 1e8;
csdp.dinftol = 1e8;
csdp.maxiter = 100;
csdp.minstepfrac = 0.90;
csdp.maxstepfrac = 0.97;
csdp.minstepp = 1e-8;
csdp.minstepd = 1e-8;
csdp.usexzgap = 1;
csdp.tweakgap = 0;
end
function scip = setup_scip_options
try
scip = optiset;
catch
scip = [];
end
function scs = setup_scs_options
scs.alpha = 1.5;
scs.rho_x = 1e-3;
scs.max_iters = 2500;
scs.eps = 1e-3;
scs.normalize = 1;
scs.scale = 5;
scs.cg_rate = 2;
scs.eliminateequalities = 0;
function dsdp = setup_dsdp_options
try
% OPTI Toolbox interface
dsdp = dsdpset();
catch
% Options for DSDP 5.6 classical interface
dsdp.r0 = -1;
dsdp.zbar = 0;
dsdp.penalty = 1e8;
dsdp.boundy = 1e6;
dsdp.gaptol = 1e-7;
dsdp.maxit = 500;
dsdp.steptol=5e-2;
dsdp.inftol=1e-8;
dsdp.dual_bound = 1e20;
dsdp.rho = 3;
dsdp.dynamicrho = 1;
dsdp.bigM = 0;
dsdp.mu0 = -1;
dsdp.reuse = 4;
dsdp.lp_barrier = 1;
end
function mosek = setup_mosek_options
try
evalc('[r,res]=mosekopt(''param'');');
mosek = res.param;
catch
mosek.param = [];
end
function quadprog = setup_quadprog_options
try
quadprog = trytoset('quadprog');
catch
quadprog.param = [];
end
function linprog = setup_linprog_options
try
linprog = trytoset('linprog');
catch
linprog.param = [];
end
function bintprog = setup_bintprog_options
try
bintprog = trytoset('bintprog');
catch
bintprog.param = [];
end
function fmincon = setup_fmincon_options
try
fmincon = trytoset('fmincon');
catch
fmincon.param = [];
end
function fminsearch = setup_fminsearch_options
try
fminsearch = trytoset('fminsearch');
catch
fminfminsearch.param = [];
end
function lsqnonneg = setup_lsqnonneg_options
try
lsqnonneg = trytoset('lsqnonneg');
catch
lsqnonneg.param = [];
end
function lsqlin = setup_lsqlin_options
try
lsqlin = trytoset('lsqlin');
catch
lsqlin.param = [];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
findulb.m
|
.m
|
LMI-Matlab-master/yalmip/extras/findulb.m
| 1,661 |
utf_8
|
01608ade93f5720dd1ed28fbb581df02
|
function [lb,ub,cand_rows_eq,cand_rows_lp] = findulb(F_struc,K,lb,ub)
%FINDULB Internal function to extract upper and lower variable bounds
n = size(F_struc,2)-1;
if nargin < 3
lb = -inf*ones(n,1);
ub = inf*ones(n,1);
end
cand_rows_eq = [];
cand_rows_lp = [];
ub2 = ub;
lb2 = lb;
if (K.f ~=0)
A = -F_struc(1:K.f,2:end);
b = F_struc(1:K.f,1);
n = size(F_struc,2)-1;
cand_rows_eq = find(sum(A~=0,2)==1);
for i = 1:length(cand_rows_eq)
j = find(A(cand_rows_eq(i),:));
ub(j)=min(ub(j),b(cand_rows_eq(i))/A(cand_rows_eq(i),j));
lb(j)=max(lb(j),b(cand_rows_eq(i))/A(cand_rows_eq(i),j));
end
end
if (K.l ~=0)
A = -F_struc(K.f+1:K.f+K.l,2:end);
b = F_struc(K.f+1:K.f+K.l,1);
[lb,ub,cand_rows_lp] = localBoundsFromInequality(A,b,lb,ub);
end
if isfield(K,'q') && nnz(K.q) > 0
% Pick out the c'x+d termn in cone(Ax+b,cx+d)
top = cumsum([1 K.q(1:end-1)]);
A = -F_struc(K.f+K.l+top,2:end);
b = F_struc(K.f+K.l+top,1);
[lb,ub] = localBoundsFromInequality(A,b,lb,ub);
end
function [lb,ub,cand_rows_lp] = localBoundsFromInequality(A,b,lb,ub);
n = size(A,2);
cand_rows_lp = find(sum(A~=0,2)==1);
if ~isempty(cand_rows_lp)
[ii,jj,kk] = find(A(cand_rows_lp,:));
s_pos = find(kk>0);
s_neg = find(kk<=0);
if ~isempty(s_pos)
for s = 1:length(s_pos)
ub(jj(s_pos(s)),1) = full(min(ub(jj(s_pos(s))),b(cand_rows_lp(ii(s_pos(s))))./kk(s_pos(s))));
end
end
if ~isempty(s_neg)
for s = 1:length(s_neg)
lb(jj(s_neg(s)),1) = full(max(lb(jj(s_neg(s))),b(cand_rows_lp(ii(s_neg(s))))./kk(s_neg(s))));
end
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
optimizer.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@optimizer/optimizer.m
| 13,039 |
utf_8
|
6c454ee18c6c1138dc70087dd5296087
|
function sys = optimizer(Constraints,Objective,options,x,u)
%OPTIMIZER Container for optimization problem
%
% OPT = OPTIMIZER(Constraints,Objective,options,x,u) exports an object that
% contains precompiled numerical data to be solved for varying arguments
% x, returning the optimal value of the expression u.
%
% OPTIMIZER typically only works efficiently if the varying data x enters
% the optmization problem affinely. If not, the precompiled problems will
% be nonconvex, despite the problem being simple for a fixed value of the
% parameter (see Wiki for beta support of a much more general optimizer)
%
% In principle, if an optimization problem has a parameter x, and we
% repeatedly want to solve the problem for varying x to compute a
% variable u, we can, instead of repeatedly constructing optimization
% problems for fixed values of x, introduce a symbolic x, and then
% simply add an equality
% solvesdp([Constraints,x == value],Objective);
% uopt = double(u)
% There will still be overhead from the SOLVESDP call, so we can
% precompile the whole structure, and let YALMIP handle the addition of
% the equality constraint for the fixed value, and automatically extract
% the solution variables we are interested in
% OPT = optimizer(Constraints,Objective,options,x,u)
% uopt1 = OPT{value1}
% uopt2 = OPT{value2}
% uopt3 = OPT{value3}
%
% By default, display is turned off (since optimizer is used in
% situations where many problems are solved repeatedly. To turn on
% display, set the verbose option in sdpsetting to 2.
%
% Example
%
% The following problem creates an LP with varying upper and lower
% bounds on the decision variable.
%
% The optimizing argument is obtained by indexing (with {}) the optimizer
% object with the point of interest. The argument should be a column
% vector (if the argument has a width larger than 1, YALMIP assumes that
% the optimal solution should be computed in several points)
%
% A = randn(10,3);
% b = rand(10,1)*19;
% c = randn(3,1);
%
% z = sdpvar(3,1);
% sdpvar UB LB
%
% Constraints = [A*z <= b, LB <= z <= UB];
% Objective = c'*z
% % We want the optimal z as a function of [LB;UB]
% optZ = optimizer(Constraints,Objective,[],[LB; UB],z);
%
% % Compute the optimal z when LB=1, UB = 3;
% zopt = optZ{[1; 3]}
%
% % Compute two solutions, one for (LB,UB) [1;3] and one for (LB,UB) [2;6]
% zopt = optZ{[[1; 3], [2;6]]}
%
% % A second output argument can be used to catch infeasibility
% [zopt,infeasible] = optZ{[1; 3]}
%
% % To avoid the need to vectorize in order to handle multiple
% parameters, a cell-based format can be used, both for inputs and
% outputs. Note that the optimizer object now is called with a cell
% and returns a cell
%
% optZ = optimizer(Constraints,Objective,[],{LB,UB},{z,sum(z)})
% [zopt,infeasible] = optZ{{1,3}};
% zopt{1}
% zopt{2}
if nargin < 5
error('OPTIMIZER requires 5 inputs');
end
% With the new optional cell-based format, the internal format is always a
% vector with all information stacked, both in and out. Hence, we need to
% save original sizes before stacking things up
if isa(x,'cell')
xvec = [];
for i = 1:length(x)
if ~(isa(x{i},'sdpvar') | isa(x{i},'ndsdpvar'))
error(['The parameters must be SDPVAR objects. Parameter #' num2str(i) ' is a ' upper(class(x{i}))]);
end
if is(x{i},'complex')
x{i} = [real(x{i});imag(x{i})];
complexInput(i) = 1;
else
complexInput(i) = 0;
end
sizeOrigIn{i} = size(x{i});
z = x{i}(:);
mask{i} = uniqueRows(z);
xvec = [xvec;z(mask{i})];
end
x = xvec;
else
if ~isreal(x)%,'complex')
complexInput(1) = 1;
x = [real(x);imag(x)];
else
complexInput(1) = 0;
end
sizeOrigIn{1} = size(x);
x = x(:);
mask{1} = uniqueRows(x);
x = x(mask{1});
end
nIn = length(x);
mIn = 1;
if isa(u,'cell')
uvec = [];
for i = 1:length(u)
if is(u{i},'complex')
complexOutput(i) = 1;
u{i} = [real(u{i});imag(u{i})];
else
complexOutput(i) = 0;
end
sizeOrigOut{i} = size(u{i});
uvec = [uvec;u{i}(:)];
end
u = uvec;
else
if is(u,'complex')
complexOutput(1) = 1;
u = [real(u);imag(u)];
else
complexOutput(1) = 0;
end
sizeOrigOut{1} = size(u);
u = u(:);
end
nOut = length(u);
mOut = 1;
if isempty(options)
options = sdpsettings;
end
if ~isa(options,'struct')
error('Third argument in OPTIMIZER should be an options structure.');
end
% Silent by default. If we want displays, set to 2
options.verbose = max(options.verbose-1,0);
% Since code is based on a fake equality, we must avoid bound propagation
% based on equalities
options.avoidequalitybounds=1;
% Normalize...
if isa(Constraints,'constraint')
Constraints = lmi(Constraints);
end
if ~isempty(Constraints)
if ~isa(Constraints,'constraint') & ~isa(Constraints,'lmi')
error('The first argument in OPTIMIZER should be a set of constraints');
end
end
if ~isempty(Constraints)
if any(is(Constraints,'sos'))
tempOps = options;
tempOps.sos.model = 2;
tempOps.verbose = max(0,tempOps.verbose-1);
parameter_sos = [x;u;recover(depends(Objective))];
parameter_sos = depends(parameter_sos);
for i = 1:length(Constraints)
if ~is(Constraints,'sos')
parameter_sos = [parameter_sos depends(Constraints(i))];
end
end
parameter_sos = recover(parameter_sos);
[Constraints,Objective] = compilesos(Constraints,Objective,tempOps,parameter_sos);
end
end
if ~isequal(options.solver,'')
% User has specified solver. Let us impose this solver forcefully to
% the compilation code, in order to handle nonlinear parameterizations
if ~strcmp(options.solver(1),'+')
options.solver = ['+' options.solver];
end
end
if options.removeequalities
error('''removeequalities'' in optimizer objects not allowed.');
end
if ~isempty(Constraints) & any(is(Constraints,'uncertain'))
[Constraints,Objective,failure] = robustify(Constraints,Objective,options);
[aux1,aux2,aux3,model] = export((x == repmat(pi,nIn*mIn,1))+Constraints,Objective,options,[],[],0);
else
[aux1,aux2,aux3,model] = export((x == repmat(pi,nIn*mIn,1))+Constraints,Objective,options,[],[],0);
end
if ~isempty(aux3)
if isstruct(aux3)
if ismember(aux3.problem, [-9 -5 -4 -3 -2 -1 14])
error(['Failed exporting the model: ' aux3.info])
end
end
end
if norm(model.F_struc(1:nIn*mIn,1)-repmat(pi,length(x),1),inf) > 1e-10
error('Failed exporting the model (try to specify another solver)')
end
% Try to set up an optimal way to compute the output
base = getbase(u);
if is(u,'linear') & all(sum(base | base,2) == 1) & all(sum(base,2)==1) & all(base(:,1)==0)
% This is just a vecotr of variables
z = [];
map = [];
uvec = u(:);
for i = 1:length(uvec)
var = getvariables(uvec(i));
mapIndex = find(var == model.used_variables);
if ~isempty(mapIndex)
map = [map;mapIndex];
else
map = [map;0];
end
end
else
% Some expression which we will use assign and double to evaluate
vars = depends(u);
z = recover(vars);
map = [];
for i = 1:length(z)
var = vars(i);
mapIndex = find(var == model.used_variables);
if ~isempty(mapIndex)
map = [map;mapIndex];
else
map = [map;0];
end
end
end
if isempty(map) | min(size(map))==0
error('The requested decision variable (argument 4) is not in model');
end
model.getsolvertime = 0;
model.solver.callhandle = str2func(model.solver.call);
sys.recover = aux2;
sys.model = model;
sys.dimin = [nIn mIn];
sys.dimout = [nOut mOut];
sys.diminOrig = sizeOrigIn;
sys.dimoutOrig = sizeOrigOut;
sys.complexInput = complexInput;
sys.complexOutput = complexOutput;
sys.mask = mask;
sys.map = map;
sys.input.expression = x;
sys.output.expression = u;
sys.output.z = z;
sys.lastsolution = [];
% This is not guaranteed to give the index in the order the variables where
% given (tested in test_optimizer2
% [a,b,c] = find(sys.model.F_struc(1:prod(sys.dimin),2:end));
% Could be done using
[b,a,c] = find(sys.model.F_struc(1:prod(sys.dimin),2:end)');
% but let us be safe
%b = [];
%for i = 1:prod(sys.dimin)
% b = [b;find(sys.model.F_struc(i,2:end))];
%end
sys.parameters = b;
used_in = find(any(sys.model.monomtable(:,b),2));
Q = sys.model.Q;
Qa = Q;Qa(:,b)=[];Qa(b,:)=[];
Qb = Q(:,b);Qb(b,:)=[];
if nnz(Q)>0
zeroRow = find(~any(Q,1));
Qtest = Q;Q(zeroRow,:)=[];Q(:,zeroRow)=[];
problematicQP = nonconvexQuadratic(Qtest);%min(eig(full(Qtest)))<-1e-14;
else
problematicQP = 0;
end
if any(sum(sys.model.monomtable(used_in,:),2)>1) | any(sum(sys.model.monomtable(used_in,:) | sys.model.monomtable(used_in,:),2) > 1) | problematicQP | ~isempty(sys.model.evalMap) | any(any(sys.model.monomtable<0))
sys.nonlinear = 1;
else
sys.nonlinear = 0;
end
sys.F = Constraints;
sys.h = Objective;
sys.ops = options;
sys.complicatedEvalMap = 0;
% Are all nonlinear operators acting on simple parameters? Elimination
% strategy will only be applied on simple problems such as x<=exp(par)
for i = 1:length(sys.model.evalMap)
if ~all(ismember(sys.model.evalMap{i}.variableIndex,sys.parameters))
sys.complicatedEvalMap = 1;
end
if length(sys.model.evalMap{i}.arg)>2
sys.complicatedEvalMap = 1;
end
end
if sys.nonlinear & ~sys.complicatedEvalMap
% These artificial equalities are removed if we will use eliminate variables
sys.model.F_struc(1:length(sys.parameters),:) = [];
sys.model.K.f = sys.model.K.f - length(sys.parameters);
% Which variables are simple nonlinear operators acting on parameters
evalParameters = [];
for i = 1:length(sys.model.evalMap)
if all(ismember(sys.model.evalMap{i}.variableIndex,sys.parameters))
evalParameters = [evalParameters;sys.model.evalMap{i}.computes(:)];
end
end
sys.model.evalParameters = evalParameters;
end
% This data is used in eliminatevariables (nonlinear parameterizations)
% A lot of performance is gained by precomputing them
% This will work as long as there a no zeros in the parameters, which might
% cause variables to dissapear (as in x*parameter >=0, parameter = 0)
% (or similiar effects happen)
sys.model.precalc.newmonomtable = sys.model.monomtable;
sys.model.precalc.rmvmonoms = sys.model.precalc.newmonomtable(:,sys.parameters);
sys.model.precalc.newmonomtable(:,sys.parameters) = 0;
sys.model.precalc.Qmap = [];
% R2012b...
try
[ii,jj,kk] = stableunique(sys.model.precalc.newmonomtable*gen_rand_hash(0,size(sys.model.precalc.newmonomtable,2),1));
sys.model.precalc.S = sparse(kk,1:length(kk),1);
sys.model.precalc.skipped = setdiff(1:length(kk),jj);
sys.model.precalc.blkOneS = blkdiag(1,sys.model.precalc.S');
catch
end
if sys.nonlinear & ~sys.complicatedEvalMap
% Precompute some structures
newmonomtable = sys.model.monomtable;
rmvmonoms = newmonomtable(:,[sys.parameters;evalParameters]);
% Linear indexation to fixed monomial terms which have to be computed
% [ii1,jj1] = find((rmvmonoms ~= 0) & (rmvmonoms ~= 1));
[ii1,jj1] = find( rmvmonoms < 0 | rmvmonoms > 1 | fix(rmvmonoms) ~= rmvmonoms);
sys.model.precalc.index1 = sub2ind(size(rmvmonoms),ii1,jj1);
sys.model.precalc.jj1 = jj1;
% Linear indexation to linear terms
linterms = rmvmonoms == 1;
if ~isempty(jj1) | any(sum(linterms,2)>1)
[ii2,jj2] = find(linterms);
sys.model.precalc.index2 = sub2ind(size(rmvmonoms),ii2,jj2);
sys.model.precalc.jj2 = jj2;
sys.model.precalc.aux = rmvmonoms*0+1;
else
[ii2,jj2] = find(linterms);
sys.model.precalc.index2 = ii2;
sys.model.precalc.jj2 = jj2;
sys.model.precalc.aux = ones(size(rmvmonoms,1),1);
end
sys.model.newmonomtable = model.monomtable;
sys.model.rmvmonoms = sys.model.newmonomtable(:,[sys.parameters;evalParameters]);
sys.model.newmonomtable(:,union(sys.parameters,evalParameters)) = 0;
sys.model.removethese = find(~any(sys.model.newmonomtable,2));
sys.model.keepingthese = find(any(sys.model.newmonomtable,2));
end
sys = class(sys,'optimizer');
function i = uniqueRows(x);
B = getbase(x);
% Quick check for trivially unique rows, typical 99% case
[n,m] = size(B);
if n == m-1 && nnz(B)==n
if isequal(B,[spalloc(n,1,0) speye(n)])
i = 1:n;
return
end
end
if length(unique(B*randn(size(B,2),1))) == n
i = 1:n;
return
end
[temp,i,j] = unique(B,'rows');
i = i(:);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
or.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@constraint/or.m
| 2,653 |
utf_8
|
27825fd7ad2b8d86ce557d3e68f65448
|
function varargout = or(varargin)
%OR (overloaded)
% Prune empty clauses
varargin = {varargin{find(~cellfun('isempty',varargin))}};
% Models OR using a nonlinear operator definition
switch class(varargin{1})
case 'char'
z = varargin{2};
X = varargin{3};
Y = varargin{4};
F = ([]);
switch class(X)
case 'sdpvar'
x = X;
xvars = getvariables(x);
allextvars = yalmip('extvariables');
if (length(xvars)==1) & ismembcYALMIP(xvars,allextvars)
[x,F] = expandor(x,allextvars,F);
end
case 'constraint'
x = binvar(1,1);
F = F + (implies_internal(x,X));
otherwise
end
switch class(Y)
case 'sdpvar'
y = Y;
yvars = getvariables(y);
allextvars = yalmip('extvariables');
if (length(yvars)==1) & ismembcYALMIP(yvars,allextvars)
[y,F] = expandor(y,allextvars,F);
end
case {'constraint','lmi'}
y = binvar(1,1);
F = F + (implies_internal(y,Y));
otherwise
end
xy = [x y];
[M,m] = derivebounds(z);
if m>=1
varargout{1} = F + (sum(xy) >= 1);
else
varargout{1} = F + (sum(xy) >= z) + (z >= xy) +(binary(z));
end
varargout{2} = struct('convexity','none','monotonicity','exact','definiteness','none','model','integer');
varargout{3} = xy;
case {'sdpvar','constraint'}
varargout{1} = yalmip('define','or',varargin{:});
otherwise
end
function [x,F] = expandor(x,allextvars,F)
xmodel = yalmip('extstruct',getvariables(x));
if isequal(xmodel.fcn,'or')
X1 = xmodel.arg{1};
X2 = xmodel.arg{2};
switch class(X1)
case 'sdpvar'
x1 = X1;
xvars = getvariables(x1);
if ismembcYALMIP(xvars,allextvars)
[x1,F] = expandor(x1,allextvars,F);
end
case 'constraint'
x1 = binvar(1,1);
F = F + (iff_internal(X1,x1));
otherwise
end
switch class(X2)
case 'sdpvar'
x2 = X2;
yvars = getvariables(x2);
if ismembcYALMIP(yvars,allextvars)
[x2,F] = expandor(x2,allextvars,F);
end
case 'constraint'
x2 = binvar(1,1);
F = F + (iff_internal(X2,x2));
otherwise
end
x = [x1 x2];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
groupchanceconstraints.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/groupchanceconstraints.m
| 710 |
utf_8
|
11836c904991112de5ae44d3a433fe11
|
function S = groupchanceconstraints(F)
G = {};
S = {};
F = flatten(F);
for i = 1:length(F.clauses)
if ~isempty(F.clauses{i}.confidencelevel)
G = addgroup(G,F.clauses{i}.jointprobabilistic);
end
end
for i = 1:length(G)
S{i} = [];
end
for i = 1:length(F.clauses)
for j = 1:length(G)
if isequal(F.clauses{i}.jointprobabilistic,G{j});
S{j} = [S{j} i];
end
end
end
for i = 1:length(S)
s.type = '()';
s.subs{1} = S{i};
S{i} = subsref(F,s);
end
function G = addgroup(G,g)
if length(G)==0
G = {g};
else
i = 1;
while i<=length(G)
if isequal(G{i},g)
return
end
i = i+1;
end
G{end+1} = g;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
display.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/display.m
| 4,251 |
utf_8
|
faa1a9761a6adc79bf84740db5d5d064
|
function sys = display(X)
%display Displays a SET object.
X = flatten(X);
nlmi = length(X.LMIid);
if (nlmi == 0)
disp('empty SET')
return
end
lmiinfo{1} = 'Matrix inequality';
lmiinfo{2} = 'Element-wise inequality';
lmiinfo{3} = 'Equality constraint';
lmiinfo{4} = 'Second order cone constraint';
lmiinfo{5} = 'Rotated Lorentz constraint';
lmiinfo{7} = 'Integrality constraint';
lmiinfo{8} = 'Binary constraint';
lmiinfo{9} = 'KYP constraint';
lmiinfo{10}= 'Eigenvalue constraint';
lmiinfo{11}= 'Sum-of-square constraint';
lmiinfo{12}= 'Logic constraint';
lmiinfo{13}= 'Parametric declaration';
lmiinfo{14}= 'Low-rank data declaration';
lmiinfo{15}= 'Uncertainty declaration';
lmiinfo{16}= 'Distribution declaration';
lmiinfo{20}= 'Power cone constraint';
lmiinfo{30}= 'User defined compilation';
lmiinfo{40}= 'Generalized KYP constraint';
lmiinfo{50}= 'Special ordered set of type 2';
lmiinfo{51}= 'Special ordered set of type 1';
lmiinfo{52}= 'Semi-continuous variable';
lmiinfo{53}= 'Semi-integer variable';
lmiinfo{54} = 'Vectorized second-order cone constraints';
lmiinfo{55}= 'Complementarity constraint';
lmiinfo{56}= 'Meta constraint';
lmiinfo{57}= 'Stacked SDP constraints';
headers = {'ID','Constraint','Tag'};
rankVariables = yalmip('rankvariables');
extVariables = yalmip('extvariables');
if nlmi>0
for i = 1:nlmi
data{i,1} = ['#' num2str(i)];
data{i,2} = lmiinfo{X.clauses{i}.type};
data{i,3} = '';
if length(getvariables(X.clauses{i}.data)) == 1
if any(ismember(getvariables(X.clauses{i}.data),rankVariables))
data{i,3} = 'Rank constraint';
end
end
if X.clauses{i}.type == 14
elseif X.clauses{i}.type == 56
data{i,2} = [data{i,3} ' (' X.clauses{i}.data{1} ')'];
data{i,3} = X.clauses{i}.handle;
else
classification = '';
members = ismembcYALMIP(getvariables(X.clauses{i}.data),yalmip('intvariables'));
if any(members)
classification = [classification ',integer'];
end
if size(X.clauses{i},2)>1
classification = [classification ',logic'];
end
if ~isempty(X.clauses{i}.confidencelevel)
classification = [classification ',chance'];
end
linearbilinearquadraticsigmonial = is(X.clauses{i}.data,'LBQS');
if ~linearbilinearquadraticsigmonial(1)
if linearbilinearquadraticsigmonial(4)
classification = [classification ',sigmonial'];
elseif linearbilinearquadraticsigmonial(2)
classification = [classification ',bilinear'];
elseif linearbilinearquadraticsigmonial(3)
classification = [classification ',quadratic'];
else
classification = [classification ',polynomial'];
end
end
data{i,3} = X.clauses{i}.handle;
if ~isreal(X.clauses{i}.data)
classification = [classification ',complex'];
end
members = ismembcYALMIP(getvariables(X.clauses{i}.data),extVariables);
if any(members)
classification = [classification ',derived'];
end
if length(classification)==0
else
data{i,2} = [data{i,2} ' (' classification(2:end) ')'];
end
if ismember(X.clauses{i}.type,[1 2 3 4 5 9]);
data{i,2} = [data{i,2} ' ' num2str(size(X.clauses{i}.data,1)) 'x' num2str(size(X.clauses{i}.data,2))];
end
end
end
end
% If no tags, don't show...
if length([data{:,3}])==0
headers = {headers{:,1:2}};
data = reshape({data{:,1:2}},length({data{:,1:2}})/2,2);
end
yalmiptable('',headers,data)
function x= truncstring(x,n)
if length(x) > n
x = [x(1:n-3) '...'];
end
function x = fillstring(x,n)
x = [x blanks(n-length(x))];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
plot.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/plot.m
| 10,083 |
utf_8
|
090afe5b9fc145b26c6455b0a5dadfef
|
function varargout = plot(varargin)
%PLOT Plots the feasible region of a set of constraints
%
% p = plot(C,x,c,n,options)
%
% Note that only convex sets are allowed, or union of convex sets
% represented using binary variables (either defined explictly or
% introduced by YALMIP when modelling, e.g., mixed integer linear
% programming representable operators)
%
% C: Constraint object
% x: Plot variables [At most three variables]
% c: color [double] ([r g b] format) or char from 'rymcgbk'
% n: #vertices [double ] (default 100 in 2D and 300 otherwise)
% options: options structure from sdpsettings
% Get the onstraints
if nargin<1
return
end
F = varargin{1};
if length(F)==0
return;
end
if nargin < 5
opts = sdpsettings('verbose',0);
else
opts = varargin{5};
if isempty(opts)
opts = sdpsettings('verbose',0);
end
end
opts.verbose = max(opts.verbose-1,0);
if any(is(F,'uncertain'))
F = robustify(F,[],opts);
end
if nargin < 3
color=['rymcgbk']';
else
color = varargin{3};
if isa(color,'sdpvar')
error('The variables should be specified in the second argument.');
end
color = color(:)';
if isempty(color)
color=['rymcgbk']';
end
end
% Plot onto this projection (at most in 3D)
if nargin < 2
x = [];
else
x = varargin{2};
if ~isempty(x)
if ~isa(x,'sdpvar')
error('Second argument should be empty or an SDPVAR');
end
x = x(:);
x = x(1:min(3,length(x)));
end
end
if isempty(F)
return
end
if any(is(F,'sos'))
% Use image representation, feels safer (I'm not sure about the logic
% in the code at the moment. Can the dualization mess up something
% otherwise...)
if ~(opts.sos.model == 1)
opts.sos.model = 2;
end
% Assume the variables we are plotting are the parametric
F = compilesos(F,[],opts,x);
end
% Create a model in YALMIPs low level format
% All we change later is the cost vector
%sol = solvesdp(F,sum(x),opts);
[model,recoverdata,diagnostic,internalmodel] = export(F,[],opts,[],[],0);
if isempty(internalmodel) | (~isempty(diagnostic) && diagnostic.problem)
error('Could not create model. Can you actually solve problems with this model?')
end
internalmodel.options.saveduals = 0;
internalmodel.getsolvertime = 0;
internalmodel.options.dimacs = 0;
% Try to find a suitable set to plot
if isempty(x)
if isempty(internalmodel.extended_variables) & isempty(internalmodel.aux_variables)
x = depends(F);
x = x(1:min(3,length(x)));
localindex = 1;
localindex = find(ismember(recoverdata.used_variables,x));
else
% not extended variables
candidates = setdiff(1:length(internalmodel.c),[ internalmodel.aux_variables(:)' internalmodel.extended_variables(:)']);
% Not nonlinear variables
candidates = candidates(find(internalmodel.variabletype(candidates)==0));
% Settle with this guess
localindex = candidates(1:min(3,length(candidates)));
x = localindex;
end
else
localindex = [];
for i = 1:length(x)
localindex = [localindex find(ismember(recoverdata.used_variables,getvariables(x(i))))];
end
end
if nargin < 4
if length(x)==3
n = 300;
else
n = 100;
end
else
n = varargin{4};
if isempty(n)
if length(x)==3
n = 300;
else
n = 100;
end
end
if ~isa(n,'double')
error('4th argument should be an integer>0');
end
end
if ~isempty(internalmodel.integer_variables)
error('PLOT can currently not display sets involving integer variables');
end
if isempty(internalmodel.binary_variables)
[x_opt{1},errorstatus] = generateBoundary(internalmodel,x,n,localindex);
else
if strcmp(internalmodel.solver.tag,'BNB')
internalmodel.solver = internalmodel.solver.lower;
end
nBin = length(internalmodel.binary_variables);
p = extractLP(internalmodel);
p = extractOnly(p,internalmodel.binary_variables);
internalmodel.F_struc = [zeros(nBin,size(internalmodel.F_struc,2));internalmodel.F_struc];
I = eye(nBin);
internalmodel.F_struc(1:nBin,1+internalmodel.binary_variables) = I;
internalmodel.K.f = internalmodel.K.f + length(internalmodel.binary_variables);
errorstatus = 1;
x_opt = {};
errorstatus = zeros(1,2^nBin);
for i = 0:2^nBin-1;
comb = dec2decbin(i,nBin);
if checkfeasiblefast(p,comb(:),1e-6)
internalmodel.F_struc(1:nBin,1) = -comb(:);
[x_temp,wrong] = generateBoundary(internalmodel,x,n,localindex);
if ~wrong
errorstatus(i+1) = 0;
x_opt{end+1} = x_temp;
end
else
errorstatus(i+1)=0;
end
end
end
if all(errorstatus)
if nargout==0
plot(0);
end
elseif nargout == 0
for i = 1:length(x_opt)
try
plotSet(x_opt{i},color(1+rem(i-1,size(color,1)),:),opts);
catch
end
end
end
if nargout > 0
varargout{1} = x_opt;
end
function [xout,errorstatus] = solvefordirection(c,internalmodel,uv)
internalmodel.c = 0*internalmodel.c;
internalmodel.c(uv) = c;
sol = feval(internalmodel.solver.call,internalmodel);
xout = sol.Primal;
xout = xout(uv(:));
errorstatus = sol.problem;
function p = plotSet(x_opt,color,options)
if size(x_opt,1)==1
p = line(x_opt,[0 0],'color',color);
set(p,'LineStyle',options.plot.wirestyle);
set(p,'LineStyle',options.plot.wirestyle);
set(p,'LineWidth',options.plot.linewidth);
set(p,'EdgeColor',options.plot.edgecolor);
set(p,'Facealpha',options.plot.shade);
elseif size(x_opt,1)==2
p = patch(x_opt(1,:),x_opt(2,:),color);
set(p,'LineStyle',options.plot.wirestyle);
set(p,'LineWidth',options.plot.linewidth);
set(p,'EdgeColor',options.plot.edgecolor);
set(p,'Facealpha',options.plot.shade);
else
try
K = convhulln(x_opt');
p = patch('Vertices', x_opt','Faces',K,'FaceColor', color);
catch
p = fill3(x_opt(1,:),x_opt(2,:),x_opt(3,:),1);
end
set(p,'LineStyle',options.plot.wirestyle);
set(p,'LineWidth',options.plot.linewidth);
set(p,'EdgeColor',options.plot.edgecolor);
set(p,'Facealpha',options.plot.shade);
lighting gouraud;
view(3);
camlight('headlight','infinite');
camlight('headlight','infinite');
camlight('right','local');
camlight('left','local');
end
function [x_opt,errorstatus] = generateBoundary(internalmodel,x,n,localindex);
x_opt = [];
phi = [];
errorstatus = 0;
waitbar_created = 0;
t0 = clock;
waitbar_starts_at = 2;
lastdraw = clock;
try % Try to ensure that we close h
if length(x)==2
mu = 0.5;
else
mu=1;
end
n_ = n;
n = ceil(mu*n);
% h = waitbar(0,['Please wait, solving ' num2str(n_) ' problems using ' internalmodel.solver.tag]);
angles = (0:(n))*2*pi/n;
if length(x)==2
c = [cos(angles);sin(angles)];
elseif length(x) == 1
c = [-1 1];n = 2;
else
c = randn(3,n);
end
i=1;
while i<=n & errorstatus ~=1
[xi,errorstatus] = solvefordirection(c(:,i),internalmodel,localindex(:));
if errorstatus == 2
disp('Discovered unbounded direction. You should add bounds on variables')
elseif errorstatus == 12
[xi,errorstatus] = solvefordirection(0*c(:,i),internalmodel,localindex(:));
if errorstatus == 0
errorstatus = 2;
disp('Discovered unbounded direction. You should add bounds on variables')
end
end
x_opt = [x_opt xi];
if ~waitbar_created
if etime(clock,t0)>waitbar_starts_at;
h = waitbar(0,['Please wait, solving ' num2str(n_) ' problems using ' internalmodel.solver.tag]);
waitbar_created = 1;
end
end
if waitbar_created & etime(clock,lastdraw)>1/10
waitbar(i/n_,h)
lastdraw = clock;
end
i=i+1;
end
if errorstatus==0 & length(x)==2
% Close the set
x_opt = [x_opt x_opt(:,1)];
% Add points adaptively
pick = 1;
n = floor((1-mu)*n_);
for i = 1:1:n
for j= 1:(size(x_opt,2)-1)
d = x_opt(:,j)-x_opt(:,j+1);
distance(j,1) = d'*d;
end
[dist,pos]=sort(-distance);
% Select insertion point
phii=(angles(pos(pick))+angles(pos(pick)+1))/2;
xi = solvefordirection([cos(phii);sin(phii)],internalmodel,localindex);
d1=xi-x_opt(:,pos(pick));
d2=xi-x_opt(:,pos(pick)+1);
if d1'*d1<1e-3 | d2'*d2<1e-3
pick = pick+1;
else
angles = [angles(1:pos(pick)) phii angles((pos(pick))+1:end)];
x_opt = [x_opt(:,1:pos(pick)) xi x_opt(:,(pos(pick))+1:end)];
end
if ~waitbar_created
if etime(clock,t0)>waitbar_starts_at;
h = waitbar(0,['Please wait, solving ' num2str(n_) ' problems using ' internalmodel.solver.tag]);
waitbar_created = 1;
end
end
if waitbar_created
waitbar((ceil(n_*mu)+i)/n_,h);
end
end
end
if waitbar_created
close(h);
end
catch
if waitbar_created
close(h);
end
end
function pLP = extractLP(p);
pLP = p;
pLP.F_struc = pLP.F_struc(1:p.K.f+p.K.l,:);
pLP.K.q = 0;
pLP.K.s = 0;
function pRed = extractOnly(p,these);
pRed = p;
p.F_struc(:,1+these) = 0;
removeEQ = find(any(p.F_struc(1:pRed.K.f,2:end),2));
removeLP = find(any(p.F_struc(1+pRed.K.f:end,2:end),2));
pRed.F_struc(pRed.K.f+removeLP,:)=[];
pRed.F_struc(removeEQ,:)=[];
pRed.K.f = pRed.K.f - length(removeEQ);
pRed.K.l = pRed.K.l - length(removeLP);
pRed.F_struc = pRed.F_struc(:,[1 1+these]);
pRed.lb = pRed.lb(these);
pRed.ub = pRed.ub(these);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
check.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/check.m
| 7,498 |
utf_8
|
f38af4ea7112e1679d548c202f244cd4
|
function [pres,dres] = check(F)
% CHECK(F) Displays/calculates constraint residuals on constraint F
%
% [pres,dres] = check(F)
%
% pres : Primal constraint residuals
% dres : Dual constraint residuals
%
% If no output argument is supplied, tabulated results are displayed
%
% Primal constraint residuals are calculated as:
%
% Semidefinite constraint F(x)>=0 : min(eig(F))
% Element-wise constraint F(x)>=0 : min(min(F))
% Equality constraint F==0 : -max(max(abs(F)))
% Second order cone t>=||x|| : t-||x||
% Integrality constraint on x : max(abs(x-round(x)))
% Sum-of-square constraint : Minus value of largest (absolute value) coefficient
% in the polynomial p-v'*v
%
% Dual constraints are evaluated similarily.
%
% See also SOLVESDP, SOLVESOS, SOSD, DUAL
% Check if solution avaliable
currsol = evalin('caller','yalmip(''getsolution'')');
if isempty(currsol)
disp('No solution available.')
return
end
F = flatten(F);
nlmi = length(F.LMIid);
spaces = [' '];
if (nlmi == 0)
if nargout == 0
disp('empty LMI')
else
pres = [];
dres = [];
end
return
end
lmiinfo{1} = 'Matrix inequality';
lmiinfo{2} = 'Elementwise inequality';
lmiinfo{3} = 'Equality constraint';
lmiinfo{4} = 'Second order cone constraint';
lmiinfo{5} = 'Rotated Lorentz constraint';
lmiinfo{7} = 'Integer constraint';
lmiinfo{8} = 'Binary constraint';
lmiinfo{9} = 'KYP constraint';
lmiinfo{10} = 'Eigenvalue constraint';
lmiinfo{11} = 'SOS constraint';
lmiinfo{15} = 'Uncertainty declaration';
lmiinfo{54} = 'Vectorized second order cone constraints';
lmiinfo{55} = 'Complementarity constraint';
lmiinfo{56} = 'Logic constraint';
header = {'ID','Constraint','Primal residual','Dual residual','Tag'};
if nargout==0
disp(' ');
end
% Checkset is very slow for multiple SOS
% The reason is that REPLACE has to be called
% for every SOS. Instead, precalc on one vector
p=[];
ParVar=[];
soscount=1;
for j = 1:nlmi
if F.clauses{j}.type==11
pi = F.clauses{j}.data;
[v,ParVari] = sosd(pi);
if isempty(v)
p=[p;0];
else
p=[p;pi];
ParVar=unique([ParVar(:);ParVari(:)]);
end
end
end
if ~isempty(ParVar)
ParVar = recover(ParVar);
p = replace(p,ParVar,double(ParVar));
end
for j = 1:nlmi
constraint_type = F.clauses{j}.type;
if constraint_type~=11 && constraint_type~=56
F0 = double(F.clauses{j}.data);
end
if ~((constraint_type == 56) || (constraint_type==11)) && any(isnan(F0(:)))
res(j,1) = NaN;
else
switch F.clauses{j}.type
case {1,9}
if isa(F0,'intval')
res(j,1) = full(min(inf_(veigsym(F0))));
else
res(j,1) = full(min(real(eig(F0))));
end
case 2
if isa(F0,'intval')
res(j,1) = full(min(min(inf_(F0))));
else
res(j,1) = full(min(min(F0)));
end
case 3
res(j,1) = -full(max(max(abs(F0))));
case 4
res(j,1) = full(F0(1)-norm(F0(2:end)));
case 5
res(j,1) = full(2*F0(1)*F0(2)-norm(F0(3:end))^2);
case 7
res(j,1) = -full(max(max(abs(F0-round(F0)))));
case 8
res(j,1) = -full(max(max(abs(F0-round(F0)))));
res(j,1) = min(res(j,1),-(any(F0>1) | any(F0<0)));
case 54
res(j,1) = inf;
for k = 1:size(F0,2)
res(j,1) = min(res(j,1),full(F0(1,k)-norm(F0(2:end,k))));
end
case 11
if 0
p = F.clauses{j}.data;
[v,ParVar] = sosd(p);
if ~isempty(ParVar)
ParVar = recover(ParVar);
p = replace(p,ParVar,double(ParVar));
end
if isempty(v)
res(j,1)=nan;
else
h = p-v'*v;
res(j,1) = full(max(max(abs(getbase(h)))));
end
else
%p = F.clauses{j}.data;
[v,ParVar] = sosd(F.clauses{j}.data);
if isempty(v)
res(j,1)=nan;
else
h = p(soscount)-v'*v;
res(j,1) = full(max(max(abs(getbase(h)))));
end
soscount=soscount+1;
end
case 56
res(j,1) = logicSatisfaction(F.clauses{j}.data);
otherwise
res(j,1) = nan;
end
end
% Get the internal index
LMIid = F.LMIid(j);
dual = yalmip('dual',LMIid);
if isempty(dual) | any(isnan(dual))
resdual(j,1) = NaN;
else
switch F.clauses{j}.type
case {1,9}
resdual(j,1) = min(eig(dual));
case 2
resdual(j,1) = min(min(dual));
case 3
resdual(j,1) = -max(max(abs(dual)));
case 4
resdual(j,1) = dual(1)-norm(dual(2:end));
case 5
resdual(j,1) = 2*dual(1)*dual(2)-norm(dual(3:end))^2;
case 7
resdual(j,1) = nan;
case 54
resdual(j,1) = inf;
for k = 1:size(dual,2)
resdual(j,1) = min(resdual(j,1),full(dual(1,k)-norm(dual(2:end,k))));
end
otherwise
gap = nan;
end
end
if nargout==0
data{j,1} = ['#' num2str(j)];
data{j,2} = lmiinfo{F.clauses{j}.type};
data{j,3} = res(j,1);
data{j,4} = resdual(j,1);
data{j,5} = F.clauses{j}.handle;
if ~islinear(F.clauses{j}.data)
if is(F.clauses{j}.data,'sigmonial')
classification = 'sigmonial';
elseif is(F.clauses{j}.data,'bilinear')
classification = 'bilinear';
elseif is(F.clauses{j}.data,'quadratic')
classification = 'quadratic';
else
classification = 'polynomial';
end
data{j,2} = [data{j,2} ' (' classification ')'];
end
end
end
if nargout>0
pres = res;
dres = resdual;
else
keep = ones(1,5);
if length([data{:,5}])==0
keep(5) = 0;
end
if all(isnan(resdual))
keep(4) = 0;
end
header = {header{:,find(keep)}};
temp = {data{:,find(keep)}};
data = reshape(temp,length(temp)/nnz(keep),nnz(keep));
yalmiptable('',header,data)
disp(' ');
end
function res = logicSatisfaction(clause);
a = clause{2};
b = clause{3};
if isa(a,'sdpvar')
aval = double(a);
if is(a,'binary')
atruth = aval == 1;
else
atruth = aval>=0;
end
elseif isa(a,'lmi') | isa(a,'constraint')
aval = check(lmi(a));
atruth = aval >= 0;
end
if isa(b,'sdpvar')
bval = double(b);
elseif isa(b,'lmi') | isa(b,'constraint')
bval = check(lmi(b));
btruth = bval >= 0;
end
switch clause{1}
case 'implies'
if all(btruth >= atruth)
res = 1;
else
res = -1;
end
case 'iff'
if all(btruth == atruth);
res = 1;
else
res = -1;
end
otherwise
res = nan;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
kkt.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/kkt.m
| 7,518 |
utf_8
|
fb7d8e6e638dcea5721ade8b986ddf2e
|
function [KKTConstraints, details] = kkt(F,h,parametricVariables,ops);
%KKT Create KKT system
%
% [KKTConstraints, details] = kkt(Constraints,Objective,parameters,options)
if ~isempty(F)
if any(is(F,'sos2'))
error('SOS2 structures not allowed in KKT');
end
end
[aux1,aux2,aux3,model] = export(F,h,sdpsettings('solver','quadprog','relax',2));
if isempty(model)
error('KKT system can only be derived for LPs or QPs');
end
model.problemclass.constraint.binary = 0;
model.problemclass.constraint.integer = 0;
model.problemclass.constraint.semicont = 0;
model.problemclass.constraint.sos1 = 0;
model.problemclass.constraint.sos2 = 0;
if ~ismember(problemclass(model), {'LP', 'Convex QP', 'Nonconvex QP'})
error('KKT system can only be derived for LPs or QPs');
end
if ~isempty(model.binary_variables) | ~isempty(model.integer_variables) | ~isempty(model.semicont_variables)
comb = [model.used_variables(model.binary_variables) model.used_variables(model.integer_variables) model.used_variables(model.semicont_variables) ];
if ~isempty(intersect(comb,getvariables(decisionvariables)))
error('KKT system cannot be derived due to binary or integer decision variables');
end
end
if nargin < 3
x = recover(model.used_variables);
parameters = [];
else
% Make sure they are sorted
parameters = getvariables(parametricVariables);
x = recover(setdiff(model.used_variables,parameters));
notparameters = find(ismember(model.used_variables,getvariables(x)));%parameters);
parameters = setdiff(1:length(model.used_variables),notparameters);
if ~isempty(parameters)
y = recover(model.used_variables(parameters));
end
end
if nargin < 4
ops = sdpsettings;
end
if isempty(ops)
ops = sdpsettings;
end
% Ex==f
E = model.F_struc(1:model.K.f,2:end);
f = -model.F_struc(1:model.K.f,1);
% Ax <= b
A = -model.F_struc(model.K.f+1:model.K.f+model.K.l,2:end);
b = model.F_struc(model.K.f+1:model.K.f+model.K.l,1);
c = model.c;
Q = model.Q;
% Are there equalities hidden in the in equalities
moved = zeros(length(b),1);
hash = randn(size(A,2),1);
Ahash = A*hash;
removed = zeros(length(b),1);
for i = 1:length(b)
if ~removed(i)
same = setdiff(find(Ahash == Ahash(i)),i);
k = find(b(i) == b(same));
if ~isempty(k)
removed(same(k)) = 1;
end
k = find(b(i) < b(same));
if ~isempty(k)
removed(same(k)) = 1;
end
end
end
if any(removed)
if ops.verbose
disp(['Removed ' num2str(nnz(removed)) ' duplicated or redundant inequalities']);
end
A(find(removed),:) = [];
b(find(removed)) = [];
Ahash = A*hash;
end
for i = 1:length(b)
if ~moved(i)
same = setdiff(find(Ahash == -Ahash(i)),i);
k = find(b(i) == -b(same));
if ~isempty(k)
E = [E;A(i,:)];
f = [f;b(i)];
moved(i) = 1;
moved(same(k)) = 1;
end
end
end
if any(moved)
if ops.verbose
disp(['Transfered ' num2str(nnz(moved)) ' inequalities to equalities']);
end
A(find(moved),:) = [];
b(find(moved)) = [];
Ahash = A*hash;
end
if ~isempty(b)
infBounds = find(b>0 & isinf(b));
if ~isempty(infBounds)
b(infBounds) = [];
A(infBounds,:) = [];
end
end
[dummy,rr] = unique([A b],'rows');
if length(rr)~=size(A,1)
A = A(rr,:);
b = b(rr);
end
if ~isempty(parameters)
b = b-A(:,parameters)*y;
f = f-E(:,parameters)*y;
A(:,parameters) = [];
E(:,parameters) = [];
c(parameters) = [];
Q2 = model.Q(notparameters,parameters);
c = c + 2*Q2*y;
Q = Q(notparameters,notparameters);
end
used = find(any(A,2));
if isempty(setdiff(1:size(A,1),used))
parametricDomain = [];
else
r = setdiff(1:size(A,1),used);
parametricDomain = b(r)>=0;
A(r,:)=[];
b(r)=[];
end
if isempty(E)
E = [];
f = [];
end
Lambda = sdpvar(size(A,1),1); % Ax <=b
mu = sdpvar(size(E,1),1); % Ex+f==0
if ops.kkt.dualbounds
if ops.verbose
disp('Starting derivation of dual bounds (can be turned off using option kkt.dualbounds)');
end
[U,pL] = derivedualBounds(2*Q,c,A,b,E,f,ops,parametricDomain);
%[U,pL] = derivedualBoundsParameterFree(2*Q,c,A,b,E,f,ops,parametricDomain);
else
U = [];
end
KKTConstraints = [];
s = 2*Q*x + c;
if ~isempty(A)
%KKTConstraints = [KKTConstraints, complements(b-A*x, Lambda >= 0):'Compl. slackness and primal-dual inequalities'];
KKTConstraints = [KKTConstraints, complements(Lambda >= 0,b-A*x):'Compl. slackness and primal-dual inequalities'];
s = s + A'*Lambda;
end
if ~isempty(E)
KKTConstraints = [KKTConstraints, (E*x == f):'Primal feasible'];
s = s + E'*mu;
end
if ~isempty(U)
finU = find(~isinf(U));
if ~isempty(finU)
KKTConstraints = [KKTConstraints, (Lambda(finU) <= U(finU)):'Upper bound on duals'];
end
end
KKTConstraints = [KKTConstraints, (s == 0):'Stationarity'];
s_ = indicators(KKTConstraints(1));
if ops.kkt.licqcut
if ops.verbose
disp('Generating LICQ cuts');
end
[Alicq,blicq] = createLICQCut(A);
KKTConstraints = [KKTConstraints, Alicq*s_ <= blicq];
end
if ops.kkt.minnormdual;
MinNorm = [0 <= Lambda <= 10000*s_,s == 0];
ops.kkt.minnormdual = ops.kkt.minnormdual-1;
parametricInMinNorm = recover(setdiff(depends(MinNorm),depends(Lambda)));
[kkt2,info2] = kkt(MinNorm,Lambda'*Lambda,parametricInMinNorm,ops);
kkt2 = [kkt2, [indicators(kkt2(1)) <= 1-[s_;s_]]];
kkt2 = [kkt2, info2.dual <= 10000];
KKTConstraints = [KKTConstraints, kkt2];
details.info2 = info2;
end
if nnz(Q)>0
details.info = 'min x''Qx+c''x';
else
details.info = 'min c''x';
end
if isempty(E)
details.info = [details.info ' s.t. Ax<=b'];
else
details.info = [details.info ' s.t. Ax<b, Ex=f'];
end
details.c = c;
details.Q = Q;
details.A = A;
details.b = b;
details.E = E;
details.f = f;
details.dual = Lambda;
details.dualeq = mu;
details.primal = x;
if length(b)>0
details.inequalities = A*x <= b;
else
details.inequalities = [];
end
if length(f)>0
details.equalities = E*x == f;
else
details.equalities = [];
end
if isempty(U)
U = repmat(inf,length(b),1);
end
details.dualbounds = U;
function [Alicq,blicq] = createLICQCut(A);
Alicq = ones(1,size(A,1));
blicq = size(A,2);
Atemp = A;
[ii,jj] = sort(sum(A | A,1));
Atemp = Atemp(:,jj);
[ii,jj] = sort(sum(A | A,2));
Atemp = Atemp(jj,:);
for ii = 1:size(Atemp,1)
rr(ii) = min(find(Atemp(ii,:)));
end
[ii,kk] = sort(rr);
kk = fliplr(kk);
Atemp = Atemp(kk,:);
nel = sum(Atemp|Atemp,2);
top = 1;
while top <= length(nel)
same = nel == nel(top);
used_in_first = find(Atemp(top,:));
oldtop = top;
while top <= length(nel)-1 && all(ismember(find(Atemp(top+1,:)),used_in_first))
top = top + 1;
end
if length(used_in_first)<size(A,2)
blicq = [blicq;nnz(used_in_first)];
e = spalloc(1,size(A,1),0);
e(jj(kk(oldtop:top)))=1;
Alicq = [Alicq;e];
end
if nnz(any(full(Atemp(1:top,:)),1)) < size(A,2)
blicq = [blicq; nnz(any(full(Atemp(1:top,:)),1))];
e = spalloc(1,size(A,1),0);
e(jj(kk(1:top))) = 1;
Alicq = [Alicq;e];
end
rr=oldtop:top;
ss = find(nel(rr)==1);
if ~isempty(ss)
blicq = [blicq;1];
e = spalloc(1,size(A,1),0);
e(jj(kk(rr(ss)))) = 1;
Alicq = [Alicq;e];
end
top = top + 1;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
getvariables.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/getvariables.m
| 905 |
utf_8
|
ef689619cd74e765cfe444b697d69eb0
|
function used = getvariables(F)
F = flatten(F);
if length(F.clauses) == 0
used = [];
return
end
if isa(F.clauses{1},'cell')
F = flatten(F);
end
used = recursivegetvariables(F,1,length(F.clauses));
function used = recursivegetvariables(F,startindex,endindex)
if endindex-startindex>50
newstart = startindex;
mid = ceil((startindex + endindex)/2);
newend = endindex;
used1 = recursivegetvariables(F,newstart,mid);
used2 = recursivegetvariables(F,mid+1,newend);
used = uniquestripped([used1 used2]);
else
used = [];
if startindex <= length(F.clauses)
used = getvariables(F.clauses{startindex}.data);
for i = startindex+1:endindex
Fivars = getvariables(F.clauses{i}.data);
if ~isequal(used,Fivars(:)')
used = [used Fivars(:)'];
end
end
used = uniquestripped(used);
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
depends.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/depends.m
| 826 |
utf_8
|
9d357105527d2957bed1f995761d9b8f
|
function LinearVariables = depends(F)
F = flatten(F);
% Get all used variables in this LMI object
used = recursivedepends(F.clauses);
% Now, determine the involved linear variables
[mt,variabletype] = yalmip('monomtable');
if any(variabletype)%1%~isempty(nlv) & any(ismembc(used,nlv(1,:)))
LinearVariables = find(any(mt(used,:),1));
LinearVariables = LinearVariables(:)';
else
LinearVariables = used;
end
function used = recursivedepends(clauses)
if length(clauses) > 2
mid = floor(length(clauses)/2);
used1 = recursivedepends({clauses{1:mid}});
used2 = recursivedepends({clauses{mid+1:end}});
used = uniquestripped([used1 used2]);
else
used = [];
for i = 1:length(clauses)
Fivar = getvariables(clauses{i}.data);
used = uniquestripped([used Fivar(:)']);
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
polytope.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/polytope.m
| 2,367 |
utf_8
|
936949134726945ac12d1cf313b998c3
|
function [P,x] = polytope(X,options)
% polytope Converts constraints to polytope object
%
% P = polytope(F)
% [P,x] = polytope(F)
%
% P : polytope object (Requires the Multi-parametric Toolbox)
% x : sdpvar object defining the variables in the polytope P.H*x<=P.K
% F : Constraint object with linear inequalities
if nargin < 2
options = sdpsettings;
elseif isempty(options)
options = sdpsettings;
end
[p,recoverdata,solver,diagnostic,F] = compileinterfacedata(X,[],[],[],options,0);
if p.K.q(1) > 0 | p.K.s(1) > 0 | any(p.variabletype)
error('Polytope can only be applied to MILP-representable constraints.')
end
if p.K.f > 0
try
[P,x] = polyhedron(X,options);
return
catch
disp('MPT does not support polytopes with empty interior')
disp('Note that these equality constraints might have been generated internally by YALMIP')
error('Functionality not yet supported')
end
end
if isempty(p.binary_variables) & isempty(p.integer_variables)
P = polytope(-p.F_struc(:,2:end),p.F_struc(:,1));
x = recover(p.used_variables);
else
nBin = length(p.binary_variables);
[pBinary,removeEQ,removeLP] = extractOnly(p,p.binary_variables);
p.F_struc = [p.F_struc(removeEQ,:);p.F_struc(p.K.f+removeLP,:)];
p.K.f = length(removeEQ);
p.K.l = length(removeLP);
p.used_variables(p.binary_variables)=[];
x = recover(p.used_variables);
P = [];
for i = 0:2^nBin-1;
comb = dec2decbin(i,nBin);
if checkfeasiblefast(pBinary,comb(:),1e-6)
pi = p;
H = -p.F_struc(:,2:end);% Hx < K
K = p.F_struc(:,1);
K = K-H(:,p.binary_variables)*comb(:);
H(:,p.binary_variables)=[];
P = [P polytope(H,K)];
end
end
end
function pLP = extractLP(p);
pLP = p;
pLP.F_struc = pLP.F_struc(1:p.K.f+p.K.l,:);
pLP.K.q = 0;
pLP.K.s = 0;
function [pRed,removeEQ,removeLP] = extractOnly(p,these);
pRed = p;
p.F_struc(:,1+these) = 0;
removeEQ = find(any(p.F_struc(1:pRed.K.f,2:end),2));
removeLP = find(any(p.F_struc(1+pRed.K.f:end,2:end),2));
pRed.F_struc(pRed.K.f+removeLP,:)=[];
pRed.F_struc(removeEQ,:)=[];
pRed.K.f = pRed.K.f - length(removeEQ);
pRed.K.l = pRed.K.l - length(removeLP);
pRed.F_struc = pRed.F_struc(:,[1 1+these]);
pRed.lb = pRed.lb(these);
pRed.ub = pRed.ub(these);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
pwamodel.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/pwamodel.m
| 1,084 |
utf_8
|
b0d6a88e6f4c02018d6c85b072b057de
|
function [A,b] = pwamodel(F,x)
[dummy,aux,s,model] = export(F,[]);
A = -model.F_struc(:,2:end);
b = model.F_struc(:,1);
keep_these = find(ismember(aux.used_variables,getvariables(x)));
A = [A(:,keep_these) A(:,setdiff(1:size(A,2),keep_these))];
[A,b] = fourier_motzkin(A,b,length(keep_these));
function [A,b] = fourier_motzkin(A,b,m)
while size(A,2)>m
[A,b] = fourier_motzkin_1(A,b,m);
[aux,i] = unique([A b],'rows');
A = A(i,:);
b = b(i);
end
function [Aout,bout] = fourier_motzkin_1(A,b,m)
for i = m+1:size(A,2)
less = find(A(:,i)>0);
larger = find(A(:,i)<0);
t(i-m) =length(less)*length(larger);
end
[minn,remove] = min(t);
remove = remove+m;
keep = setdiff(1:size(A,2),remove);
less = find(A(:,remove)>0);
larger = find(A(:,remove)<0);
notinvolved = find(A(:,remove)==0);
Aout = A(notinvolved,keep);
bout = b(notinvolved);
for i = 1:length(less)
for j = 1:length(larger)
Aout = [Aout;A(less(i),keep)/abs(A(less(i),remove)) + A(larger(j),keep)/abs(A(larger(j),remove))];
bout = [bout;b(less(i))+b(larger(j))];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
categorizeproblem.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/categorizeproblem.m
| 19,268 |
utf_8
|
62d7b9118d98a76df49c59aabb69bc3a
|
function [problem,integer_variables,binary_variables,parametric_variables,uncertain_variables,semicont_variables,quad_info] = categorizeproblem(F,P,h,relax,parametric,evaluation,F_vars,exponential_cone)
%categorizeproblem Internal function: tries to determine the type of optimization problem
F = flatten(F);
Counter = length(F.LMIid);
Ftype = zeros(Counter,1);
real_data = 1;
int_data = 0;
interval_data = 0;
bin_data = 0;
par_data = 0;
scn_data = 0;
poly_constraint = 0;
bilin_constraint = 0;
sigm_constraint = 0;
rank_constraint = 0;
rank_objective = 0;
exp_cone = 0;
parametric_variables = [];
kyp_prob = 0;
gkyp_prob = 0;
% ***********************************************
% Setup an empty problem definition
% ***********************************************
problem.objective.linear = 0;
problem.objective.quadratic.convex = 0;
problem.objective.quadratic.nonconvex = 0;
problem.objective.quadratic.nonnegative = 0;
problem.objective.polynomial = 0;
problem.objective.maxdet.convex = 0;
problem.objective.maxdet.nonconvex = 0;
problem.objective.sigmonial = 0;
problem.constraint.equalities.linear = 0;
problem.constraint.equalities.quadratic = 0;
problem.constraint.equalities.polynomial = 0;
problem.constraint.equalities.sigmonial = 0;
problem.constraint.inequalities.elementwise.linear = 0;
problem.constraint.inequalities.elementwise.quadratic.convex = 0;
problem.constraint.inequalities.elementwise.quadratic.nonconvex = 0;
problem.constraint.inequalities.elementwise.sigmonial = 0;
problem.constraint.inequalities.elementwise.polynomial = 0;
problem.constraint.inequalities.semidefinite.linear = 0;
problem.constraint.inequalities.semidefinite.quadratic = 0;
problem.constraint.inequalities.semidefinite.polynomial = 0;
problem.constraint.inequalities.semidefinite.sigmonial = 0;
problem.constraint.inequalities.rank = 0;
problem.constraint.inequalities.secondordercone.linear = 0;
problem.constraint.inequalities.secondordercone.nonlinear = 0;
problem.constraint.inequalities.rotatedsecondordercone = 0;
problem.constraint.inequalities.powercone = 0;
problem.constraint.complementarity.variable = 0;
problem.constraint.complementarity.linear = 0;
problem.constraint.complementarity.nonlinear = 0;
problem.constraint.integer = 0;
problem.constraint.binary = 0;
problem.constraint.semicont = 0;
problem.constraint.sos1 = 0;
problem.constraint.sos2 = 0;
problem.complex = 0;
problem.parametric = parametric;
problem.interval = 0;
problem.evaluation = evaluation;
problem.exponentialcone = exponential_cone;
% ********************************************************
% Make a list of all globally available discrete variables
% ********************************************************
integer_variables = yalmip('intvariables');
binary_variables = yalmip('binvariables');
semicont_variables = yalmip('semicontvariables');
uncertain_variables = yalmip('uncvariables');
for i = 1:Counter
switch F.clauses{i}.type
case 7
integer_variables = union(integer_variables,getvariables(F.clauses{i}.data));
case 8
binary_variables = union(binary_variables,getvariables(F.clauses{i}.data));
case 13
parametric_variables = union(parametric_variables,getvariables(F.clauses{i}.data));
case 52
semicont_variables = union(semicont_variables,getvariables(F.clauses{i}.data));
otherwise
end
end
% ********************************************************
% Logarithmic objective?
% ********************************************************
if ~isempty(P)
problem.objective.maxdet.convex = 1;
problem.objective.maxdet.nonconvex = 1;
problem.objective.maxdet.convex = all(P.gain<=0);
problem.objective.maxdet.nonconvex = any(P.gain>0);
end
%problem.objective.maxdet = ~isempty(P);
% ********************************************************
% Rank variables
% ********************************************************
rank_variables = yalmip('rankvariables');
any_rank_variables = ~isempty(rank_variables);
% ********************************************************
% Make a list of all globally available nonlinear variables
% ********************************************************
[monomtable,variabletype] = yalmip('monomtable');
linear_variables = find(variabletype==0);
nonlinear_variables = find(variabletype~=0);
sigmonial_variables = find(variabletype==4);
if isempty(F_vars)
allvars = getvariables(F);
else
allvars = F_vars;
end
members = ismembcYALMIP(nonlinear_variables,allvars);
any_nonlinear_variables =~isempty(find(members));
any_discrete_variables = ~isempty(integer_variables) | ~isempty(binary_variables) | ~isempty(semicont_variables);
interval_data = isinterval(h);
problem.constraint.equalities.multiterm = 0;
for i = 1:Counter
Fi = F.clauses{i};
% Only real-valued data?
real_data = real_data & isreal(Fi.data);
interval_data = interval_data | isinterval(Fi.data);
% Any discrete variables used
if any_discrete_variables
Fvar = getvariables(Fi.data);
int_data = int_data | any(ismembcYALMIP(Fvar,integer_variables));
bin_data = bin_data | any(ismembcYALMIP(Fvar,binary_variables));
par_data = par_data | any(ismembcYALMIP(Fvar,parametric_variables));
scn_data = scn_data | any(ismembcYALMIP(Fvar,semicont_variables));
end
if any_rank_variables
rank_constraint = rank_constraint | any(ismember(getvariables(Fi.data),rank_variables));
end
% Check for equalities violating GP definition
if problem.constraint.equalities.multiterm == 0
if Fi.type==3
if isempty(strfind(Fi.handle,'Expansion of'))
if multipletermsInEquality(Fi)
problem.constraint.equalities.multiterm = 1;
end
end
end
end
if ~any_nonlinear_variables % No nonlinearly parameterized constraints
switch Fi.type
case {1,9,40}
problem.constraint.inequalities.semidefinite.linear = 1;
case 2
problem.constraint.inequalities.elementwise.linear = 1;
case 3
problem.constraint.equalities.linear = 1;
case {4,54}
problem.constraint.inequalities.secondordercone.linear = 1;
case 5
problem.constraint.inequalities.rotatedsecondordercone = 1;
case 20
problem.constraint.inequalities.powercone = 1;
case 50
problem.constraint.sos2 = 1;
case 51
problem.constraint.sos1 = 1;
case 55
problem.constraint.complementarity.linear = 1;
otherwise
end
else
% Can be nonlinear stuff
vars = getvariables(Fi.data);
usednonlins = find(ismembcYALMIP(nonlinear_variables,vars));
if ~isempty(usednonlins)
usedsigmonials = find(ismember(sigmonial_variables,vars));
if ~isempty(usedsigmonials)
switch Fi.type
case 1
problem.constraint.inequalities.semidefinite.sigmonial = 1;
case 2
problem.constraint.inequalities.elementwise.sigmonial = 1;
case 3
problem.constraint.equalities.sigmonial = 1;
case {4,54}
problem.constraint.inequalities.secondordercone.nonlinear = 1;
case 5
error('Sigmonial RSOCP not supported');
otherwise
error('Report bug in problem classification (sigmonial constraint)');
end
else
%deg = degree(Fi.data);
types = variabletype(getvariables(Fi.data));
if ~any(types)
deg = 1;
elseif any(types==1) || any(types==2)
deg = 2;
else
deg = NaN;
end
switch deg
case 1
switch Fi.type
case 1
problem.constraint.inequalities.semidefinite.linear = 1;
case 2
problem.constraint.inequalities.elementwise.linear = 1;
case 3
problem.constraint.equalities.linear = 1;
case {4,54}
problem.constraint.inequalities.secondordercone.linear = 1;
case 5
problem.constraint.inequalities.rotatedsecondordercone = 1;
case 20
problem.constraint.inequalities.powercone = 1;
otherwise
error('Report bug in problem classification (linear constraint)');
end
case 2
switch Fi.type
case 1
problem.constraint.inequalities.semidefinite.quadratic = 1;
case 2
% FIX : This should be re-used from
% convertconvexquad
convex = 1;
f = Fi.data;f = f(:);
ii = 1;
while convex & ii<=length(f)
[Q,caux,faux,xaux,info] = quaddecomp(f(ii));
if info | any(eig(full(Q)) > 0)
convex = 0;
end
ii= ii + 1;
end
if convex
problem.constraint.inequalities.elementwise.quadratic.convex = 1;
else
problem.constraint.inequalities.elementwise.quadratic.nonconvex = 1;
end
case 3
problem.constraint.equalities.quadratic = 1;
case {4,54}
problem.constraint.inequalities.secondordercone.nonlinear = 1;
case 5
error
case 55
problem.constraint.complementarity.nonlinear = 1;
otherwise
error('Report bug in problem classification (quadratic constraint)');
end
otherwise
switch Fi.type
case 1
problem.constraint.inequalities.semidefinite.polynomial = 1;
case 2
problem.constraint.inequalities.elementwise.polynomial = 1;
case 3
problem.constraint.equalities.polynomial = 1;
case {4,54}
problem.constraint.inequalities.secondordercone.nonlinear = 1;
case 5
% problem.constraint.inequalities.rotatedsecondordercone = 1;
case 55
problem.constraint.complementarity.nonlinear = 1;
otherwise
error('Report bug in problem classification (polynomial constraint)');
end
end
end
else
switch Fi.type
case 1
problem.constraint.inequalities.semidefinite.linear = 1;
case 2
problem.constraint.inequalities.elementwise.linear = 1;
case 3
problem.constraint.equalities.linear = 1;
case {4,54}
problem.constraint.inequalities.secondordercone.linear = 1;
case 5
problem.constraint.inequalities.rotatedsecondordercone = 1;
case 20
problem.constraint.inequalities.powercone = 1;
case 7
problem.constraint.integer = 1;
case 8
problem.constraint.binary = 1;
case 50
problem.constraint.sos2 = 1;
case 51
problem.constraint.sos1 = 1;
case 52
problem.constraint.semicont = 1;
case 55
problem.constraint.complementarity.linear = 1;
otherwise
error('Report bug in problem classification (linear constraint)');
end
end
end
end
if int_data
problem.constraint.integer = 1;
end
if bin_data
problem.constraint.binary = 1;
end
if scn_data
problem.constraint.semicont = 1;
end
if ~real_data
problem.complex = 1;
end
if interval_data
problem.interval = 1;
end
if rank_constraint
problem.constraint.inequalities.rank = 1;
end
if ~isempty(uncertain_variables)
problem.uncertain = 1;
end
if (relax==1) | (relax==3)
problem.constraint.equalities.linear = problem.constraint.equalities.linear | problem.constraint.equalities.quadratic | problem.constraint.equalities.polynomial | problem.constraint.equalities.sigmonial;
problem.constraint.equalities.quadratic = 0;
problem.constraint.equalities.polynomial = 0;
problem.constraint.equalities.sigmonial = 0;
problem.constraint.inequalities.elementwise.linear = problem.constraint.inequalities.elementwise.linear | problem.constraint.inequalities.elementwise.quadratic.convex | problem.constraint.inequalities.elementwise.quadratic.nonconvex | problem.constraint.inequalities.elementwise.sigmonial | problem.constraint.inequalities.elementwise.polynomial;
problem.constraint.inequalities.elementwise.quadratic.convex = 0;
problem.constraint.inequalities.elementwise.quadratic.nonconvex = 0;
problem.constraint.inequalities.elementwise.sigmonial = 0;
problem.constraint.inequalities.elementwise.polynomial = 0;
problem.constraint.inequalities.semidefinite.linear = problem.constraint.inequalities.semidefinite.linear | problem.constraint.inequalities.semidefinite.quadratic | problem.constraint.inequalities.semidefinite.polynomial | problem.constraint.inequalities.semidefinite.sigmonial;
problem.constraint.inequalities.semidefinite.quadratic = 0;
problem.constraint.inequalities.semidefinite.polynomial = 0;
problem.constraint.inequalities.semidefinite.sigmonial = 0;
problem.constraint.inequalities.elementwise.secondordercone.linear = problem.constraint.inequalities.secondordercone.linear | problem.constraint.inequalities.secondordercone.nonlinear ;
problem.constraint.inequalities.elementwise.secondordercone.nonlinear = 0;
poly_constraint = 0;
bilin_constraint = 0;
sigm_constraint = 0;
problem.evaluation = 0;
problem.exponentialcone = 0;
end
% Analyse the objective function
quad_info = [];
if isa(h,'sdpvar')
h_is_linear = is(h,'linear');
else
h_is_linear = 0;
end
if (~isempty(h)) & ~h_is_linear &~(relax==1) &~(relax==3)
if ~(isempty(binary_variables) & isempty(integer_variables))
h_var = depends(h);
if any(ismember(h_var,binary_variables))
problem.constraint.binary = 1;
end
if any(ismember(h_var,integer_variables))
problem.constraint.integer = 1;
end
end
if any(ismember(getvariables(h),sigmonial_variables))
problem.objective.sigmonial = 1;
else
[Q,c,f,x,info] = quaddecomp(h);
if ~isreal(Q) % Numerical noise common on imaginary parts
Qr = real(Q);
Qi = imag(Q);
Qr(abs(Qr)<1e-10) = 0;
Qi(abs(Qi)<1e-10) = 0;
cr = real(c);
ci = imag(c);
cr(abs(cr)<1e-10) = 0;
ci(abs(ci)<1e-10) = 0;
Q = Qr + sqrt(-1)*Qi;
c = cr + sqrt(-1)*ci;
end
if info==0
% OK, we have some kind of quadratic expression
% Find involved variables
if all(nonzeros(Q)>=0)
problem.objective.quadratic.nonnegative = 1;
else
problem.objective.quadratic.nonnegative = 0;
end
index = find(any(Q,2));
if length(index) < length(Q)
Qsub = Q(index,index);
[Rsub,p]=chol(Qsub);
if p
% Maybe just some silly numerics
[Rsub,p]=chol(Qsub+1e-12*eye(length(Qsub)));
end
if p==0
[i,j,k] = find(Rsub);
R = sparse((i),index(j),k,length(Qsub),length(Q));
% R = Q*0;
% R(index,index) = Rsub;
else
R = [];
end
else
[R,p]=chol(Q);
end
if p~=0
if any(~diag(Q) & any(triu(Q,1),2))
% Diagonal zero but non-zero outside, cannot be convex
else
Q = full(Q);
if min(eig(Q))>=-1e-10
p=0;
try
[U,S,V]=svd(Q);
catch
[U,S,V]=svd(full(Q));
end
i = find(diag(S)>1e-10);
R = sqrt(S(1:max(i),1:max(i)))*V(:,1:max(i))';
end
end
end
if p==0
problem.objective.quadratic.convex = 1;
else
problem.objective.quadratic.nonconvex = 1;
end
quad_info.Q = Q;
quad_info.c = c;
quad_info.f = f;
quad_info.x = x;
quad_info.R = R;
quad_info.p = p;
else
problem.objective.polynomial = 1;
end
end
else
problem.objective.linear = ~isempty(h);
end
if (relax==1) | (relax==2)
problem.constraint.integer = 0;
problem.constraint.binary = 0;
problem.constraint.sos2 = 0;
problem.constraint.semicont = 0;
int_data = 0;
bin_data = 0;
scn_data = 0;
end
function p = multipletermsInEquality(Fi);
p = 0;
Fi = sdpvar(Fi.data);
if length(getvariables(Fi))>1
B = getbase(Fi);
if ~isreal(B)
B = [real(B);imag(B)];
end
p = any(sum(B | B,2)-(B(:,1) == 0) > 1);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
Polyhedron.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/Polyhedron.m
| 2,402 |
utf_8
|
30f5cf13a964070f9b800e10d49a372f
|
function [P,x] = polyhedron(X,options)
% polyhedron Converts constraint to MPT polyhedron object
%
% P = polyhedron(F)
% [P,x] = polyhedron(F)
%
% P : polyhedron object (Requires the Multi-parametric Toolbox)
% x : sdpvar object defining the variables in the polyhedron
% F : Constraint object with linear inequalities
if nargin < 2
options = sdpsettings;
elseif isempty(options)
options = sdpsettings;
end
[p,recoverdata,solver,diagnostic,F] = compileinterfacedata(X,[],[],[],options,0);
if p.K.q(1) > 0 | p.K.s(1) > 0 | any(p.variabletype)
error('Polyhedron can only be applied to MILP-representable constraints.')
end
if isempty(p.binary_variables) & isempty(p.integer_variables)
Aeq = -p.F_struc(1:p.K.f,2:end);
beq = p.F_struc(1:p.K.f,1);
A = -p.F_struc(p.K.f+1:end,2:end);
b = p.F_struc(p.K.f+1:end,1);
P = Polyhedron('A',A,'b',b,'Ae',Aeq,'be',beq);
x = recover(p.used_variables);
else
nBin = length(p.binary_variables);
[pBinary,removeEQ,removeLP] = extractOnly(p,p.binary_variables);
p.F_struc = [p.F_struc(removeEQ,:);p.F_struc(p.K.f+removeLP,:)];
p.K.f = length(removeEQ);
p.K.l = length(removeLP);
p.used_variables(p.binary_variables)=[];
x = recover(p.used_variables);
P = [];
for i = 0:2^nBin-1;
comb = dec2decbin(i,nBin);
if checkfeasiblefast(pBinary,comb(:),1e-6)
pi = p;
H = -p.F_struc(:,2:end);
K = p.F_struc(:,1);
K = K-H(:,p.binary_variables)*comb(:);
H(:,p.binary_variables)=[];
Aeq = H(1:p.K.f,:);
beq = H(1:p.K.f);
A = H(p.K.f+1:end,:);
b = K(p.K.f+1:end);
Pi = Polyhedron('A',A,'b',b,'Ae',Aeq,'be',beq);
P = [P Pi];
end
end
end
function pLP = extractLP(p);
pLP = p;
pLP.F_struc = pLP.F_struc(1:p.K.f+p.K.l,:);
pLP.K.q = 0;
pLP.K.s = 0;
function [pRed,removeEQ,removeLP] = extractOnly(p,these);
pRed = p;
p.F_struc(:,1+these) = 0;
removeEQ = find(any(p.F_struc(1:pRed.K.f,2:end),2));
removeLP = find(any(p.F_struc(1+pRed.K.f:end,2:end),2));
pRed.F_struc(pRed.K.f+removeLP,:)=[];
pRed.F_struc(removeEQ,:)=[];
pRed.K.f = pRed.K.f - length(removeEQ);
pRed.K.l = pRed.K.l - length(removeLP);
pRed.F_struc = pRed.F_struc(:,[1 1+these]);
pRed.lb = pRed.lb(these);
pRed.ub = pRed.ub(these);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
lmi2sedumistruct.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@lmi/lmi2sedumistruct.m
| 20,660 |
utf_8
|
29d3ff75fe3b58db06487e773878882b
|
function [F_struc,K,KCut,schur_funs,schur_data,schur_variables] = lmi2sedumistruct(F)
%lmi2sedumistruct Internal function: Converts LMI to format needed in SeDuMi
nvars = yalmip('nvars'); %Needed lot'sa times...
% We first browse to see what we have got and the
% dimension of F_struc (massive speed improvement)
F = flatten(F);
type_of_constraint = zeros(length(F.LMIid),1);%zeros(size(F.clauses,2),1);
any_cuts = 0;
for i = 1:length(F.LMIid)%size(F.clauses,2)
type_of_constraint(i) = F.clauses{i}.type;
if F.clauses{i}.cut
any_cuts = 1;
end
end
F_struc = [];
schur_data = [];
schur_funs = [];
schur_variables = [];
sdp_con = find(type_of_constraint == 1 | type_of_constraint == 9 | type_of_constraint == 40);
sdpstack_con = find(type_of_constraint == 57);
lin_con = find(type_of_constraint == 2 | type_of_constraint == 12);
equ_con = find(type_of_constraint == 3);
qdr_con = find(type_of_constraint == 4);
mqdr_con = find(type_of_constraint == 54);
rlo_con = find(type_of_constraint == 5);
pow_con = find(type_of_constraint == 20);
sos2_con = find(type_of_constraint == 50);
sos1_con = find(type_of_constraint == 51);
cmp_con = find(type_of_constraint == 55);
% SeDuMi struct
K.f = 0; % Linear equality
K.l = 0; % Linear inequality
K.c = 0; % Complementarity constraints
K.q = 0; % SOCP
K.r = 0; % Rotated SOCP (obsolete)
K.p = 0; % Power cone
K.s = 0; % SDP cone
K.rank = [];
K.dualrank = [];
K.scomplex = [];
K.xcomplex = [];
KCut.f = [];
KCut.l = [];
KCut.c = [];
KCut.q = [];
KCut.r = [];
KCut.p = [];
KCut.s = [];
top = 1;
localtop = 1;
% In the first part of the code, we will work with a transposed version of
% the vectorized constraints, i.e. constraints are added by adding columns,
% wheras the final output will be transposed
% Linear equality constraints
alljx = [];
allix = [];
allsx = [];
block = 0;
for i = 1:length(equ_con)
constraints = equ_con(i);
data = getbase(F.clauses{constraints}.data);
% [n,m] = size(F.clauses{constraints}.data);
% Which variables are needed in this constraint
lmi_variables = getvariables(F.clauses{constraints}.data);
if isreal(data)
ntimesm = size(data,1);
%ntimesm = n*m; %Just as well pre-calc
else
% Complex constraint, Expand to real and Imag
ntimesm = 2*size(data,1);
%ntimesm = 2*n*m; %Just as well pre-calc
data = [real(data);imag(data)];
end
mapX = [1 1+lmi_variables];
[ix,jx,sx] = find(data);
%F_structemp = sparse(mapX(jx),ix,sx,1+nvars,ntimesm);
%F_struc = [F_struc F_structemp];
alljx = [alljx mapX(jx)];
allix = [allix ix(:)'+block];block = block + ntimesm;
allsx = [allsx sx(:)'];
if F.clauses{constraints}.cut
KCut.f = [KCut.f localtop:localtop+ntimesm-1];
end
localtop = localtop+ntimesm;
top = top+ntimesm;
K.f = K.f+ntimesm;
end
F_struc = sparse(alljx,allix,allsx,1+nvars,block);
% Linear inequality constraints
localtop = 1;
% Cuts are not dealt with correctly in the recurisve code. Use slower
% version. Test with bmibnb_qcqp5
if any_cuts
for i = 1:length(lin_con)
constraints = lin_con(i);
data = getbase(F.clauses{constraints}.data);
[n,m] = size(F.clauses{constraints}.data);
% Which variables are needed in this constraint
lmi_variables = getvariables(F.clauses{constraints}.data);
% Convert to real problem
if isreal(data)
ntimesm = n*m; %Just as well pre-calc
else
% Complex constraint, Expand to real and Imag
ntimesm = 2*n*m; %Just as well pre-calc
data = [real(data);imag(data)];
end
% Add numerical data to complete problem setup
mapX = [1 1+lmi_variables];
[ix,jx,sx] = find(data);
F_structemp = sparse(mapX(jx),ix,sx,1+nvars,ntimesm);
F_struc = [F_struc F_structemp];
if F.clauses{constraints}.cut
KCut.l = [KCut.l localtop:localtop+ntimesm-1];
end
localtop = localtop+ntimesm;
top = top+ntimesm;
K.l = K.l+ntimesm;
end
else
if length(lin_con)>0
[F_struc,K,KCut] = recursive_lp_fix(F,F_struc,K,KCut,lin_con,nvars,4,1);
end
end
for i = 1:length(cmp_con)
constraints = cmp_con(i);
[n,m] = size(F.clauses{constraints}.data);
ntimesm = n*m; %Just as well pre-calc
% Which variables are needed in this constraint
lmi_variables = getvariables(F.clauses{constraints}.data);
% We allocate the structure blockwise...
F_structemp = spalloc(1+nvars,ntimesm,0);
% Add these rows only
F_structemp([1 1+lmi_variables(:)'],:)= getbase(F.clauses{constraints}.data).';
% ...and add them together (efficient for large structures)
F_struc = [F_struc F_structemp];
top = top+ntimesm;
K.c(i) = n;
end
qdr_con = union(qdr_con,mqdr_con);
if length(qdr_con) > 0
[F_struc,K,KCut] = recursive_socp_fix(F,F_struc,K,KCut,qdr_con,nvars,8,1);
end
% %
% if length(mqdr_con) > 0
% [F_struc,K,KCut] = recursive_msocp_fix(F,F_struc,K,KCut,mqdr_con,nvars,inf,1);
% end
% Rotated Lorentz cone constraints
for i = 1:length(rlo_con)
constraints = rlo_con(i);
[n,m] = size(F.clauses{constraints}.data);
ntimesm = n*m; %Just as well pre-calc
% Which variables are needed in this constraint
lmi_variables = getvariables(F.clauses{constraints}.data);
% We allocate the structure blockwise...
F_structemp = spalloc(1+nvars,ntimesm,0);
% Add these rows only
F_structemp([1 1+lmi_variables(:)'],:)= getbase(F.clauses{constraints}.data).';
% ...and add them together (efficient for large structures)
F_struc = [F_struc F_structemp];
top = top+ntimesm;
K.r(i) = n;
end
% Power cone constraints
for i = 1:length(pow_con)
constraints = pow_con(i);
[n,m] = size(F.clauses{constraints}.data);
ntimesm = n*m; %Just as well pre-calc
% Should always have size 4
if n~=4
error('Power cone constraint has strange dimension')
end
% Which variables are needed in this constraint
lmi_variables = getvariables(F.clauses{constraints}.data);
% We allocate the structure blockwise...
F_structemp = spalloc(1+nvars,ntimesm,0);
% Add these rows only
F_structemp([1 1+lmi_variables(:)'],:)= getbase(F.clauses{constraints}.data).';
alpha = F_structemp(1,end);
F_structemp(:,end)=[];
% ...and add them together (efficient for large structures)
F_struc = [F_struc F_structemp];
top = top+ntimesm;
K.p(i) = alpha;
end
% Semidefinite constraints
% We append the recursively in order to speed up construction
% of problems with a lot of medium size SDPs
any_schur = 0;
for j = sdp_con(:)'
if ~isempty(F.clauses{j}.schurfun)
any_schur = 1;
break
end
end
if any_schur
[F_struc,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,F_struc,K,KCut,schur_funs,schur_data,schur_variables,sdp_con,nvars,inf,1);
else
[F_struc,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,F_struc,K,KCut,schur_funs,schur_data,schur_variables,sdp_con,nvars,8,1);
end
% Now go back to YALMIP default orientation constraints x variables
F_struc = F_struc.';
% Now fix things for the rank constraint
% This is currently a hack...
% Should not be in this file
[rank_variables,dual_rank_variables] = yalmip('rankvariables');
if ~isempty(rank_variables)
used_in = find(sum(abs(F_struc(:,1+rank_variables)),2));
if ~isempty(used_in)
if used_in >=1+K.f & used_in < 1+K.l+K.f
for i = 1:length(used_in)
[ii,jj,kk] = find(F_struc(used_in(i),:));
if length(ii)==2 & kk(2)<1
r = floor(kk(1));
var = jj(2)-1;
extstruct = yalmip('extstruct',var);
X = extstruct.arg{1};
if issymmetric(X)
F_structemp = sedumize(X,nvars);
else
error('Only symmetric matrices can be rank constrained.')
end
F_struc = [F_struc;F_structemp];
if isequal(K.s,0)
K.s(1,1) = size(extstruct.arg{1},1);
else
K.s(1,end+1) = size(extstruct.arg{1},1);
end
K.rank(1,end+1) = min(r,K.s(end));
else
error('This rank constraint is not supported (only supports rank(X) < r)')
end
end
% Remove the nonlinear operator constraints
F_struc(used_in,:) = [];
K.l = K.l - length(used_in);
else
error('You have added a rank constraint on an equality constraint, or a scalar expression?!')
end
end
end
if ~isempty(sos2_con) | ~isempty(sos1_con)
K.sos.type = [];
K.sos.variables = {};
K.sos.weight = {};
for i = sos2_con(:)'
K.sos.type = [K.sos.type '2'];
K.sos.variables{end+1} = getvariables(F.clauses{i}.data);
K.sos.variables{end} = K.sos.variables{end}(:);
temp = struct(F.clauses{i}.data);
K.sos.weight{end+1} = temp.extra.sosweights;
end
for i = sos1_con(:)'
K.sos.type = [K.sos.type '1'];
K.sos.variables{end+1} = getvariables(F.clauses{i}.data);
K.sos.variables{end} = K.sos.variables{end}(:);
temp = struct(F.clauses{i}.data);
K.sos.weight{end+1} = temp.extra.sosweights;
end
else
K.sos.type = [];
K.sos.variables = [];
K.sos.weight = [];
end
if ~isempty(dual_rank_variables)
used_in = find(sum(abs(F_struc(:,1+dual_rank_variables)),2));
if ~isempty(used_in)
if used_in >=1+K.f & used_in < 1+K.l+K.f
for i = 1:length(used_in)
[ii,jj,kk] = find(F_struc(used_in(i),:));
if length(ii)==2 & kk(2)<1
r = floor(kk(1));
var = jj(2)-1;
extstruct = yalmip('extstruct',var);
X = extstruct.arg{1};
id = getlmiid(X);
inlist=getlmiid(F);
index=find(id==inlist);
if ~isempty(index)
K.rank(1,index) = min(r,K.s(index));
end
else
error('This rank constraint is not supported (only supports rank(X) < r)')
end
end
% Remove the nonlinear operator constraints
F_struc(used_in,:) = [];
K.l = K.l - length(used_in);
else
error('You have added a rank constraint on an equality constraint, or a scalar expression?!')
end
end
end
function F_structemp = sedumize(Fi,nvars)
Fibase = getbase(Fi);
[n,m] = size(Fi);
ntimesm = n*m;
lmi_variables = getvariables(Fi);
[ix,jx,sx] = find(Fibase);
mapX = [1 1+lmi_variables];
F_structemp = sparse(ix,mapX(jx),sx,ntimesm,1+nvars);
function [F_struc,K,KCut] = recursive_lp_fix(F,F_struc,K,KCut,lp_con,nvars,maxnlp,startindex)
% Check if we should recurse
if length(lp_con)>=2*maxnlp
% recursing costs, so do 4 in one step
ind = 1+ceil(length(lp_con)*(0:0.25:1));
[F_struc1,K,KCut] = recursive_lp_fix(F,[],K,KCut,lp_con(ind(1):ind(2)-1),nvars,maxnlp,startindex+ind(1)-1);
[F_struc2,K,KCut] = recursive_lp_fix(F,[],K,KCut,lp_con(ind(2):ind(3)-1),nvars,maxnlp,startindex+ind(2)-1);
[F_struc3,K,KCut] = recursive_lp_fix(F,[],K,KCut,lp_con(ind(3):ind(4)-1),nvars,maxnlp,startindex+ind(3)-1);
[F_struc4,K,KCut] = recursive_lp_fix(F,[],K,KCut,lp_con(ind(4):ind(5)-1),nvars,maxnlp,startindex+ind(4)-1);
F_struc = [F_struc F_struc1 F_struc2 F_struc3 F_struc4];
return
elseif length(lp_con)>=maxnlp
mid = ceil(length(lp_con)/2);
[F_struc1,K,KCut] = recursive_lp_fix(F,[],K,KCut,lp_con(1:mid),nvars,maxnlp,startindex);
[F_struc2,K,KCut] = recursive_lp_fix(F,[],K,KCut,lp_con(mid+1:end),nvars,maxnlp,startindex+mid);
F_struc = [F_struc F_struc1 F_struc2];
return
end
oldF_struc = F_struc;
F_struc = [];
for i = 1:length(lp_con)
constraints = lp_con(i);
Fi = F.clauses{constraints}.data;
Fibase = getbase(Fi);
% [n,m] = size(Fi);
% Convert to real problem
if isreal(Fibase)
ntimesm = size(Fibase,1);
%ntimesm = n*m; %Just as well pre-calc
else
% Complex constraint, Expand to real and Imag
ntimesm = 2*size(Fibase,1);
%ntimesm = 2*n*m; %Just as well pre-calc
Fibase = [real(Fibase);imag(Fibase)];
end
% Which variables are needed in this constraint
lmi_variables = getvariables(Fi);
mapX = [1 1+lmi_variables];
% simpleMap = all(mapX==1:length(mapX));
simpleMap = 0;%all(diff(lmi_variables)==1);
% highly optimized concatenation...
if size(Fibase) == [ntimesm 1+nvars] & simpleMap
F_struc = [F_struc Fibase'];
elseif simpleMap
vStart = lmi_variables(1);
vEnd = lmi_variables(end);
if vStart == 1
F_struc = [F_struc [Fibase spalloc(n,nvars-vEnd,0)]'];
else
F_struc = [F_struc [Fibase(:,1) spalloc(n,vStart-1,0) Fibase(:,2:end) spalloc(n,nvars-vEnd,0)]'];
end
else
[ix,jx,sx] = find(Fibase);
F_structemp = sparse(mapX(jx),ix,sx,1+nvars,ntimesm);
F_struc = [F_struc F_structemp];
end
if F.clauses{constraints}.cut
KCut.l = [KCut.l i+startindex-1:i+startindex-1+n];
end
K.l(i+startindex-1) = ntimesm;
end
K.l = sum(K.l);
F_struc = [oldF_struc F_struc];
function [F_struc,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,F_struc,K,KCut,schur_funs,schur_data,schur_variables,sdp_con,nvars,maxnsdp,startindex)
if isempty(sdp_con)
return
% Check if we should recurse
elseif length(sdp_con)>2*maxnsdp
% recursing costs, so do 4 in one step
ind = 1+ceil(length(sdp_con)*(0:0.25:1));
[F_struc1,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,[],K,KCut,schur_funs,schur_data,schur_variables,sdp_con(ind(1):ind(2)-1),nvars,maxnsdp,startindex+ind(1)-1);
[F_struc2,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,[],K,KCut,schur_funs,schur_data,schur_variables,sdp_con(ind(2):ind(3)-1),nvars,maxnsdp,startindex+ind(2)-1);
[F_struc3,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,[],K,KCut,schur_funs,schur_data,schur_variables,sdp_con(ind(3):ind(4)-1),nvars,maxnsdp,startindex+ind(3)-1);
[F_struc4,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,[],K,KCut,schur_funs,schur_data,schur_variables,sdp_con(ind(4):ind(5)-1),nvars,maxnsdp,startindex+ind(4)-1);
F_struc = [F_struc F_struc1 F_struc2 F_struc3 F_struc4];
return
elseif length(sdp_con)>maxnsdp
mid = ceil(length(sdp_con)/2);
[F_struc1,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,[],K,KCut,schur_funs,schur_data,schur_variables,sdp_con(1:mid),nvars,maxnsdp,startindex);
[F_struc2,K,KCut,schur_funs,schur_data,schur_variables] = recursive_sdp_fix(F,[],K,KCut,schur_funs,schur_data,schur_variables,sdp_con(mid+1:end),nvars,maxnsdp,startindex+mid);
F_struc = [F_struc F_struc1 F_struc2];
return
end
oldF_struc = F_struc;
F_struc = [];
for i = 1:length(sdp_con)
constraints = sdp_con(i);
% Simple data
Fi = F.clauses{constraints};
X = Fi.data;
lmi_variables = getvariables(X);
[n,m] = size(X);
ntimesm = n*m; %Just as well pre-calc
if is(X,'gkyp')
ss = struct(X);
nn = size(F.clauses{1}.data,1);
bb = getbase(ss.extra.M);
Mbase = [];
for ib = 1:size(bb,2)-1
Mbase{ib} = (reshape(bb(:,ib+1),nn,nn));
end
for ip = 1:length(ss.extra.P)
Pvars{ip} = getvariables(ss.extra.P{ip});
end
schur_data{i,1} = {ss.extra.K, ss.extra.Phi,Mbase, ss.extra.negated, getvariables(ss.extra.M),Pvars};
schur_funs{i,1} = 'HKM_schur_GKYP';
schur_variables{i,1} = lmi_variables;
elseif ~isempty(Fi.schurfun)
schur_data{i,1} = Fi.schurdata;
schur_funs{i,1} = Fi.schurfun;
schur_variables{i,1} = lmi_variables;
end
% get numerics
Fibase = getbase(X);
% now delete old data to save memory
% F.clauses{constraints}.data=[];
% Which variables are needed in this constraint
%lmi_variables = getvariables(Fi);
if length(lmi_variables) == nvars
% No remap needed
F_structemp = Fibase';
else
mapX = [1 1+lmi_variables];
[ix,jx,sx] = find(Fibase);
clear Fibase;
% Seems to be faster to transpose generation
F_structemp = sparse(ix,mapX(jx),sx,ntimesm,1+nvars)';
clear jx ix sx
end
F_struc = [F_struc F_structemp];
if Fi.cut
KCut.s = [KCut.s i+startindex-1];
end
K.s(i+startindex-1) = n;
K.rank(i+startindex-1) = n;
K.dualrank(i+startindex-1) = n;
% Check for a complex structure
if ~isreal(F_structemp)
K.scomplex = [K.scomplex i+startindex-1];
end
clear F_structemp
end
F_struc = [oldF_struc F_struc];
function [F_struc,K,KCut] = recursive_socp_fix(F,F_struc,K,KCut,qdr_con,nvars,maxnsocp,startindex);
% Check if we should recurse
if length(qdr_con)>2*maxnsocp
% recursing costs, so do 4 in one step
ind = 1+ceil(length(qdr_con)*(0:0.25:1));
[F_struc1,K1,KCut] = recursive_socp_fix(F,[],K,KCut,qdr_con(ind(1):ind(2)-1),nvars,maxnsocp,startindex+ind(1)-1);
[F_struc2,K2,KCut] = recursive_socp_fix(F,[],K,KCut,qdr_con(ind(2):ind(3)-1),nvars,maxnsocp,startindex+ind(2)-1);
[F_struc3,K3,KCut] = recursive_socp_fix(F,[],K,KCut,qdr_con(ind(3):ind(4)-1),nvars,maxnsocp,startindex+ind(3)-1);
[F_struc4,K4,KCut] = recursive_socp_fix(F,[],K,KCut,qdr_con(ind(4):ind(5)-1),nvars,maxnsocp,startindex+ind(4)-1);
F_struc = [F_struc F_struc1 F_struc2 F_struc3 F_struc4];
K.q = [K1.q K2.q K3.q K4.q];
K.q(K.q==0)=[];
return
elseif length(qdr_con)>maxnsocp
mid = ceil(length(qdr_con)/2);
[F_struc1,K1,KCut] = recursive_socp_fix(F,[],K,KCut,qdr_con(1:mid),nvars,maxnsocp,startindex);
[F_struc2,K2,KCut] = recursive_socp_fix(F,[],K,KCut,qdr_con(mid+1:end),nvars,maxnsocp,startindex+mid);
F_struc = [F_struc F_struc1 F_struc2];
K.q = [K1.q K2.q];
K.q(K.q==0)=[];
return
end
% second order cone constraints
for i = 1:length(qdr_con)
constraints = qdr_con(i);
[n,m] = size(F.clauses{constraints}.data);
ntimesm = n*m; %Just as well pre-calc
% Which variables are needed in this constraint
lmi_variables = getvariables(F.clauses{constraints}.data);
data = getbase(F.clauses{constraints}.data);
if isreal(data)
mapX = [1 1+lmi_variables];
[ix,jx,sx] = find(data);
F_structemp = sparse(mapX(jx),ix,sx,1+nvars,ntimesm);
else
n = n+(n-1);
ntimesm = n*m;
F_structemp = spalloc(ntimesm,1+nvars,0);
data = [data(1,:);real(data(2:end,:));imag(data(2:end,:))];
F_structemp(:,[1 1+lmi_variables(:)'])= data;
F_structemp = F_structemp';
end
% ...and add them together (efficient for large structures)
F_struc = [F_struc F_structemp];
% K.q(i+startindex-1) = n;
K.q = [K.q ones(1,m)*n];
end
K.q(K.q==0)=[];
function [F_struc,K,KCut] = recursive_msocp_fix(F,F_struc,K,KCut,qdr_con,nvars,maxnsocp,startindex);
if isequal(K.q,0)
K.q = [];
end
% second order cone constraints
for i = 1:length(qdr_con)
constraints = qdr_con(i);
[n,m] = size(F.clauses{constraints}.data);
ntimesm = n*m; %Just as well pre-calc
% Which variables are needed in this constraint
lmi_variables = getvariables(F.clauses{constraints}.data);
data = getbase(F.clauses{constraints}.data);
if isreal(data)
mapX = [1 1+lmi_variables];
[ix,jx,sx] = find(data);
F_structemp = sparse(mapX(jx),ix,sx,1+nvars,ntimesm);
else
n = n+(n-1);
ntimesm = n*m;
F_structemp = spalloc(ntimesm,1+nvars,0);
data = [data(1,:);real(data(2:end,:));imag(data(2:end,:))];
F_structemp(:,[1 1+lmi_variables(:)'])= data;
F_structemp = F_structemp';
end
% ...and add them together (efficient for large structures)
F_struc = [F_struc F_structemp];
K.q = [K.q ones(1,m)*n];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
plot.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/plot.m
| 3,229 |
utf_8
|
dfbeaac5398f6b4128ffe8d0b28117f3
|
function Y=plot(varargin)
%PLOT (overloaded)
% Fast version for plotting simple PWA objects
if nargin == 1
X = varargin{1};
if isa(varargin{1},'sdpvar')
if length(X) == 1
if isequal(full(getbase(X)),[0 1])
extstruct = yalmip('extstruct',getvariables(X));
if ~isempty(extstruct)
if isequal(extstruct.fcn,'pwa_yalmip') | isequal(extstruct.fcn,'pwq_yalmip')%#ok
switch extstruct.arg{3}
case ''
otherwise
Pn = polytope; Bi = {}; Ci = {};
index = extstruct.arg{5};
for i = 1:length(extstruct.arg{1})
% Pick out row
for j = 1:length(extstruct.arg{1}{i}.Bi)
extstruct.arg{1}{i}.Bi{j} = extstruct.arg{1}{i}.Bi{j}(index,:);
extstruct.arg{1}{i}.Ci{j} = extstruct.arg{1}{i}.Ci{j}(index,:);
end
if isempty(extstruct.arg{1}{i}.Ai{1})
Pn = [Pn extstruct.arg{1}{i}.Pn];
Bi = cat(2, Bi, extstruct.arg{1}{i}.Bi);
Ci = cat(2, Ci, extstruct.arg{1}{i}.Ci);
else
if nnz([extstruct.arg{1}{i}.Ai{:}]) == 0
Pn = [Pn extstruct.arg{1}{i}.Pn];
Bi = cat(2, Bi, extstruct.arg{1}{i}.Bi);
Ci = cat(2, Ci, extstruct.arg{1}{i}.Ci);
else
hold on
mpt_plotPWQ(extstruct.arg{1}{i}.Pn, ...
extstruct.arg{1}{i}.Ai, ...
extstruct.arg{1}{i}.Bi, ...
extstruct.arg{1}{i}.Ci, []);
hold off
end
end
end
if ~isempty(Bi),
mpt_plotPWA(Pn, Bi, Ci);
end
drawnow
return
end
end
end
end
end
end
end
% More complex expression. Get epi-graph model
% project to our variables, and extract defining facets
if nargin == 1
[p,Bi,Ci,Pn,Pfinal] = pwa(varargin{1});%#ok
elseif isa(varargin{2},'lmi')
[p,Bi,Ci,Pn,Pfinal] = pwa(varargin{1},varargin{2});%#ok
else
error('Second argument should be a domain defining SET object.');
end
if nargout>0
Y = mpt_plotPWA(Pn,Bi,Ci);
else
mpt_plotPWA(Pn,Bi,Ci);
end
function S = extractrow(S,index)
for i = 1:length(S)
S{i} = S{i}(index,:);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
subsasgn.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/subsasgn.m
| 7,395 |
utf_8
|
0dc57809e264cdd2678ba09ef96ecf94
|
function y = subsasgn(X,I,Y)
%SUBASGN (overloaded)
try
if strcmp('()',I.type)
X_is_spdvar = isa(X,'sdpvar');
Y_is_spdvar = isa(Y,'sdpvar');
if any(I.subs{1} <=0)
error('Index into matrix is negative or zero.');
end
switch 2*X_is_spdvar+Y_is_spdvar
case 1
% This code does not work properly
% Only work if b is undefined!!?!!
% generally ugly code...
y = Y;
[n_y,m_y] = size(Y);
y_lmi_variables = y.lmi_variables;
try
X0 = sparse(subsasgn(full(X),I,full(reshape(Y.basis(:,1),n_y,m_y))));
[n_x,m_x] = size(X0);
y.basis = reshape(X0,n_x*m_x,1);
X = full(X)*0;
for i = 1:length(y_lmi_variables)
X0 = full(sparse(subsasgn(X,I,full(reshape(Y.basis(:,i+1),n_y,m_y)))));
y.basis(:,i+1) = reshape(X0,n_x*m_x,1);
end
y.dim(1) = n_x;
y.dim(2) = m_x;
% Reset info about conic terms
y.conicinfo = [0 0];
catch
error(lasterr)
end
case 2
if ~isempty(Y)
Y = sparse(Y);
end
y = X;
% Special code for speed
% elements in vector replaced with constants
if min(X.dim(1),X.dim(2))==1 & (length(I.subs)==1)
y = X;
y.basis(I.subs{1},1) = Y;
y.basis(I.subs{1},2:end) = 0;
y = clean(y);
% Reset info about conic terms
if isa(y,'sdpvar')
y.conicinfo = [0 0];
end
return;
end
x_lmi_variables = X.lmi_variables;
lmi_variables = [];
% y.basis = [];
n = y.dim(1);
m = y.dim(2);
subX = sparse(subsasgn(full(reshape(X.basis(:,1),n,m)),I,Y));
y.basis = subX(:);
j = 1;
Z = 0*Y;
for i = 1:length(x_lmi_variables)
subX = sparse(subsasgn(full(reshape(X.basis(:,i+1),n,m)),I,Z));
if (norm(subX,inf)>0)
y.basis(:,j+1) = subX(:);
lmi_variables = [lmi_variables x_lmi_variables(i)];
j = j+1;
end
end
y.dim(1) = size(subX,1);
y.dim(2) = size(subX,2);
if isempty(lmi_variables) % Convert back to double!!
y=full(reshape(y.basis(:,1),y.dim(1),y.dim(2)));
return
else %Nope, still a sdpvar
y.lmi_variables = lmi_variables;
% Reset info about conic terms
y.conicinfo = [0 0];
end
case 3
z = X;
x_lmi_variables = X.lmi_variables;
y_lmi_variables = Y.lmi_variables;
% In a first run, we fix the constant term and null terms in the X basis
lmi_variables = [];
nx = X.dim(1);
mx = X.dim(2);
ny = Y.dim(1);
my = Y.dim(2);
if (mx==1) & (my == 1) & isempty(setdiff(y_lmi_variables,x_lmi_variables)) & (max(I.subs{1}) < nx);
% Fast specialized code for Didier
y = specialcode(X,Y,I);
return
end
% subX = sparse(subsasgn(full(reshape(X.basis(:,1),nx,mx)),I,reshape(Y.basis(:,1),ny,my)));
subX = subsasgn(reshape(X.basis(:,1),nx,mx),I,reshape(Y.basis(:,1),ny,my));
z.basis = subX(:);
j = 1;
yz = 0*reshape(Y.basis(:,1),ny,my);
for i = 1:length(x_lmi_variables)
% subX = sparse(subsasgn(full(reshape(X.basis(:,i+1),nx,mx)),I,yz));
subX = subsasgn(reshape(X.basis(:,i+1),nx,mx),I,yz);
if (norm(subX,inf)>0)
z.basis(:,j+1) = subX(:);
lmi_variables = [lmi_variables x_lmi_variables(i)];
j = j+1;
end
end
z.lmi_variables=lmi_variables;
all_lmi_variables = union(lmi_variables,y_lmi_variables);
in_z = ismembc(all_lmi_variables,lmi_variables);
in_y = ismembc(all_lmi_variables,y_lmi_variables);
z_ind = 2;
y_ind = 2;
basis=z.basis(:,1);
nz = size(subX,1);
mz = size(subX,2);
for i = 1:length(all_lmi_variables)
switch 2*in_y(i)+in_z(i)
case 1
basis(:,i+1) = z.basis(:,z_ind);z_ind = z_ind+1;
case 2
temp = sparse(subsasgn(full(0*reshape(X.basis(:,1),nx,mx)),I,full(reshape(Y.basis(:,y_ind),ny,my))));
basis(:,i+1) = temp(:);
y_ind = y_ind+1;
case 3
Z1 = z.basis(:,z_ind);
Z4 = Y.basis(:,y_ind);
Z3 = reshape(Z4,ny,my);
Z2 = sparse(subsasgn(0*reshape(full(X.basis(:,1)),nx,mx),I,Z3));
temp = reshape(Z1,nz,mz)+Z2;
% temp = reshape(z.basis(:,z_ind),nz,mz)+sparse(subsasgn(0*reshape(full(X.basis(:,1)),nx,mx),I,reshape(Y.basis(:,y_ind),ny,my)));
basis(:,i+1) = temp(:);
z_ind = z_ind+1;
y_ind = y_ind+1;
otherwise
end
end;
z.dim(1) = nz;
z.dim(2) = mz;
z.basis = basis;
z.lmi_variables = all_lmi_variables;
y = z;
% Reset info about conic terms
y.conicinfo = [0 0];
otherwise
end
else
error('Reference type not supported');
end
catch
error(lasterr)
end
function y = specialcode(X,Y,I)
y = X;
X_basis = X.basis;
Y_basis = Y.basis;
ind = I.subs{1};ind = ind(:);
yvar_in_xvar = zeros(length(Y.lmi_variables),1);
for i = 1:length(Y.lmi_variables);
yvar_in_xvar(i) = find(X.lmi_variables==Y.lmi_variables(i));
end
y.basis(ind,:) = 0;
mapper = [1 1+yvar_in_xvar(:)'];mapper = mapper(:);
[i,j,k] = find(y.basis);
[ib,jb,kb] = find(Y_basis);
i = [i(:);ind(ib(:))];
j = [j(:);mapper(jb(:))];
k = [k(:);kb(:)];
y.basis = sparse(i,j,k,size(y.basis,1),size(y.basis,2));
y = clean(y);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sym.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/sym.m
| 3,154 |
utf_8
|
07ae0f26ffe548a4af2b632bd01c0bdf
|
function symb_pvec = sdisplay(pvec,symbolicname)
%SDISPLAY Symbolic display of SDPVAR expression
%
% Note that the symbolic display only work if all
% involved variables are explicitely defined as
% scalar variables.
%
% Variables that not are defined as scalars
% will be given the name ryv(i). ryv means
% recovered YALMIP variables, i indicates the
% index in YALMIP (i.e. the result from getvariables)
%
% If you want to change the generic name ryv, just
% pass a second string argument
%
% EXAMPLES
% sdpvar x y
% sdisplay(x^2+y^2)
% ans =
% 'x^2+y^2'
%
% t = sdpvar(2,1);
% sdisplay(x^2+y^2+t'*t)
% ans =
% 'x^2+y^2+ryv(5)^2+ryv(6)^2'
allnames = {};
for pi = 1:size(pvec,1)
for pj = 1:size(pvec,2)
Y.type = '()';
Y.subs = [{pi} {pj}];
p = subsref(pvec,Y);
% p = pvec(pi,pj);
if isa(p,'double')
symb_p = num2str(p);
else
LinearVariables = depends(p);
x = recover(LinearVariables);
exponent_p = full(exponents(p,x));
names = cell(length(x),1);
for i = 1:length(names)
names{i} = ['x' num2str(LinearVariables(i))];
allnames{end+1} = names{i};
end
symb_p = '';
if all(exponent_p(1,:)==0)
symb_p = num2str(full(getbasematrix(p,0)));
exponent_p = exponent_p(2:end,:);
end
for i = 1:size(exponent_p,1)
coeff = full(getbasematrixwithoutcheck(p,i));
switch coeff
case 1
coeff='+';
case -1
coeff = '-';
otherwise
if isreal(coeff)
if coeff >0
coeff = ['+' num2str2(coeff)];
else
coeff=[num2str2(coeff)];
end
else
coeff = ['+' '(' num2str2(coeff) ')' ];
end
end
symb_p = [symb_p coeff symbmonom(names,exponent_p(i,:))];
end
if symb_p(1)=='+'
symb_p = symb_p(2:end);
end
end
symb_pvec{pi,pj} = symb_p;
end
end
allnames = unique(allnames);
for i = 1:length(allnames)
evalin('caller',['syms ' allnames{i}]);
end
S = '';
for pi = 1:size(pvec,1)
ss = '';
for pj = 1:size(pvec,2)
ss = [ss ' ' symb_pvec{pi,pj} ','];
end
S = [S ss ';'];
end
S = ['[' S ']'] ;
symb_pvec = evalin('caller',S);
function s = symbmonom(names,monom)
s = '';
for j = 1:length(monom)
if abs( monom(j))>0
s = [s names{j}];
if monom(j)~=1
s = [s '^' num2str(monom(j))];
end
s =[s '*'];
end
end
if isequal(s(end),'*')
s = s(1:end-1);
end
function s = num2str2(x)
s = num2str(full(x));
if isequal(s,'1')
s = '';
end
if isequal(s,'-1')
s = '-';
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
or.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/or.m
| 2,236 |
utf_8
|
68a1641f6a288ec6b04d2e6630a99bd9
|
function varargout = or(varargin)
%OR (overloaded)
%
% z = or(x,y)
% z = x | y
%
% The OR operator is implemented using the concept of nonlinear operators
% in YALMIP. X|Y defines a new so called derived variable that can be
% treated as any other variable in YALMIP. When SOLVESDP is issued,
% constraints are added to the problem to model the OR operator. The new
% constraints add constraints to ensure that z,x and y satisfy the
% truth-table for OR.
%
% The model for OR is (z>x) + (z>y) + (z<x+y) + (binary(z))
%
% It is assumed that x and y are binary variables (either explicitely
% declared using BINVAR, or constrained using BINARY.)
%
% See also SDPVAR/AND, BINVAR, BINARY
% Models OR using a nonlinear operator definition
switch class(varargin{1})
case 'char'
z = varargin{2};
x = varargin{3};
y = varargin{4};
% *******************************************************
% For *some* efficiency,we merge expressions like A|B|C|D
xvars = getvariables(x);
yvars = getvariables(y);
allextvars = yalmip('extvariables');
if (length(xvars)==1) & ismembc(xvars,allextvars)
x = expandor(x,allextvars);
end
if (length(yvars)==1) & ismembc(yvars,allextvars)
y = expandor(y,allextvars);
end
% *******************************************************
xy=[x y];
varargout{1} = (sum(xy) > z) + (z > xy) +(binary(z)) ;
varargout{2} = struct('convexity','milp','monotonicity','milp','definiteness','milp');
varargout{3} = xy;
case 'sdpvar'
x = varargin{1};
y = varargin{2};
varargout{1} = yalmip('addextendedvariable','or',varargin{:});
otherwise
end
function x = expandor(x,allextvars)
xmodel = yalmip('extstruct',getvariables(x));
if isequal(xmodel.fcn,'or')
x1 = xmodel.arg{1};
x2 = xmodel.arg{2};
if ismembc(getvariables(xmodel.arg{1}),allextvars)
x1 = expandor(xmodel.arg{1},allextvars);
end
if ismembc(getvariables(xmodel.arg{2}),allextvars)
x2 = expandor(xmodel.arg{2},allextvars);
end
x = [x1 x2];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
repmat.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/repmat.m
| 2,094 |
utf_8
|
695991712637a5274ff19d51a5fa40d2
|
function Y=repmat(varargin)
%REPMAT (overloaded)
try
X = varargin{1};
Y = X;
Y.basis = [];
n = Y.dim(1);
m = Y.dim(2);
for i = 1:length(Y.lmi_variables)+1
temp = repmatfixed(reshape(X.basis(:,i),n,m),varargin{2:end});
Y.basis(:,i) = temp(:);
end
Y.dim(1) = size(temp,1);
Y.dim(2) = size(temp,2);
% Reset info about conic terms
Y.conicinfo = [0 0];
catch
error(lasterr)
end
function B = repmatfixed(A,M,N)
if nargin < 2
error('MATLAB:repmat:NotEnoughInputs', 'Requires at least 2 inputs.')
end
if nargin == 2
if isscalar(M)
siz = [M M];
else
siz = M;
end
else
siz = [M N];
end
if isscalar(A)
nelems = prod(siz);
if nelems>0
% Since B doesn't exist, the first statement creates a B with
% the right size and type. Then use scalar expansion to
% fill the array. Finally reshape to the specified size.
B = spalloc(nelems,1,nnz(A));
B(nelems) = A;
if ~isequal(B(1), B(nelems)) | ~(isnumeric(A) | islogical(A))
% if B(1) is the same as B(nelems), then the default value filled in for
% B(1:end-1) is already A, so we don't need to waste time redoing
% this operation. (This optimizes the case that A is a scalar zero of
% some class.)
B(:) = A;
end
B = reshape(B,siz);
else
B = A(ones(siz));
end
elseif ndims(A) == 2 & numel(siz) == 2
[m,n] = size(A);
if (m == 1 & siz(2) == 1)
B = A(ones(siz(1), 1), :);
elseif (n == 1 & siz(1) == 1)
B = A(:, ones(siz(2), 1));
else
mind = (1:m)';
nind = (1:n)';
mind = mind(:,ones(1,siz(1)));
nind = nind(:,ones(1,siz(2)));
B = A(mind,nind);
end
else
Asiz = size(A);
Asiz = [Asiz ones(1,length(siz)-length(Asiz))];
siz = [siz ones(1,length(Asiz)-length(siz))];
for i=length(Asiz):-1:1
ind = (1:Asiz(i))';
subs{i} = ind(:,ones(1,siz(i)));
end
B = A(subs{:});
end
function a = isscalar(b)
[n,m] = size(b);
a = (n*m == 1);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
subsref.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/subsref.m
| 4,658 |
utf_8
|
844eb9433dfa4b2c8de950579397cde2
|
function varargout = subsref(varargin)
%SUBSREF (overloaded)
% Stupid first slice call (supported by MATLAB)
if length(varargin{2}.subs) > 2
i = 3;
ok = 1;
while ok & (i <= length(varargin{2}.subs))
ok = ok & (isequal(varargin{2}.subs{i},1) | isequal(varargin{2}.subs{i},':'));
i = i + 1;
end
if ok
varargin{2}.subs = {varargin{2}.subs{1:2}};
else
error('??? Index exceeds matrix dimensions.');
end
end
if (isa(varargin{2}.subs{1},'sdpvar')) | (length(varargin{2}.subs)==2 & isa(varargin{2}.subs{2},'sdpvar'))
% *****************************************
% Experimental code for varaiable indicies
% *****************************************
varargout{1} = milpsubsref(varargin{:});
return
else
X = varargin{1};
Y = varargin{2};
end
try
switch Y.type
case '()'
% Check for simple cases to speed things up (yes, ugly but we all want speed don't we!)
switch size(Y.subs,2)
case 1
if isa(Y.subs{1},'sdpvar')
varargout{1} = yalmip('addextendedvariable',mfilename,varargin{:});
return
else
y = subsref1d(X,Y.subs{1});
end
case 2
y = subsref2d(X,Y.subs{1},Y.subs{2});
otherwise
error('Indexation error.');
end
otherwise
error(['Indexation with ''' Y.type ''' not supported']) ;
end
catch
error(lasterr)
end
if isempty(y.lmi_variables)
y = full(reshape(y.basis(:,1),y.dim(1),y.dim(2)));
else
% Reset info about conic terms
y.conicinfo = [0 0];
end
varargout{1} = y;
function X = subsref1d(X,ind1)
% Get old and new size
n = X.dim(1);
m = X.dim(2);
% Convert to linear indecicies
if islogical(ind1)
ind1 = double(find(ind1));
end
% Ugly hack handle detect X(:)
%pickall = 0;
if ischar(ind1)
X.dim(1) = n*m;
X.dim(2) = 1;
return;
end
% What would the size be for a double
dummy = reshape(X.basis(:,1),n,m);
dummy = dummy(ind1);
nnew = size(dummy,1);
mnew = size(dummy,2);
[nx,mx] = size(X.basis);
% Sparse row-based subsref can be EEEEEEEXTREMELY SLOW IN SOME CASES
% FIX : Smarter approach?
%
% try
% [ix,jx,sx] = find(X.basis);
% [keep ,loc] = ismember(ix,ind1);keep = find(keep);
% ix = loc(keep);%ix = loc(ix);
% jx = jx(keep);
% sx = sx(keep);
% Z = sparse(ix,jx,sx,length(ind1),mx);
% catch
% 9
% end
if length(ind1) > 1
Z = X.basis.';
Z = Z(:,ind1);
Z = Z.';
else
Z = X.basis(ind1,:);
end
% if ~isequal(Z,Z2)
% error
% end
% Find non-zero basematrices
nzZ = find(any(Z(:,2:end),1));
if ~isempty(nzZ)
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = X.lmi_variables(nzZ);
X.basis = Z(:,[1 1+nzZ]);
else
bas = reshape(X.basis(:,1),n,m);
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = [];
X.basis = reshape(bas(ind1),nnew*mnew,1);
end
%nzZ = find(any(Z,1));
% % A bit messy code to speed up things
% if isempty(nzZ)
% bas = reshape(X.basis(:,1),n,m);
% X.dim(1) = nnew;
% X.dim(2) = mnew;
% X.lmi_variables = [];
% X.basis = reshape(bas(ind1),nnew*mnew,1);
% else
% if nzZ(1) == 1
%
% else
% end
% end
function X = subsref2d(X,ind1,ind2)
if ischar(ind1)
ind1 = 1:X.dim(1);
end
if ischar(ind2)
ind2 = 1:X.dim(2);
end
% Convert to linear indecicies
if islogical(ind1)
ind1 = double(find(ind1));
end
% Convert to linear indecicies
if islogical(ind2)
ind2 = double(find(ind2));
end
n = X.dim(1);
m = X.dim(2);
lind2 = length(ind2);
lind1 = length(ind1);
if lind2 == 1
ind1_ext = ind1(:);
else
ind1_ext = kron(repmat(1,lind2,1),ind1(:));
end
if lind1 == 1
ind2_ext = ind2(:);
else
ind2_ext = kron(ind2(:),repmat(1,lind1,1));
end
if prod(size(ind1_ext))==0 | prod(size(ind2_ext))==0
linear_index = [];
else
% Speed-up for some bizarre code with loads of indexing of vector
if m==1 & ind2_ext==1
linear_index = ind1_ext;
else
linear_index = sub2ind([n m],ind1_ext,ind2_ext);
end
end
nnew = length(ind1);
mnew = length(ind2);
% Put all matrices in vectors and extract sub matrix
Z = X.basis(linear_index,:);
% Find non-zero basematrices
nzZ = find(any(Z(:,2:end),1));
if ~isempty(nzZ)
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = X.lmi_variables(nzZ);
X.basis = Z(:,[1 1+nzZ]);
else
bas = reshape(X.basis(:,1),n,m);
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = [];
X.basis = reshape(bas(linear_index),nnew*mnew,1);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
pwa.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/pwa.m
| 4,373 |
utf_8
|
22c949c81c11c00407c9edb6dab6066e
|
function [p,Bi,Ci,Pn,Pfinal] = PWA(h,Xdomain)
% PWA Tries to create a PWA description
%
% [p,Bi,Ci,Pn,Pfinal] = PWA(h,X)
%
% Input
% h : scalar SDPVAR object
% X : Constraint object
%
% Output
%
% p : scalar SDPVAR object representing the PWA function
% Bi,Ci,Pn,Pfinal : Data in MPT format
%
% The command tries to expand the nonlinear operators
% (min,max,abs,...) used in the variable h, in order
% to generate an epi-graph model. Given this epigraph model,
% it is projected to the variables of interest and the
% defining facets of the PWA function is extracted. The second
% argument can be used to limit the domain of the PWA function.
% If no second argument is supplied, the PWA function is created
% over the domain -100 to 100.
%
% A new sdpvar object p is created, representing the same
% function as h, but in a slightly different internal format.
% Additionally, the PWA description in MPT format is created.
%
% The function is mainly inteded to be used for easy
% plotting of convex PWA functions
t = sdpvar(1,1);
[F,failure,cause] = expandmodel(lmi(h<=t),[],sdpsettings('allowmilp',0));
if failure
error(['Could not expand model (' cause ')']);
return
end
% Figure out what the actual original variables are
% note, by construction, they
all_initial = getvariables(h);
all_extended = yalmip('extvariables');
all_variables = getvariables(F);
gen_here = getvariables(t);
non_ext_in = setdiff(all_initial,all_extended);
lifted = all_variables(all_variables>gen_here);
vars = union(setdiff(setdiff(setdiff(all_variables,all_extended),gen_here),lifted),non_ext_in);
nx = length(vars);
X = recover(vars);
if nargin == 1
Xdomain = (-100 <= X <= 100);
else
Xdomain = (-10000 <= X <= 10000)+Xdomain;
end
[Ai,Bi,Ci,Pn] = generate_pwa(F,t,X,Xdomain,nx);
Pfinal = union(Pn);
sol.Pn = Pn;
sol.Bi = Bi;
sol.Ci = Ci;
sol.Ai = Ai;
sol.Pfinal = Pfinal;
p = pwf(sol,X,'convex');
%
% binarys = recover(all_variables(find(ismember(all_variables,yalmip('binvariables')))))
% if length(binarys) > 0
%
% Binary_Equalities = [];
% Binary_Inequalities = [];
% Mixed_Equalities = [];
% top = 1;
% for i = 1:length(F)
% Fi = sdpvar(F(i));
% if is(F(i),'equality')
% if all(ismember(getvariables(Fi),yalmip('binvariables')))
% Binary_Equalities = [Binary_Equalities;(top:top-1+prod(size(Fi)))'];
% Mixed_Equalities = [Mixed_Equalities;(top:top-1+prod(size(Fi)))'];
% end
% else
% if all(ismember(getvariables(Fi),yalmip('binvariables')))
% Binary_Inequalities = [Binary_Inequalities;(top:top-1+prod(size(Fi)))'];
% end
% end
% top = top+prod(size(Fi))';
% end
% P = sdpvar(F);
% P_ineq = extsubsref(P,setdiff(1:length(P),[Binary_Equalities; Binary_Inequalities]))
% P_binary_eq = extsubsref(P,Binary_Equalities);HK1 = getbase(P_binary_eq);
% P_binary_ineq = extsubsref(P,Binary_Inequalities);HK2 = getbase(P_binary_ineq);
% nbin = length(binarys);
% enums = dec2decbin(0:2^nbin-1,nbin)'
% if isempty(HK2)
% HK2 = HK1*0;
% end
% for i = 1:size(enums,2)
% if all(HK1*[1;enums(:,i)]==0)
% if all(HK2*[1;enums(:,i)]>=0)
% Pi = replace(P_ineq,binarys,enums(:,i))
% end
% end
% end
%
% else
% [Ai,Bi,Ci,Pn] = generate_pwa(F,t,X,Xdomain,nx);
% end
%
function [Ai,Bi,Ci,Pn] = generate_pwa(F,t,X,Xdomain,nx)
% Project, but remember that we already expanded the constraints
P = polytope(projection(F+(t<=10000)+Xdomain,[X;t],[],1));Xdomain = polytope(Xdomain);
[H,K] = double(P);
facets = find(H(:,end)<0);
region = find(~H(:,end) & any(H(:,1:nx),2) );
Hr = H(region,1:nx);
Kr = K(region,:);
H = H(facets,:);
K = K(facets);
K = K./H(:,end);
H = H./repmat(H(:,end),1,size(H,2));
nx = length(X);
Pn = [];
cib = [H(:,1:nx) K];
Ai = {};
Bi = cell(0);
Ci = cell(0);
if length(Kr > 0)
Xdomain = intersect(Xdomain,polytope(Hr,Kr));
end
[Hr,Kr] = double(Xdomain);
for i = 1:length(K)
j = setdiff(1:length(K),i);
HiKi = repmat(cib(i,:),length(K)-1,1)-cib(j,:);
Pi = polytope([HiKi(:,1:nx);Hr],[HiKi(:,end);Kr]);
if isfulldim(Pi)
Pn = [Pn Pi];
Bi{end+1} = -cib(i,1:end-1);
Ci{end+1} = cib(i,end);
Ai{end+1} = [];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
mtimes.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/mtimes.m
| 5,659 |
utf_8
|
70cfba01103b6fc708e8b37cbf17df2e
|
function Z = mtimes(X,Y)
%MTIMES (overloaded)
% Brute-force implementation of multiplication of noncommuting variables
% (with possible commuting variables involved)
% Check classes
X_is_spdvar = isa(X,'sdpvar');
Y_is_spdvar = isa(Y,'sdpvar');
X_is_ncvar = isa(X,'ncvar');
Y_is_ncvar = isa(Y,'ncvar');
% Get all the tables, and expand them so that they correspond to the same
% number of variables globally (nonCommutingTable is not up to date after a
% new commuting variables has been defined, to save flops)
nonCommutingTable = yalmip('nonCommutingTable');
[monomtable,variabletype] = yalmip('monomtable');
if size(monomtable,1)>size(nonCommutingTable,1)
nonCommutingTable((1+size(nonCommutingTable,1)):(size(monomtable,1)),1) = (1+size(nonCommutingTable,1)):(size(monomtable,1));
end
% Cast commutative variables as nc temporarily by adding them to the table
commuting = find(~any(nonCommutingTable,2));
nonCommutingTable(commuting,1) = commuting;
x_variables = getvariables(X);Xbase = getbase(X);
y_variables = getvariables(Y);Ybase = getbase(Y);
temp_monom_table = [];
temp_nc_table = [];
temp_c_table = [];
new_base = [];
for i = 0:length(x_variables)
if i>0
x_monom = nonCommutingTable(x_variables(i),:);
else
x_monom = nan;
end
x_base = Xbase(:,i+1);
for j = 0:length(y_variables)
if j>0
y_monom = nonCommutingTable(y_variables(j),:);
else
y_monom = nan;
end
y_base = Ybase(:,j+1);
xy_base = reshape(x_base,size(X))*reshape(y_base,size(Y));
if (i == 0) & (j== 0)
new_base = xy_base(:);
elseif nnz(xy_base)>0
xy_monom = [x_monom(2:end) y_monom(2:end)];
xy_monom = xy_monom(find(xy_monom));
temp_nc_table(end+1,1:length(xy_monom)) = xy_monom;
temp_c_table(end+1,1:2) = [x_monom(1) y_monom(1)];
new_base = [new_base xy_base(:)];
end
end
end
% It could have happended that new commuting monomials where generated
% during the multiplication. Check and create these
for i = 1:size(temp_c_table,1)
aux = spalloc(1,size(monomtable,2),2);
if ~isnan(temp_c_table(i,1))
aux = monomtable(temp_c_table(i,1),:) + aux;
end
if ~isnan(temp_c_table(i,2))
aux = monomtable(temp_c_table(i,2),:) + aux;
end
if nnz(aux)>0
candidates = findrows(monomtable,aux);
if ~isempty(candidates)
temp_c_table(i,1) = candidates;
else
monomtable = [monomtable;aux];
nonCommutingTable(end+1,1) = nan;
temp_c_table(i,1) = size(monomtable,1);
switch sum(aux)
case 1
variabletype(end+1) = 0;
case 2
if nnz(aux) == 1
variabletype(end+1) = 2;
else
variabletype(end+1) = 1;
end
otherwise
variabletype(end+1) = 3;
end
end
end
end
temp_nc_table = [temp_c_table(:,1) temp_nc_table];
% Okay, now we have the monomials. Now we have to match them to
% possible earlier monomials
if size(nonCommutingTable,2) < size(temp_nc_table,2)
nonCommutingTable(1,size(temp_nc_table,2)) = 0;
elseif size(temp_nc_table,2) < size(nonCommutingTable,2)
temp_nc_table(1,size(nonCommutingTable,2)) = 0;
end
for i = 1:size(temp_nc_table,1)
candidates = findrows_nan(nonCommutingTable,temp_nc_table(i,:));
if isempty(candidates)
nonCommutingTable = [nonCommutingTable;temp_nc_table(i,:)];
monomtable(end+1,end+1) = 0;
involved = temp_nc_table(i,1+find(temp_nc_table(i,2:end)));
switch length(involved)
case 1
if isnan(temp_nc_table(i,1))
variabletype(end+1) = 0;
else
if variabletype(temp_nc_table(i,1)) == 0
variabletype(end+1) = 1;
else
variabletype(end+1) = 3;
end
end
case 2
if isnan(temp_nc_table(i,1))
if involved(1) == involved(2)
variabletype(end+1) = 2;
else
variabletype(end+1) = 1;
end
else
variabletype(end+1) = 3;
end
otherwise
variabletype(end+1) = 3;
end
lmivariables(i) = size(nonCommutingTable,1);
else
lmivariables(i) = candidates;
end
end
% Create an output variable quickly
if X_is_ncvar
Z = X;
else
Z = Y;
end
Z.basis = new_base;
Z.lmi_variables = lmivariables;
% Fucked up order (lmi_variables should be sorted and unique)
if any(diff(Z.lmi_variables)<0)
[i,j]=sort(Z.lmi_variables);
Z.basis = [Z.basis(:,1) Z.basis(:,j+1)];
Z.lmi_variables = Z.lmi_variables(j);
end
[un_Z_vars2] = uniquestripped(Z.lmi_variables);
if length(un_Z_vars2) < length(Z.lmi_variables)
[un_Z_vars,hh,jj] = unique(Z.lmi_variables);
if length(Z.lmi_variables) ~=length(un_Z_vars)
Z.basis = Z.basis*sparse([1 1+jj],[1 1+(1:length(jj))],ones(1,1+length(jj)))';
Z.lmi_variables = un_Z_vars;
end
end
Z.dim = size(xy_base);
Z = clean(Z);
if size(monomtable,2) < size(monomtable,1)
monomtable(size(monomtable,1),size(monomtable,1)) = 0;
end
yalmip('nonCommutingTable',nonCommutingTable);
yalmip('setmonomtable',monomtable,variabletype);
function c = findrows_nan(a,b)
a(isnan(a)) = 0;
b(isnan(b)) = 0;
c=findrows(a,b);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
and.m
|
.m
|
LMI-Matlab-master/yalmip/extras/@ncvar/and.m
| 2,197 |
utf_8
|
e574e35b982582324eb3c78d9d965cab
|
function varargout = and(varargin)
%AND (overloaded)
%
% z = and(x,y)
% z = x & y
%
% The AND operator is implemented using the concept of nonlinear operators
% in YALMIP. X|Y defines a new so called derived variable that can be
% treated as any other variable in YALMIP. When SOLVESDP is issued,
% constraints are added to the problem to model the AND operator. The new
% constraints add constraints to ensure that z, x and y satisfy the
% truth-table for AND.
%
% The model for AND is (z<=x)+(z<=y)+(1+z>=x+y)+(binary(z))
%
% It is assumed that x and y are binary variables (either explicitely
% declared using BINVAR, or constrained using BINARY.)
%
% See also SDPVAR/AND, BINVAR, BINARY
switch class(varargin{1})
case 'char'
z = varargin{2};
x = varargin{3};
y = varargin{4};
% *******************************************************
% For *some* efficiency,we merge expressions like A&B&C&D
xvars = getvariables(x);
yvars = getvariables(y);
allextvars = yalmip('extvariables');
if (length(xvars)==1) & ismembc(xvars,allextvars)
x = expandand(x,allextvars);
end
if (length(yvars)==1) & ismembc(yvars,allextvars)
y = expandand(y,allextvars);
end
% *******************************************************
varargout{1} = (x >= z) + (y >= z) + (length(x)+length(y)-1+z >= sum(x)+sum(y)) + (binary(z));
varargout{2} = struct('convexity','milp','monotoncity','milp','definiteness','milp');
varargout{3} = [];
case 'sdpvar'
x = varargin{1};
y = varargin{2};
varargout{1} = yalmip('addextendedvariable','and',varargin{:});
otherwise
end
function x = expandand(x,allextvars)
xmodel = yalmip('extstruct',getvariables(x));
if isequal(xmodel.fcn,'and')
x1 = xmodel.arg{1};
x2 = xmodel.arg{2};
if ismembc(getvariables(xmodel.arg{1}),allextvars)
x1 = expandand(xmodel.arg{1},allextvars);
end
if ismembc(getvariables(xmodel.arg{2}),allextvars)
x2 = expandand(xmodel.arg{2},allextvars);
end
x = [x1 x2];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
addfactors.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/addfactors.m
| 2,579 |
utf_8
|
1a0e68ae8acfbe591015380fb18a28ad
|
function Z = addfactors(Z,X,Y)
if isa(X,'double') || isa(X,'logical')
if length(Y.midfactors)==0
return
end
% Y = refactor(Y);
Z.midfactors = Y.midfactors;
Z.leftfactors = Y.leftfactors;
Z.rightfactors = Y.rightfactors;
Z.midfactors{end+1} = X;
if length(X)>1
Z.leftfactors{end+1} = speye(size(X,1));
Z.rightfactors{end+1} = speye(size(X,2));
else
Z.leftfactors{end+1} = 1;
Z.rightfactors{end+1} = 1;
end
elseif isa(Y,'double') || isa(Y,'logical')
if length(X.midfactors)==0
return
end
% X = refactor(X);
Z.midfactors = X.midfactors;
Z.leftfactors = X.leftfactors;
Z.rightfactors = X.rightfactors;
Z.midfactors{end+1} = Y;
if length(Y)>1
Z.leftfactors{end+1} = speye(size(Y,1));
Z.rightfactors{end+1} = speye(size(Y,2));
else
Z.leftfactors{end+1} = 1;
Z.rightfactors{end+1} = 1;
end
else
if length(X.midfactors)==0 || length(Y.midfactors)==0
Z.midfactors = [];
Z.leftfactors = [];
Z.rightfactors = [];
return
end
% X = refactor(X);
% Y = refactor(Y);
if prod(X.dim)>0 && prod(Y.dim)==1
for i = 1:length(Y.midfactors)
Y.leftfactors{i} = repmat(Y.leftfactors{i},X.dim(1),1);
Y.rightfactors{i} = repmat(Y.rightfactors{i},1,X.dim(2));
end
end
if prod(Y.dim)>0 && prod(X.dim)==1
for i = 1:length(X.midfactors)
X.leftfactors{i} = repmat(X.leftfactors{i},Y.dim(1),1);
X.rightfactors{i} = repmat(X.rightfactors{i},1,Y.dim(2));
end
end
Z.leftfactors = {X.leftfactors{:},Y.leftfactors{:}};
Z.midfactors = {X.midfactors{:},Y.midfactors{:}};
Z.rightfactors = {X.rightfactors{:},Y.rightfactors{:}};
end
n = Z.dim(1);
m = Z.dim(2);
for i = 1:length(Z.midfactors)
% isdouble(i) = isa(Z.midfactors{i},'double');
if size(Z.leftfactors{i},1)~=n
if prod(size(Z.midfactors{i}))==1
Z.leftfactors{i} = ones(n,1);
else
error('Inconsistent factors. Please report bug');
end
end
if size(Z.rightfactors{i},2)~=m
if prod(size(Z.midfactors{i}))==1
Z.rightfactors{i} = ones(1,m);
else
error('Inconsistent factors. Please report bug');
end
end
end
Z = cleandoublefactors(Z);
try
Z = flushmidfactors(Z);
catch
1
end
function Z = refactor(Z)
if isempty(Z.midfactors)
Z.leftfactors{1} = 1;
Z.midfactors{1} = Z;
Z.rightfactors{1} = 1;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
asec.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/asec.m
| 881 |
utf_8
|
210ec08cb20380016ffc9ab743ade4e9
|
function varargout = asec(varargin)
%ASEC (overloaded)
switch class(varargin{1})
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)(1./(x.*(x.^2-1).^0.5));
varargout{1} = [varargin{3}.^2 >= 1]; % Disconnected domain
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ASEC called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xU <= -1 || xL >= 1
L = asec(xL);
U = asec(xU);
elseif xL < 0 & xU > 0
L = 0;
U = pi;
elseif xU < 0 || xL > 0
L = real(asec(xL));
U = real(asec(xU));
else
L = 0;
U = pi;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
norm.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/norm.m
| 12,678 |
utf_8
|
833cfcffac8a86284f26c75e3bec8bc9
|
function varargout = norm(varargin)
%NORM (overloaded)
%
% t = NORM(x,P)
%
% The variable t can only be used in convexity preserving
% operations such as t<=1, max(t,y)<=1, minimize t etc.
%
% For matrices...
% NORM(X) models the largest singular value of X, max(svd(X)).
% NORM(X,2) is the same as NORM(X).
% NORM(X,1) models the 1-norm of X, the largest column sum, max(sum(abs(X))).
% NORM(X,inf) models the infinity norm of X, the largest row sum, max(sum(abs(X'))).
% NORM(X,'inf') same as above
% NORM(X,'fro') models the Frobenius norm, sqrt(sum(diag(X'*X))).
% NORM(X,'nuc') models the Nuclear norm, sum of singular values.
% NORM(X,'*') same as above
% NORM(X,'tv') models the (isotropic) total variation semi-norm
% For vectors...
% NORM(V) = norm(V,2) = standard Euclidean norm.
% NORM(V,inf) = max(abs(V)).
% NORM(V,1) = sum(abs(V))
%
% SEE ALSO SUMK, SUMABSK
%% ***************************************************
% This file defines a nonlinear operator for YALMIP
%
% It can take three different inputs
% For DOUBLE inputs, it returns standard double values
% For SDPVAR inputs, it generates an internal variable
%
% When first input is 'model' it returns the graph
% in the first output and structure describing some
% properties of the operator.
%% ***************************************************
switch class(varargin{1})
case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.
if nargin == 1
varargout{1} = yalmip('define',mfilename,varargin{1},2);
else
switch varargin{2}
case {1,2,inf,'inf','fro'}
varargout{1} = yalmip('define',mfilename,varargin{:});
case 'tv'
if ~isreal(varargin{1})
error('Total variation norm not yet implemented for complex arguments');
end
if min(varargin{1}.dim)==1
varargout{1} = norm(diff(varargin{1}),1);
return
end
varargout{1} = yalmip('define','norm_tv',varargin{:});
case {'nuclear','*'}
if min(size(varargin{1}))==1
varargout{1} = norm(varargin{1},1);
else
varargout{1} = yalmip('define','norm_nuclear',varargin{:});
end
otherwise
if isreal(varargin{1}) & min(size(varargin{1}))==1 & isa(varargin{2},'double')
varargout{1} = pnorm(varargin{:});
else
error('norm(x,P) only supported for P = 1, 2, inf, ''fro'' and ''nuclear''');
end
end
end
case 'char' % YALMIP sends 'model' when it wants the epigraph or hypograph
switch varargin{1}
case 'graph'
t = varargin{2};
X = varargin{3};
p = varargin{4};
% Code below complicated by two things
% 1: Absolute value for complex data -> cone constraints on
% elements
% 2: SUBSREF does not call SDPVAR subsref -> use extsubsref.m
switch p
case 1
if issymmetric(X)
Z = sdpvar(size(X,1),size(X,2));
else
Z = sdpvar(size(X,1),size(X,2),'full');
end
if min(size(X))>1
if isreal(X)
z = reshape(Z,[],1);
x = reshape(X,[],1);
F = (-z <= x <= z);
else
F = ([]);
zvec = reshape(Z,1,[]);
xrevec=reshape(real(X),1,[]);
ximvec=reshape(imag(X),1,[]);
F = [F,cone([zvec;xrevec;ximvec])];
end
F = F + (sum(Z,1) <= t);
else
if isreal(X)
% Standard definition
% F = (-t <= X <= t);
X = reshape(X,[],1);
Z = reshape(Z,[],1);
Xbase = getbase(X);
Constant = find(~any(Xbase(:,2:end),2));
if ~isempty(Constant)
% Exploit elements without any
% decision variables
r1 = ones(length(Z),1);
r2 = zeros(length(Z),1);
r1(Constant) = 0;
r2(Constant) = abs(Xbase(Constant,1));
Z = Z.*r1 + r2;
end
F = (-Z <= X <= Z) + (sum(Z) <= t);
else
F = (cone([reshape(Z,1,[]);real(reshape(X,1,[]));imag(reshape(X,1,[]))]));
F = F + (sum(Z) <= t);
end
end
case 2
if min(size(X))>1
F = ([t*eye(size(X,1)) X;X' t*eye(size(X,2))])>=0;
else
F = cone(X(:),t);
end
case {inf,'inf'}
if min(size(X))>1
Z = sdpvar(size(X,1),size(X,2),'full');
if isreal(X)
F = (-Z <= X <= Z);
else
F = ([]);
for i = 1:size(X,1)
for j = 1:size(X,2)
xi = extsubsref(X,i,j);
zi = extsubsref(Z,i,j);
F = F + (cone([real(xi);imag(xi)],zi));
end
end
end
F = F + (sum(Z,2) <= t);
else
if isreal(X)
F = (-t <= X <= t);
[M,m,infbound] = derivebounds(X);
if ~infbound
F = F + (0 <= t <= max(max(abs([m M]))));
end
else
F = ([]);
for i = 1:length(X)
xi = extsubsref(X,i);
F = F + (cone([real(xi);imag(xi)],t));
end
end
end
case 'fro'
X.dim(1)=X.dim(1)*X.dim(2);
X.dim(2)=1;
F = (cone(X,t));
case 'nuclear'
U = sdpvar(X.dim(2));
V = sdpvar(X.dim(1));
F = [trace(U)+trace(V) <= 2*t, [U X';X V]>=0];
case 'tv'
Dx = [diff(X,1,1);zeros(1,X.dim(2))];
Dy = [diff(X,1,2) zeros(X.dim(1),1)];
T = sdpvar(X.dim(1),X.dim(2),'full');
F = cone([reshape(T,1,[]);reshape(Dx,1,[]);reshape(Dy,1,[])]);
F = [F, sum(sum(T)) <= t];
otherwise
end
varargout{1} = F;
varargout{2} = struct('convexity','convex','monotonicity','none','definiteness','positive','model','graph');
varargout{3} = X;
case 'exact'
t = varargin{2};
X = varargin{3};
p = varargin{4};
if ~isreal(X) | isequal(p,2) | isequal(p,'fro') | min(size(X))>1 % Complex valued data, matrices and 2-norm not supported
varargout{1} = [];
varargout{2} = [];
varargout{3} = [];
else
if p==1
X = reshape(X,length(X),1);
absX = sdpvar(length(X),1);
d = binvar(length(X),1);
[M,m] = derivebounds(X);
if all(abs(sign(m)-sign(M))<=1)
% Silly convex case. Some coding to care of the
% case sign(0)=0...
d = ones(length(X),1);
d(m<0)=-1;
F = (t - sum(absX) == 0) + (absX == d.*X);
else
F = ([]);
% Some fixes to remove trivial constraints
% which caused problems in a user m
positive = find(m >= 0);
negative = find(M <= 0);
fixed = find(m==M);
if ~isempty(fixed)
positive = setdiff(positive,fixed);
negative = setdiff(negative,fixed);
end
if ~isempty(positive)
d = subsasgn(d,struct('type','()','subs',{{positive}}),1);
end
if ~isempty(negative)
d = subsasgn(d,struct('type','()','subs',{{negative}}),0);
end
if ~isempty(fixed)
notfixed = setdiff(1:length(m),fixed);
addsum = sum(abs(m(fixed)));
m = m(notfixed);
M = M(notfixed);
X = extsubsref(X,notfixed);
absX = extsubsref(absX,notfixed);
d = extsubsref(d,notfixed);
else
addsum = 0;
end
maxABSX = max([abs(m) abs(M)],[],2);
% d==0 ---> X<0 and absX = -X
F = F + (X <= M.*d) + (0 <= absX+X <= 2*maxABSX.*d);
% d==1 ---> X>0 and absX = X
F = F + (X >= m.*(1-d)) + (0 <= absX-X <= 2*maxABSX.*(1-d));
F = F + (t - sum(absX)-addsum == 0);
end
else
F = max_integer_model([X;-X],t);
end
varargout{1} = F;
varargout{2} = struct('convexity','convex','monotonicity','milp','definiteness','positive','model','integer');
varargout{3} = X;
end
otherwise
error('SDPVAR/NORM called with CHAR argument?');
end
otherwise
error('Strange type on first argument in SDPVAR/NORM');
end
function F = findmax(F,M,m,X,t)
n = length(X);
d = binvar(n,1);
F = F + (sum(d)==1);
F = F + (-(max(M)-min(m))*(1-d) <= t-X <= (max(M)-min(m))*(1-d));
kk = [];
ii = [];
for i = 1:n
k = [1:1:i-1 i+1:1:n]';
ii = [ii;repmat(i,n-1,1)];
kk = [kk;k];
Mm = M(k)-m(i);
end
xii = extsubsref(X,ii);
dii = extsubsref(d,ii);
xkk = extsubsref(X,kk);
F = F + (xkk <= xii+(M(kk)-m(ii)).*(1-dii));
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
pow10.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/pow10.m
| 979 |
utf_8
|
3c67d739166aa630ae6b9939611ab49c
|
function varargout = pow10(varargin)
%POW10 (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/POW10 CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','convex','monotonicity','increasing','definiteness','positive','model','callback');
operator.convexhull = @convexhull;
operator.bounds = @bounds;
operator.derivative = @derivative;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/POW10 called with CHAR argument?');
end
function df = derivative(x)
df = log(10)*pow10(x);
function [L,U] = bounds(xL,xU)
L = pow10(xL);
U = pow10(xU);
function [Ax, Ay, b] = convexhull(xL,xU)
fL = pow10(xL);
fU = pow10(xU);
dfL = log(10)*fL;
dfU = log(10)*fU;
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
tan.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/tan.m
| 841 |
utf_8
|
af58a56ca9dea8449e2c6fef9202be16
|
function varargout = tan (varargin)
%TAN (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/TAN CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)(sec(x).^2);
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/TAN called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
n1 = fix((xL+pi/2)/(pi));
n2 = fix((xU+pi/2)/(pi));
if n1==n2
L = tan(xL);
U = tan(xU);
else
L = -inf;
U = inf;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
asinh.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/asinh.m
| 677 |
utf_8
|
e3f8453d9133b82d52664494918be4c5
|
function varargout = asinh(varargin)
%ASINH (overloaded)
switch class(varargin{1})
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','increasing','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)((1 + x.^2).^-0.5);
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ASINH called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = asinh(xL);
U = asinh(xU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
plot.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/plot.m
| 4,864 |
utf_8
|
0e3843abf5f44e3a2a5e011a093f9bc3
|
function Y=plot(varargin)
%PLOT (overloaded)
% Fast version for plotting simple PWA objects
if nargin == 1
X = varargin{1};
if isa(varargin{1},'sdpvar')
if length(X) == 1
if isequal(full(getbase(X)),[zeros(length(X),1) eye(length(X))])
extstruct = yalmip('extstruct',getvariables(X));
if ~isempty(extstruct)
if isequal(extstruct.fcn,'pwa_yalmip') | isequal(extstruct.fcn,'pwq_yalmip')%#ok
% Maybe some reduction has been performed so we
% actually can plot it
xarg = extstruct.arg{2};
switch extstruct.arg{3}
case ''
otherwise
Pn = polytope; Bi = {}; Ci = {};
index = extstruct.arg{5};
for i = 1:length(extstruct.arg{1})
% Pick out row
for j = 1:length(extstruct.arg{1}{i}.Bi)
extstruct.arg{1}{i}.Bi{j} = extstruct.arg{1}{i}.Bi{j}(index,:);
extstruct.arg{1}{i}.Ci{j} = extstruct.arg{1}{i}.Ci{j}(index,:);
end
if isempty(extstruct.arg{1}{i}.Ai{1})
Pn = [Pn extstruct.arg{1}{i}.Pn];
Bi = cat(2, Bi, extstruct.arg{1}{i}.Bi);
Ci = cat(2, Ci, extstruct.arg{1}{i}.Ci);
else
if nnz([extstruct.arg{1}{i}.Ai{:}]) == 0
Pn = [Pn extstruct.arg{1}{i}.Pn];
Bi = cat(2, Bi, extstruct.arg{1}{i}.Bi);
Ci = cat(2, Ci, extstruct.arg{1}{i}.Ci);
else
hold on
[extstruct.arg{1}{i}.Pn,extstruct.arg{1}{i}.Bi,extstruct.arg{1}{i}.Ci,extstruct.arg{1}{i}.Ai] = reduce_basis(extstruct.arg{1}{i}.Pn,extstruct.arg{1}{i}.Bi,extstruct.arg{1}{i}.Ci,extstruct.arg{1}{i}.Ai,xarg);
Y = mpt_plotPWQ(extstruct.arg{1}{i}.Pn, extstruct.arg{1}{i}.Ai,extstruct.arg{1}{i}.Bi,extstruct.arg{1}{i}.Ci);
hold off
end
end
end
if ~isempty(Bi),
hold on
[Pn,Bi,Ci] = reduce_basis(Pn,Bi,Ci,[],xarg);
if size(Bi{1},2) > 2
error('Cannot plot high-dimensional PWA functions')
end
mpt_plotPWA(Pn, Bi, Ci);
hold off
end
drawnow
return
end
end
end
end
else
for j = 1:length(X)
plot(extsubsref(X,j));
end
return
end
end
end
% More complex expression. Get epi-graph model
% project to our variables, and extract defining facets
if nargin == 1
[p,Bi,Ci,Pn,Pfinal] = pwa(varargin{1});%#ok
elseif isa(varargin{2},'lmi')
[p,Bi,Ci,Pn,Pfinal] = pwa(varargin{1},varargin{2});%#ok
else
error('Second argument should be a domain defining SET object.');
end
if nargout>0
Y = mpt_plotPWA(Pn,Bi,Ci);
else
mpt_plotPWA(Pn,Bi,Ci);
end
function S = extractrow(S,index)
for i = 1:length(S)
S{i} = S{i}(index,:);
end
function [Pnnew,Binew,Cinew,Ainew] = reduce_basis(Pn,Bi,Ci,Ai,xarg);
%
if ~isequal(getbase(xarg),[zeros(length(xarg),1) eye(length(xarg))])
base = getbase(xarg);
c = base(:,1);
D = base(:,2:end);
Pnnew = [];
Ainew = [];
Binew = [];
Cinew = [];
for i = 1:length(Pn)
[H,K] = double(Pn(i));
Phere = polytope(H*D,K-H*c);
if isfulldim(Phere)
Pnnew = [Pnnew Phere];
if ~isempty(Ai)
Cinew{end+1} = Ci{i} + Bi{i}*c + c'*Ai{i}*c;
Binew{end+1} = Bi{i}*D + 2*c'*Ai{i}*D;
Ainew{end+1} = D'*Ai{i}*Ai{i};
else
Cinew{end+1} = Ci{i} + Bi{i}*c;
Binew{end+1} = Bi{i}*D;
end
end
end
else
Pnnew = Pn;
Ainew = Ai;
Binew = Bi;
Cinew = Ci;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
ismember_internal.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/ismember_internal.m
| 3,293 |
utf_8
|
5c70c86d0d39f66f8b69c3e2f83b0508
|
function YESNO = ismember_internal(x,p)
%ISMEMBER_INTERNAL Helper for ISMEMBER
if isa(x,'sdpvar') & (isa(p,'polytope') | isa(p,'Polyhedron'))
if length(p) == 1
[H,K,Ae,be] = poly2data(p);
if min(size(x))>1
error('first argument should be a vector');
end
if length(x) == size(H,2)
x = reshape(x,length(x),1);
YESNO = [H*x <= K,Ae*x == be];
return
else
disp('The polytope in the ismember condition has wrong dimension')
error('Dimension mismatch.');
end
else
d = binvar(length(p),1);
YESNO = (sum(d)==1);
[L,U] = safe_bounding_box(p(1));
for i = 1:length(p)
[Li,Ui] = safe_bounding_box(p(i));
L = min([L Li],[],2);
U = max([U Ui],[],2);
end
for i = 1:length(p)
[H,K,Ae,be] = poly2data(p(i));
% Merge equalities into inequalities
H = [H;Ae;-Ae];
K = [K;be;-be];
if min(size(x))>1
error('first argument should be a vector');
end
if length(x) == size([H],2)
x = reshape(x,length(x),1);
lhs = H*x-K;
% Derive bounds based on YALMIPs knowledge on bounds on
% involved variables
[M,m] = derivebounds(lhs);
% Strengthen by using MPTs bounding box
%[temp,L,U] = bounding_box(p(i));
Hpos = (H>0);
Hneg = (H<0);
M = min([M (H.*Hpos*U+H.*Hneg*L-K)],[],2);
YESNO = YESNO + (H*x-K <= M.*(1-extsubsref(d,i)));
else
error('Dimension mismatch.');
end
end
end
return
end
if isa(x,'sdpvar') & isa(p,'double')
x = reshape(x,prod(x.dim),1);
if numel(p)==1
F = (x == p);
else
if size(p,1)==length(x) & size(p,2)>1
Delta = binvar(size(p,2),1);
F = [sum(Delta) == 1, x == p*Delta];
if all(all(p == fix(p)))
% Check if x implicitly is constrained to be integer
B = getbase(x);
if all(all(B == fix(B)))
if all(sum(B | B,2)<= 1)
F = [F, integer(x)];
end
end
end
else
p = p(:);
Delta = binvar(length(x),length(p),'full');
F = [sum(Delta,2) == 1, x == Delta*p];
if all(all(p == fix(p)))
% Check if x implicitly is constrained to be integer
B = getbase(x);
if all(all(B == fix(B)))
if all(sum(B | B,2)<= 1)
F = [F, integer(x)];
end
end
end
end
end
YESNO = F;
return
end
function [H,K,Ae,be] = poly2data(p);
if isa(p,'polytope')
[H,K] = double(p);
Ae = [];
be = [];
else
p = p.minHRep();
H = p.A;
K = p.b;
Ae = p.Ae;
be = p.be;
end
function [L,U] = safe_bounding_box(P)
if isa(P,'polytope')
[temp,L,U] = bounding_box(P);
else
S = outerApprox(P);
L = S.Internal.lb;
U = S.Internal.ub;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sqrtm_internal.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/sqrtm_internal.m
| 1,323 |
utf_8
|
b33f0b07880e3a33d7952c5da2aaf17b
|
function varargout = sqrtm_internal(varargin)
%SQRTM (overloaded)
switch class(varargin{1})
case 'double'
varargout{1} = sqrt(varargin{1});
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
X = varargin{3};
F = (X >= eps);
varargout{1} = F;
varargout{2} = struct('convexity','concave','monotonicity','increasing','definiteness','positive','convexhull',@convexhull,'bounds',@bounds,'model','callback','derivative',@(x) 1./(eps + 2*abs(x).^0.5),'inverse',@(x)x.^2);
varargout{3} = X;
otherwise
error('SDPVAR/SQRTM called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xL < 0
% The variable is not bounded enough yet
L = 0;
else
L = sqrt(xL);
end
if xU < 0
% This is an infeasible problem
L = inf;
U = -inf;
else
U = sqrt(xU);
end
function [Ax, Ay, b] = convexhull(xL,xU)
if xL < 0 | xU == 0
Ax = []
Ay = [];
b = [];
else
fL = sqrt(xL);
fU = sqrt(xU);
dfL = 1/(2*sqrt(xL));
dfU = 1/(2*sqrt(xU));
[Ax,Ay,b] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);
remove = isinf(b) | isinf(Ax) | isnan(b);
if any(remove)
remove = find(remove);
Ax(remove)=[];
b(remove)=[];
Ay(remove)=[];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
invsathub.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/invsathub.m
| 3,871 |
utf_8
|
36f5bf3e2525f27b871df12fa5223c98
|
function varargout = invsathub (varargin)
%INVSATHUB (overloaded)
switch class(varargin{1})
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','none','definiteness','positive','model','callback');
operator.bounds = @bounds;
operator.convexhull = @convexhull;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/INVSATHUB called with CHAR argument?');
end
function [L,U] = bounds(xL,xU,lambda)
fL = invsathub(xL,lambda);
fU = invsathub(xU,lambda);
U = max(fL,fU);
L = min(fL,fU);
if xL<0 & xU>0
L = 0;
end
function [Ax, Ay, b, K] = convexhull(xL,xU,lambda)
K.l = 0;
K.f = 0;
fL = invsathub(xL,lambda);
fU = invsathub(xU,lambda);
if xU < -3*lambda % 1
Ax = 0;Ay = 1;b = 3*lambda;K.f = 1;
elseif xL>=-lambda & xU <= 0 % 2
Ax = 1;Ay = 1; b = 0;K.f = 1;
elseif xL>=0 & xU <= lambda % 3
Ax = 1;Ay = -1; b = 0;K.f = 1;
elseif xU<=0 | xL>=0 %4
dfL = derivative(xL,lambda);
dfU = derivative(xU,lambda);
[Ax,Ay,b,K] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);
elseif xL<0 & xL>=-lambda & xU>0 & xU<= lambda % 5
[Ax,Ay,b,K] = convexhullConvex(xL,xU,fL,fU,-lambda,lambda);
elseif 0%xL<=-lambda & xL>=-3*lambda
z = [xL 0 xU];
fz = [fL 0 fU];
k1 = max((fz(2:end)-fz(1))./(z(2:end)-xL))+1e-12;
k2 = min((fz(2:end)-fz(1))./(z(2:end)-xL))-1e-12;
k3 = min((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))+1e-12;
k4 = max((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))-1e-12;
Ax = [-k1;k2;-k3;k4];
Ay = [1;-1;1;-1];
b = [k1*(-z(1)) + fz(1);-(k2*(-z(1)) + fz(1));k3*(-z(end)) + fz(end);-(k4*(-z(end)) + fz(end))];
K.l = length(b);
elseif xL<-3*lambda & xU>3*lambda
z = [xL 0 xU];
fz = [fL 0 fU];
k1 = max((fz(2:end)-fz(1))./(z(2:end)-xL))+1e-12;
k2 = min((fz(2:end)-fz(1))./(z(2:end)-xL))-1e-12;
k3 = min((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))+1e-12;
k4 = max((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))-1e-12;
Ax = [-k1;k2;-k3;k4];
Ay = [1;-1;1;-1];
b = [k1*(-z(1)) + fz(1);-(k2*(-z(1)) + fz(1));k3*(-z(end)) + fz(end);-(k4*(-z(end)) + fz(end))];
K.l = length(b);
% clf
% x = linspace(xL,xU,1000);
% plot(polytope([Ax Ay],b)); hold on
% plot(x,invsathub(x,lambda))
% 1
else
z = [linspace(xL,xU,100)];
fz = [invsathub(z,lambda)];
if xU>0 & xL<0
z = [0 z];
fz = [0 fz];
end
[minval,minpos] = min(fz);
[maxval,maxpos] = max(fz);
xtestmin = linspace(z(max([1 minpos-5])),z(min([100 minpos+5])),100);
xtestmax = linspace(z(max([1 maxpos-5])),z(min([100 maxpos+5])),100);
fz1 = invsathub(xtestmin,lambda);
fz2 = invsathub(xtestmax,lambda);
z = [z(:);xtestmin(:);xtestmax(:)];
fz = [fz(:);fz1(:);fz2(:)];
[z,sorter] = sort(z);
fz = fz(sorter);
[z,ii,jj]=unique(z);
fz = fz(ii);
k1 = max((fz(2:end)-fz(1))./(z(2:end)-xL))+1e-12;
k2 = min((fz(2:end)-fz(1))./(z(2:end)-xL))-1e-12;
k3 = min((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))+1e-12;
k4 = max((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))-1e-12;
Ax = [-k1;k2;-k3;k4];
Ay = [1;-1;1;-1];
b = [k1*(-z(1)) + fz(1);-(k2*(-z(1)) + fz(1));k3*(-z(end)) + fz(end);-(k4*(-z(end)) + fz(end))];
K.l = length(b);
end
%
% clf
% x = linspace(xL,xU,1000);
% plot(polytope([Ax Ay],b)); hold on
% plot(x,invsathub(x,lambda))
% 1
function df=derivative(x,lambda)
if nargin==1
lambda=0.5;
end
df = 0;
if (-3*lambda < x) & (x < -lambda)
df = -0.25*(2*x+6*lambda);
elseif (-lambda < x) & (x < 0)
df = -lambda;
elseif (x>0) & (x<lambda)
df = lambda;
elseif (x>lambda) & (x<3*lambda)
df = -0.25*(2*x-6*lambda);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
tanh.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/tanh.m
| 783 |
utf_8
|
30538db981e451f6b520b7c7895a8e3d
|
function varargout = tanh(varargin)
%TANH (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/TANH CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','increasing','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)(1-tanh(x).^2);
operator.range = [-1 1];
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/TANH called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = cosh(xL);
U = cosh(xU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
acot.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/acot.m
| 807 |
utf_8
|
8bec7762540393b0aae6b6b9ebc2864a
|
function varargout = acot(varargin)
%ACOT (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/ACOT CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)(-(1 + x.^2).^-1);
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ACOT called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xL<=0 & xU >=0
L = -inf;
U = inf;
else
L = acot(xU);
U = acot(xL);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
subsasgn.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/subsasgn.m
| 10,156 |
utf_8
|
0a2475237bd1aeaaf6ae5439d0435c39
|
function y = subsasgn(X,I,Y)
%SUBASGN (overloaded)
try
if strcmp('()',I.type)
X_is_spdvar = isa(X,'sdpvar') | isa(X,'ndsdpvar');
Y_is_spdvar = isa(Y,'sdpvar') | isa(Y,'ndsdpvar');
if islogical(I.subs{1})
I.subs{1} = double(find(I.subs{1}));
end
if any(I.subs{1} <=0)
error('Index into matrix is negative or zero.');
end
switch 2*X_is_spdvar+Y_is_spdvar
case 1
% This code does not work properly
% Only work if b is undefined!!?!!
% generally ugly code...
y = Y;
[n_y,m_y] = size(Y);
y_lmi_variables = y.lmi_variables;
try
X0 = subsasgn(full(X),I,full(reshape(Y.basis(:,1),n_y,m_y)));
dim = size(X0);
y.basis = reshape(X0,prod(dim),1);
X = full(X)*0;
for i = 1:length(y_lmi_variables)
X0 = subsasgn(X,I,full(reshape(Y.basis(:,i+1),n_y,m_y)));
y.basis(:,i+1) = reshape(X0,prod(dim),1);
end
y.dim = dim;
% Reset info about conic terms
y.conicinfo = [0 0];
y.basis = sparse(y.basis);
if length(dim)>2
y = ndsdpvar(y);
end
y = flush(y);
catch
error(lasterr)
end
case 2
if ~isempty(Y)
Y = sparse(double(Y));
end
y = X;
% Special code for speed
% elements in vector replaced with constants
if min(X.dim(1),X.dim(2))==1 & (length(I.subs)==1)
y = X;
if isempty(Y)
y.basis(I.subs{1},:) = [];
if X.dim(1) == 1
y.dim(2) = y.dim(2) - length(unique(I.subs{1}));
else
y.dim(1) = y.dim(1) - length(unique(I.subs{1}));
end
else
y.basis(I.subs{1},1) = Y;
y.basis(I.subs{1},2:end) = 0;
end
if prod(y.dim)~=size(y.basis,1)
% Ah bugger, the dimension of the object was changed)
aux = X.basis(:,1);
aux = reshape(aux,X.dim);
aux(I.subs{1})=Y;
y.dim = size(aux);
end
y = clean(y);
% Reset info about conic terms
if isa(y,'sdpvar')
y.conicinfo = [0 0];
y = flush(y);
end
return;
end
x_lmi_variables = X.lmi_variables;
lmi_variables = [];
n = y.dim(1);
m = y.dim(2);
subX = sparse(subsasgn(full(reshape(X.basis(:,1),n,m)),I,Y));
y.basis = subX(:);
if isa(I.subs{1},'char')
I.subs{1} = 1:n;
end
if length(I.subs)>1
if isa(I.subs{2},'char')
I.subs{2} = 1:m;
end
end
if length(I.subs)>1
if length(I.subs{1})==1 & length(I.subs{2})~=1
I.subs{1} = repmat(I.subs{1},size(I.subs{2},1),size(I.subs{2},2));
elseif length(I.subs{2})==1 & length(I.subs{1})~=1
I.subs{2} = repmat(I.subs{2},size(I.subs{1},1),size(I.subs{1},2));
end
end
if length(I.subs)>1
ii = kron(I.subs{1}(:),ones(length(I.subs{2}),1));
jj = kron(ones(length(I.subs{1}),1),I.subs{2}(:));
LinearIndex = sub2ind([n m],ii,jj);
else
LinearIndex = I.subs{1};
end
if isempty(Y)
X.basis = X.basis(:,2:end);
X.basis(LinearIndex,:) = [];
y.basis = [y.basis(:,1) X.basis];
else
X.basis(LinearIndex,2:end)=sparse(0);
y.basis = [y.basis(:,1) X.basis(:,2:end)];
end
y.dim(1) = size(subX,1);
y.dim(2) = size(subX,2);
y = clean(y);
if isa(y,'sdpvar')
% Reset info about conic terms
y.conicinfo = [0 0];
y = flush(y);
end
case 3
z = X;
x_lmi_variables = X.lmi_variables;
y_lmi_variables = Y.lmi_variables;
% In a first run, we fix the constant term and null terms in the X basis
lmi_variables = [];
nx = X.dim(1);
mx = X.dim(2);
ny = Y.dim(1);
my = Y.dim(2);
if (mx==1) & (my == 1) & isempty(setdiff(y_lmi_variables,x_lmi_variables)) & (max(I.subs{1}) < nx) & length(I.subs)==1 & length(unique(I.subs{1}))==length(I.subs{1}) ;
% Fast specialized code for Didier
y = specialcode(X,Y,I);
return
end
subX = subsasgn(reshape(X.basis(:,1),nx,mx),I,reshape(Y.basis(:,1),ny,my));
[newnx, newmx] = size(subX);
j = 1;
yz = reshape(1:ny*my,ny,my);
subX2 = subsasgn(reshape(zeros(nx*mx,1),nx,mx),I,yz);
subX2 = subX2(:);
[ix,jx,sx] = find(subX2);
yz = 0*reshape(Y.basis(:,1),ny,my);
lmi_variables = zeros(1,length(x_lmi_variables));
A = reshape(1:nx*mx,nx,mx);
B = reshape(1:newnx*newmx,newnx,newmx);
rm = B(1:nx,1:mx);rm = rm(:);
[iix,jjx,ssx] = find(X.basis(:,2:end));
z.basis = [subX(:) sparse(rm(iix),jjx,ssx,newnx*newmx,size(X.basis,2)-1)];
z.basis(ix,2:end) = 0;
keep = find(any(z.basis(:,2:end),1));
z.basis = z.basis(:,[1 1+keep]);
lmi_variables2 = x_lmi_variables(keep);
z.lmi_variables = lmi_variables2;
lmi_variables = lmi_variables2;
all_lmi_variables = union(lmi_variables,y_lmi_variables);
in_z = ismembcYALMIP(all_lmi_variables,lmi_variables);
in_y = ismembcYALMIP(all_lmi_variables,y_lmi_variables);
z_ind = 2;
y_ind = 2;
basis = spalloc(size(z.basis,1),1+length(all_lmi_variables),0);
basis(:,1) = z.basis(:,1);
nz = size(subX,1);
mz = size(subX,2);
template = full(0*reshape(X.basis(:,1),nx,mx));
in_yin_z = 2*in_y + in_z;
if all(in_yin_z<3)
case1 = find(in_yin_z==1);
if ~isempty(case1)
basis(:,case1+1) = z.basis(:,2:1+length(case1));
in_yin_z(case1) = 0;
end
end
for i = 1:length(all_lmi_variables)
switch in_yin_z(i)
case 1
basis(:,i+1) = z.basis(:,z_ind);z_ind = z_ind+1;
case 2
temp = sparse(subsasgn(template,I,full(reshape(Y.basis(:,y_ind),ny,my))));
basis(:,i+1) = temp(:);
y_ind = y_ind+1;
case 3
Z1 = z.basis(:,z_ind);
Z4 = Y.basis(:,y_ind);
Z3 = reshape(Z4,ny,my);
Z2 = sparse(subsasgn(0*reshape(full(X.basis(:,1)),nx,mx),I,Z3));
temp = reshape(Z1,nz,mz)+Z2;
basis(:,i+1) = temp(:);
z_ind = z_ind+1;
y_ind = y_ind+1;
otherwise
end
end;
z.dim(1) = nz;
z.dim(2) = mz;
z.basis = basis;
z.lmi_variables = all_lmi_variables(:)';
y = z;
% Reset info about conic terms
y.conicinfo = [0 0];
y = flush(y);
otherwise
end
else
error('Reference type not supported');
end
catch
error(lasterr)
end
function y = specialcode(X,Y,I)
y = X;
X_basis = X.basis;
Y_basis = Y.basis;
ind = I.subs{1};ind = ind(:);
yvar_in_xvar = zeros(length(Y.lmi_variables),1);
for i = 1:length(Y.lmi_variables);
yvar_in_xvar(i) = find(X.lmi_variables==Y.lmi_variables(i));
end
y.basis(ind,:) = 0;
mapper = [1 1+yvar_in_xvar(:)'];mapper = mapper(:);
[i,j,k] = find(y.basis);
[ib,jb,kb] = find(Y_basis);
i = [i(:);ind(ib(:))];
j = [j(:);mapper(jb(:))];
k = [k(:);kb(:)];
y.basis = sparse(i,j,k,size(y.basis,1),size(y.basis,2));
y = clean(y);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
atan.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/atan.m
| 1,152 |
utf_8
|
071999f9ece4ebf3e24f7eb58e385149
|
function varargout = atan(varargin)
%ATAN (overloaded)
switch class(varargin{1})
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','increasing','definiteness','none','model','callback');
operator.convexhull = @convexhull;
operator.bounds = @bounds;
operator.derivative = @(x)((1+x.^2).^-1);
operator.inverse = @(x)(tan(x));
operator.range = [-pi/2 pi/2];
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ATAN called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = atan(xL);
U = atan(xU);
function [Ax, Ay, b] = convexhull(xL,xU)
fL = atan(xL);
fU = atan(xU);
dfL = 1/(1+xL^2);
dfU = 1/(1+xU^2);
if xL >= 0
% Concave region
[Ax,Ay,b] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);
elseif xU <= 0
% Convex region
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
else
% Changes convexity. We're lazy and let YALMIP sample instead
Ax = [];
Ay = [];
b = [];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sqrt.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/sqrt.m
| 3,036 |
utf_8
|
dbdc41fb98e355d38f7827f44c1095b5
|
function varargout = sqrt(varargin)
%SQRT (overloaded)
%
% t = sqrt(x)
%
% The variable t can only be used in concavity preserving
% operations such as t>=1, max t etc.
%
% When SQRT is used in a problem, the domain constraint
% (x>=0) is automatically added to the problem.
%
% In nonconvex cases, use sqrtm instead.
%
% See also CPOWER
switch class(varargin{1})
case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.
X = varargin{1};
[n,m] = size(X);
if is(varargin{1},'real') %& (n*m==1)
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
else
error('SQRT can only be applied to real scalars');
end
case 'char' % YALMIP send 'model' when it wants the epigraph or hypograph
switch varargin{1}
case 'graph'
t = varargin{2}; % Second arg is the extended operator variable
X = varargin{3}; % Third arg and above are the args user used when defining t.
if is(X,'linear')
varargout{1} = (cone([(X-1)/2;t],(X+1)/2));
varargout{2} = struct('convexity','concave','monotonicity','increasing','definiteness','positive');
varargout{3} = X;
elseif is(X,'quadratic')
[F,x] = check_for_special_cases(X,t);
if isempty(F)
varargout{1} = [];
varargout{2} = [];
varargout{3} = [];
else
varargout{1} = F;
varargout{2} = struct('convexity','convex','monotonicity','none','definiteness','positive');
varargout{3} = x;
end
else
varargout{1} = [];
varargout{2} = [];
varargout{3} = [];
end
otherwise
varargout{1} = [];
varargout{2} = [];
varargout{3} = [];
end
otherwise
end
function [F,x] = check_for_special_cases(q,t)
% Check if user is constructing sqrt(quadratic). If that is the case,
% return norm(linear)
F = [];
x = [];
if length(q)>1
return
end
[Q,c,f,x,info] = quaddecomp(q);
if info==0 & nnz(Q)>0
index = find(any(Q,2));
if length(index) < length(Q)
Qsub = Q(index,index);
[Rsub,p]=chol(Qsub);
if p==0
[i,j,k] = find(Rsub);
R = sparse((i),index(j),k,length(Qsub),length(Q));
else
R = [];
end
else
[R,p]=chol(Q);
if p & min(eig(full(Q)))>=-1e-12
[U,S,V] = svd(full(Q));
r = max(find(diag(S)));
R = sqrtm(S(1:r,1:r))*V(:,1:r)';
p = 0;
end
end
d = 0.5*(R'\c);
if p==0 & f-d'*d>-1e-12
F = cone([R*x+d;sqrt(f-d'*d)],t);
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
exp.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/exp.m
| 1,481 |
utf_8
|
955d4798dee16d92e6cae7aa58a9527a
|
function varargout = exp(varargin)
%EXP (overloaded)
switch class(varargin{1})
case 'sdpvar'
x = varargin{1};
d = size(x);
x = x(:);
y = [];
for i = 1:prod(d)
xi = extsubsref(x,i);
if isreal(xi)
y = [y;InstantiateElementWise(mfilename,xi)];
else
y = [y;cos(xi) + sqrt(-1)*sin(xi)];
end
end
varargout{1} = reshape(y,d);
case 'char'
varargout{1} = [];
varargout{2} = createOperator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/EXP called with CHAR argument?');
end
function operator = createOperator
operator = struct('convexity','convex','monotonicity','increasing','definiteness','positive','model','callback');
operator.convexhull = @convexhull;
operator.bounds = @bounds;
operator.derivative = @(x)exp(x);
operator.inverse = @(x)log(x);
operator.range = [0 inf];
% Bounding functions for the branch&bound solver
function [L,U] = bounds(xL,xU)
L = exp(xL);
U = exp(xU);
function [Ax, Ay, b, K] = convexhull(xL,xU)
fL = exp(xL);
fU = exp(xU);
if fL == fU
Ax = [];
Ay = [];
b = [];
else
dfL = exp(xL);
dfU = exp(xU);
% A cut with tangent parallell to upper bound is very efficient
xM = log((fU-fL)/(xU-xL));
fM = exp(xM);
dfM = exp(xM);
[Ax,Ay,b] = convexhullConvex(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
end
K = [];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
times.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/times.m
| 11,578 |
utf_8
|
446a9d604ec704ba3af6d3c341e133f8
|
function y = times(X,Y)
%TIMES (overloaded)
% Check dimensions
[n,m]=size(X);
if ~((prod(size(X))==1) || (prod(size(Y))==1))
if ~((n==size(Y,1) && (m ==size(Y,2))))
error('Matrix dimensions must agree.')
end
end;
% Convert block objects
if isa(X,'blkvar')
X = sdpvar(X);
end
if isa(Y,'blkvar')
Y = sdpvar(Y);
end
if isa(X,'double')
if any(isnan(X))
error('Multiplying NaN with an SDPVAR makes no sense.');
end
end
if isa(Y,'double')
if any(isnan(Y))
error('Multiplying NaN with an SDPVAR makes no sense.');
end
end
if isempty(X)
YY = full(reshape(Y.basis(:,1),Y.dim(1),Y.dim(2)));
y = X.*YY;
return
elseif isempty(Y)
XX = full(reshape(X.basis(:,1),X.dim(1),X.dim(2)));
y = XX.*Y;
return
end
if (isa(X,'sdpvar') && isa(Y,'sdpvar'))
X = flush(X);
Y = flush(Y);
if (X.typeflag==5) && (Y.typeflag==5)
error('Product of norms not allowed');
end
try
y = check_for_special_case(Y,X);
if ~isempty(y)
return
end
% Check for the case x.*y where x and y are unit variables
[mt,variable_type,hashedMT,hash] = yalmip('monomtable');
if length(X.lmi_variables)==numel(X)
if length(Y.lmi_variables) == numel(Y)
if numel(X)==numel(Y)
% This looks promising. write as (x0+X)*(y0+Y)
X0 = reshape(X.basis(:,1),X.dim);
Y0 = reshape(Y.basis(:,1),Y.dim);
Xsave = X;
Ysave = Y;
X.basis(:,1)=0;
Y.basis(:,1)=0;
if nnz(X.basis)==numel(X)
if nnz(Y.basis)==numel(Y)
D = [spalloc(numel(Y),1,0) speye(numel(Y))];
if isequal(X.basis,D)
if isequal(Y.basis,D)
% Pew.
Z = X;
generated_monoms = mt(X.lmi_variables,:) + mt(Y.lmi_variables,:);
generated_hash = generated_monoms*hash;
keep = zeros(1,numel(X));
if all(generated_hash) && all(diff(sort([generated_hash;hashedMT])))
Z.lmi_variables = size(mt,1)+(1:numel(X));
keep = keep + 1;
else
for i = 1:numel(X)
if generated_hash(i)
before = find(abs(hashedMT-generated_hash(i))<eps);
if isempty(before)
% mt = [mt;generated_monoms(i,:)];
keep(i) = 1;
Z.lmi_variables(i) = size(mt,1)+nnz(keep);
else
Z.lmi_variables(i) = before;
end
else
Z.lmi_variables(i) = 0;
end
end
end
if any(keep)
keep = find(keep);
mt = [mt;generated_monoms(keep,:)];
yalmip('setmonomtable',mt,[],[hashedMT;generated_hash(keep)],hash);
end
if any(diff(Z.lmi_variables)<0)
[i,j]=sort(Z.lmi_variables);
Z.lmi_variables = Z.lmi_variables(j);
Z.basis(:,2:end) = Z.basis(:,j+1);
end
if Z.lmi_variables(1)==0
i = find(Z.lmi_variables == 0);
Z.basis(:,1) = sum(Z.basis(:,1+i),2);
Z.basis(:,1+i)=[];
end
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = Z + X0.*Y0 + X0.*Y + X.*Y0;
Z = flush(Z);
y = clean(Z);
return
end
end
end
end
end
X = Xsave;
Y = Ysave;
end
end
x_isscalar = (X.dim(1)*X.dim(2)==1);
y_isscalar = (Y.dim(1)*Y.dim(2)==1);
all_lmi_variables = uniquestripped([X.lmi_variables Y.lmi_variables]);
Z = X;Z.dim(1) = 1;Z.dim(2) = 1;Z.lmi_variables = all_lmi_variables;Z.basis = [];
% Awkward code due to bug in ML6.5
Xbase = reshape(X.basis(:,1),X.dim(1),X.dim(2));
Ybase = reshape(Y.basis(:,1),Y.dim(1),Y.dim(2));
if x_isscalar
Xbase = sparse(full(Xbase));
end
if y_isscalar
Ybase = sparse(full(Ybase));
end
index_Y = zeros(length(all_lmi_variables),1);
index_X = zeros(length(all_lmi_variables),1);
for j = 1:length(all_lmi_variables)
indexy = find(all_lmi_variables(j)==Y.lmi_variables);
indexx = find(all_lmi_variables(j)==X.lmi_variables);
if ~isempty(indexy)
index_Y(j) = indexy;
end
if ~isempty(indexx)
index_X(j) = indexx;
end
end
ny = Y.dim(1);
my = Y.dim(2);
nx = X.dim(1);
mx = X.dim(2);
% Linear terms
base = Xbase.*Ybase;
Z.basis = base(:);
x_base_not_zero = nnz(Xbase)>0;
y_base_not_zero = nnz(Ybase)>0;
for i = 1:length(all_lmi_variables)
base = 0;
if index_Y(i) && x_base_not_zero
base = Xbase.*getbasematrixwithoutcheck(Y,index_Y(i));
end
if index_X(i) && y_base_not_zero
base = base + getbasematrixwithoutcheck(X,index_X(i)).*Ybase;
end
Z.basis(:,i+1) = base(:);
end
% Nonlinear terms
i = i+1;
ix=1;
new_mt = [];
%mt = yalmip('monomtable');
nvar = length(all_lmi_variables);
local_mt = mt(all_lmi_variables,:);
theyvars = find(index_Y);
thexvars = find(index_X);
hash = randn(size(mt,2),1);
mt_hash = mt*hash;
for ix = thexvars(:)'
% if mx==1
Xibase = X.basis(:,1+index_X(ix));
% else
% Xibase = reshape(X.basis(:,1+index_X(ix)),nx,mx);
% end
mt_x = local_mt(ix,:);
y_basis = Y.basis(:,1+index_Y(theyvars));
x_basis = repmat(Xibase,1,length(theyvars(:)'));
if y_isscalar && ~x_isscalar
y_basis = repmat(y_basis,nx*mx,1);
elseif x_isscalar && ~y_isscalar
x_basis = repmat(x_basis,ny*my,1);
end
allBase = x_basis.*y_basis;
jjj = 1;
usedatall = find(any(allBase,1));
% for iy = theyvars(:)'
for iy = theyvars(usedatall(:))'
% ff=Y.basis(:,1+index_Y(iy));
% Yibase = reshape(ff,ny,my);
% prodbase = Xibase.*Yibase;
prodbase = allBase(:,usedatall(jjj));jjj = jjj+1;
% prodbase = reshape(prodbase,ny,my);
if (norm(prodbase,inf)>1e-12)
mt_y = local_mt(iy,:);
% Idiot-hash the lists
new_hash = (mt_x+mt_y)*hash;
if abs(new_hash)<eps%if nnz(mt_x+mt_y)==0
Z.basis(:,1) = Z.basis(:,1) + prodbase(:);
else
before = find(abs(mt_hash-(mt_x+mt_y)*hash)<eps);
if isempty(before)
mt = [mt;mt_x+mt_y];
mt_hash = [mt_hash;(mt_x+mt_y)*hash];
Z.lmi_variables = [Z.lmi_variables size(mt,1)];
else
Z.lmi_variables = [Z.lmi_variables before];
end
Z.basis(:,i+1) = prodbase(:);i = i+1;
end
end
end
end
% Fucked up order
if any(diff(Z.lmi_variables)<0)
[i,j]=sort(Z.lmi_variables);
Z.lmi_variables = Z.lmi_variables(j);
Z.basis(:,2:end) = Z.basis(:,j+1);
end
% FIX : Speed up
if length(Z.lmi_variables) ~=length(unique(Z.lmi_variables))
un_Z_vars = unique(Z.lmi_variables);
newZbase = Z.basis(:,1);
for i = 1:length(un_Z_vars)
newZbase = [newZbase sum(Z.basis(:,find(un_Z_vars(i)==Z.lmi_variables)+1),2)];
end
Z.basis = newZbase;
Z.lmi_variables = un_Z_vars;
end
yalmip('setmonomtable',mt);
if ~(x_isscalar || y_isscalar)
Z.dim(1) = X.dim(1);
Z.dim(2) = Y.dim(2);
else
Z.dim(1) = max(X.dim(1),Y.dim(1));
Z.dim(2) = max(X.dim(2),Y.dim(2));
end
catch
error(lasterr)
end
% Reset info about conic terms
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = flush(Z);
y = clean(Z);
return
end
if isa(X,'sdpvar')
Z = X;
X = Y;
Y = Z;
end
y = Y;
if prod(Y.dim)==1
y.basis = X(:)*(y.basis);
y.dim = size(X);
else
y.basis = [(Y.basis.')*diag(sparse(X(:)))].';
end
% Reset info about conic terms
y.conicinfo = [0 0];
Z.extra.opname='';
y = flush(y);
y = clean(y);
function y = check_for_special_case(Y,X);
y = [];
if (min(size(X))>1) || (min(size(Y))>1)
return
end
if ~all(size(Y)==size(X))
return
end
entropies = zeros(length(Y),1);
if is(X,'linear')
argst = yalmip('getarguments',Y);
if length(argst)~=length(X)
return
end
if length(argst) == 1
args{1} = argst;
else
args = argst;
end
for i = 1:length(args)
if isempty(args{i})
return
end
if isequal(args{i}.fcn,'log')
S(1).subs={i};
S(1).type='()';
Z = subsref(X,S);
if isequal(Z.basis,args{i}.arg{1}.basis)
if isequal(Z.lmi_variables,args{i}.arg{1}.lmi_variables)
entropies(i) = 1;
end
end
end
end
end
if all(entropies)
y = -ventropy(X);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
erf.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/erf.m
| 2,291 |
utf_8
|
34e3cf2135d769bd1d33bc39a72655bd
|
function varargout = erf(varargin)
%ERF (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/ERF CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','increasing','definiteness','none','model','callback');
operator.bounds = @bounds;
operator.range = [-1 1];
operator.derivative =@(x)exp(-x.^2)*2/sqrt(pi);
operator.inverse = @(x)(erfinv(x));
operator.convexhull = @convexhull;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ERF called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = erf(xL);
U = erf(xU);
function [Ax, Ay, b, K] = convexhull(xL,xU)
K = [];
if xU <= 0
xM = (xL+xU)/2;
fL = erf(xL);
fM = erf(xM);
fU = erf(xU);
dfL = exp(-xL.^2)*2/sqrt(pi);
dfM = exp(-xM.^2)*2/sqrt(pi);
dfU = exp(-xU.^2)*2/sqrt(pi);
[Ax,Ay,b] = convexhullConvex(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
elseif xL >= 0
xM = (xL+xU)/2;
fL = erf(xL);
fM = erf(xM);
fU = erf(xU);
dfL = exp(-xL.^2)*2/sqrt(pi);
dfM = exp(-xM.^2)*2/sqrt(pi);
dfU = exp(-xU.^2)*2/sqrt(pi);
[Ax,Ay,b] = convexhullConcave(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
else
z = linspace(xL,xU,1000);
fz = erf(z);
[minval,minpos] = min(fz);
[maxval,maxpos] = max(fz);
xtestmin = linspace(z(max([1 minpos-5])),z(min([100 minpos+5])),100);
xtestmax = linspace(z(max([1 maxpos-5])),z(min([100 maxpos+5])),100);
fz1 = erf(xtestmin);
fz2 = erf(xtestmax);
z = [z(:);xtestmin(:);xtestmax(:)];
fz = [fz(:);fz1(:);fz2(:)];
[z,sorter] = sort(z);
fz = fz(sorter);
[z,ii,jj]=unique(z);
fz = fz(ii);
k1 = max((fz(2:end)-fz(1))./(z(2:end)-xL))+1e-12;
k2 = min((fz(2:end)-fz(1))./(z(2:end)-xL))-1e-12;
k3 = min((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))+1e-12;
k4 = max((fz(1:end-1)-fz(end))./(z(1:end-1)-xU))-1e-12;
Ax = [-k1;k2;-k3;k4];
Ay = [1;-1;1;-1];
b = [k1*(-z(1)) + fz(1);-(k2*(-z(1)) + fz(1));k3*(-z(end)) + fz(end);-(k4*(-z(end)) + fz(end))];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
erfc.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/erfc.m
| 756 |
utf_8
|
d1523f1dce8b03ea7377827749ac68ef
|
function varargout = erfc(varargin)
%ERFC (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/ERFC CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','decreasing','definiteness','positive','model','callback');
operator.bounds = @bounds;
operator.range = [-1 1];
operator.derivative =@(x)-exp(-x.^2)*2/sqrt(pi);
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ERF called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = erfc(xL);
U = erfc(xU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
power.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/power.m
| 3,973 |
utf_8
|
840a5282a2173feba3ea38f581a42286
|
function y = power(x,d)
%POWER (overloaded)
% Vectorize x if d is vector
if numel(x)==1 & (numel(d)>1)
x = x.*ones(size(d));
end
% Vectorize if x is a vector
if numel(d)==1 & (numel(x)>1)
d = d.*ones(size(x));
end
if ~isequal(size(d),size(x))
error('Dimension mismatch in power');
end
if isa(x,'sdpvar')
x = flush(x);
end
% Reuse code
if numel(x)==1 && numel(d)==1
y = mpower(x,d);
return
end
if isa(d,'sdpvar')
% Call helper which vectorizes the elements
y = powerinternalhelper(d,x);
return
end
% Sanity Check
if prod(size(d))>1
if any(size(d)~=size(x))
error('Matrix dimensions must agree.');
end
else
d = ones(x.dim(1),x.dim(2))*d;
end
% Trivial cases
if isa(d,'double')
if all(all(d==0))
if x.dim(1)~=x.dim(2)
error('Matrix must be square.')
end
y = eye(x.dim(1),x.dim(2)).^0;
return
end
if all(all(d==1))
y = x;
return
end
end
% Fractional, negative or different powers are
% treated less efficiently using simple code.
fractional = any(any((ceil(d)-d>0)));
negative = any(any(d<0));
different = ~all(all(d==d(1)));
if fractional | negative | different
if x.dim(1)>1 | x.dim(2)>1
if isequal(x.basis,[spalloc(prod(x.dim),1,0) speye(prod(x.dim))]) & all(d==d(1))
% Simple case x.^d
y = vectorizedUnitPower(x,d);
return
end
[n,m] = size(x);
y = [];
for i = 1:n % FIX : Vectorize!
if m == 1
temp = extsubsref(x,i,1).^d(i,1);
else
temp = [];
for j = 1:m
temp = [temp extsubsref(x,i,j).^d(i,j)];
end
end
y = [y;temp];
end
return
else
base = getbase(x);
if isequal(base,[0 1])
mt = yalmip('monomtable');
var = getvariables(x);
previous_var = find((mt(:,var)==d) & (sum(mt~=0,2)==1));
if isempty(previous_var)
mt(end+1,:) = mt(getvariables(x),:)*d;
yalmip('setmonomtable',mt);
y = recover(size(mt,1));
else
y = recover(previous_var);
end
elseif (size(base,2) == 2) & base(1)==0
% Something like a*t^-d
y = base(2)^d*recover(getvariables(x))^d;
else
error('Only unit scalars can have negative or non-integer powers.');
end
end
return
end
if isequal(x.basis,[spalloc(prod(x.dim),1,0) speye(prod(x.dim))]) & all(d==d(1))
% Simple case x.^d
y = vectorizedUnitPower(x,d);
return
end
% Back to scalar power...
d = d(1,1);
if x.dim(1)>1 | x.dim(2)>1
switch d
case 0
y = 1;
case 1
y = x;
otherwise
y = x.*power(x,d-1);
end
else
error('This should not appen. Report bug (power does not use mpower)')
end
function y = vectorizedUnitPower(x,d)
d = d(1);
[mt,variabletype,hashM,hash] = yalmip('monomtable');
var = getvariables(x);
usedmt = mt(var,:);
newmt = usedmt*d;
hashV = newmt*hash;
if ~any(ismember(hashV,hashM))
variabletype = [variabletype newvariabletypegen(newmt)];
y = size(mt,1) + (1:length(var));
mt = [mt;newmt];
else
y = [];
allnewmt = [];
newvariables = 0;
keep = zeros(size(usedmt,1),1);
for i = 1:length(hashV)
previous_var = find(abs(hashM - hashV(i)) < 1e-20);
if isempty(previous_var)
newmt = usedmt(i,:)*d;
variabletype = [variabletype newvariabletypegen(newmt)];
newvariables = newvariables + 1;
keep(i) = 1;
y = [y size(mt,1)+newvariables];
else
y = [y previous_var];
end
end
mt = [mt;usedmt(find(keep),:)*d];
end
yalmip('setmonomtable',mt,variabletype);
y = reshape(recover(y),x.dim);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
asin.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/asin.m
| 733 |
utf_8
|
3100afdb50eaff864a0e7f6331e7452b
|
function varargout = asin(varargin)
%ASIN (overloaded)
switch class(varargin{1})
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','increasing','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)((1 - x.^2).^-0.5);
operator.range = [-pi/2 pi/2];
operator.domain = [-1 1];
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ASIN called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = asin(xL);
U = asin(xU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
lmior.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/lmior.m
| 1,467 |
utf_8
|
cc3cd29a91a762b089e33a55547aac55
|
function varargout = lmior(varargin)
%OR (overloaded)
% Models OR using a nonlinear operator definition
switch class(varargin{1})
case 'char'
z = varargin{2};
allextvars = yalmip('extvariables');
X = {};
for i = 3:nargin
Xtemp = expandor(varargin{i},allextvars);
for j = 1:length(Xtemp)
X{end + 1} = Xtemp{j};
end
end
F = ([]);
x = binvar(length(X),1);
for i = 1:length(X)
F = F + (implies_internal(extsubsref(x,i),X{i}));
end
varargout{1} = F + (sum(x) >= 1);
varargout{2} = struct('convexity','none','monotonicity','none','definiteness','none','extra','marker','model','integer');
varargout{3} = recover(depends(F));
case {'lmi'}
x = varargin{1};
y = varargin{2};
varargout{1} = (yalmip('define','lmior',varargin{:}) == 1);
otherwise
end
function x = expandor(x,allextvars)
if length(getvariables(x))>1
x = {x};
return;
end
xmodel = yalmip('extstruct',getvariables(x));
if ~isempty(xmodel) & isequal(xmodel.fcn,'lmior')
x1 = xmodel.arg{1};
x2 = xmodel.arg{2};
if ismembc(getvariables(x1),allextvars)
x1 = expandor(x1,allextvars);
else
x1 = {x1};
end
if ismembc(getvariables(x2),allextvars)
x2 = expandor(x2,allextvars);
else
x2 = {x2};
end
x = {x1{:},x2{:}};
else
x = {x};
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
ismember.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/ismember.m
| 3,414 |
utf_8
|
fb8583f41aa5b455ee06f14d295c8b5f
|
function varargout = ismember(varargin)
%ISMEMBER Define membership constraint on SDPVAR object
%
% F = ISMEMBER(x,P)
%
% Input
% x : SDPVAR object
% P : MPT polytope object, double, or CONSTRAINT object
% Output
% F : Constraints
%
% Depending on the second argument P, different classes of constraint are
% generated.
%
% If P is a single polytope, the linear constraints [H,K] = double(P);
% F=[H*x <= K] will be created.
%
% If P is a polytope array, then length(P) binary variables will be
% introduced and the constraint will model that x is inside at least one of
% the polytopes.
%
% If P is a vector of DOUBLE, a constraint constraining the elements of x
% to take one of the values in P is created. This will introduce
% numel(P)*numel(x) binary variables
%
% If P is matrix of DOUBLE, a constraint constraining the vector x to equal
% one of the columns of P is created. This will introduce size(P,2) binary
% variables
%
% Since the two last constructions are based on big-M formulations, all
% involved variable should have explicit variable bounds.
x = varargin{1};
p = varargin{2};
% Backwards compatibility (this should really be done in another command)
% This code is probably only used in solvemoment
if isa(x,'double')
varargout{1} = any(full(p.basis(:,1)));
return
end
if isa(x,'sdpvar') & isa(p,'sdpvar')
x_base = x.basis;
x_vars = x.lmi_variables;
p_base = x.basis;
p_vars = x.lmi_variables;
% Member at all
varargout{1} = ismember(x.lmi_variables,p.lmi_variables);
if varargout{1}
index_in_x_vars = find(x.lmi_variables == p.lmi_variables);
varargout{1} = full(any(p.basis(:,1+index_in_x_vars),2));
if min(p.dim(1),p.dim(2))~=1
varargout{1} = reshape(YESNO,p.dim(1),p.dim(2));
end
end
return
end
% Here is the real overloaded ismember
switch class(varargin{1})
case 'sdpvar'
if isa(varargin{1},'sdpvar') & (isa(varargin{2},'polytope') | isa(varargin{2},'Polyhedron'))
if ~isequal(length(varargin{1}),safe_dimension(varargin{2}))
disp('The polytope in the ismember condition has wrong dimension')
error('Dimension mismatch.');
end
end
if isa(varargin{2},'polytope') & length(varargin{2})==1
[H,K] = double(varargin{2});
varargout{1} = [H*x <= K];
elseif isa(varargin{2},'Polyhedron') & length(varargin{2})==1
%P = convexHull(varargin{2});
P = minHRep(varargin{2});
varargout{1} = [P.A*x <= P.b, P.Ae*x == P.be];
else
varargout{1} = (yalmip('define',mfilename,varargin{:}) == 1);
varargout{1} = setupMeta(lmi([]), mfilename,varargin{:});
if isa(varargin{2},'double')
if size(varargin{1},1) == size(varargin{2},1) % v in [v1 v2 v3]
varargout{1} = [ varargout{1}, min(varargin{2},[],2) <= varargin{1} <= max(varargin{2},[],2)];
else
varargout{1} = [ varargout{1}, min(min(varargin{2})) <= varargin{1}(:) <= max(max(varargin{2}))];
end
end
end
case 'char'
varargout{1} = ismember_internal(varargin{3},varargin{4});
end
function d = safe_dimension(P)
if isa(P,'polytope')
d = dimension(P);
elseif isa(P,'Polyhedron')
d = P.Dim;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
lmixor.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/lmixor.m
| 1,474 |
utf_8
|
08dbdab504839a1207e532b611ea5c1f
|
function varargout = lmixor(varargin)
%XOR (overloaded)
% Models XOR using a nonlinear operator definition
switch class(varargin{1})
case 'char'
z = varargin{2};
allextvars = yalmip('extvariables');
X = {};
for i = 3:nargin
Xtemp = expandxor(varargin{i},allextvars);
for j = 1:length(Xtemp)
X{end + 1} = Xtemp{j};
end
end
F = ([]);
x = binvar(length(X),1);
for i = 1:length(X)
F = F + (implies_internal(extsubsref(x,i),X{i}));
end
varargout{1} = F + (sum(x) == 1);
varargout{2} = struct('convexity','none','monotonicity','none','definiteness','none','extra','marker','model','integer');
varargout{3} = recover(depends(F));
case {'lmi'}
x = varargin{1};
y = varargin{2};
varargout{1} = (yalmip('define','lmior',varargin{:}) == 1);
otherwise
end
function x = expandxor(x,allextvars)
if length(getvariables(x))>1
x = {x};
return;
end
xmodel = yalmip('extstruct',getvariables(x));
if ~isempty(xmodel) & isequal(xmodel.fcn,'lmior')
x1 = xmodel.arg{1};
x2 = xmodel.arg{2};
if ismembc(getvariables(x1),allextvars)
x1 = expandxor(x1,allextvars);
else
x1 = {x1};
end
if ismembc(getvariables(x2),allextvars)
x2 = expandxor(x2,allextvars);
else
x2 = {x2};
end
x = {x1{:},x2{:}};
else
x = {x};
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
model.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/model.m
| 4,132 |
utf_8
|
875ed9e5691dfe8921448baee0c20edf
|
function [properties,F,arguments,fcn]=model(X,method,options,extstruct,w)
%MODEL Internal function to extracts nonlinear operator models
%
% [properties,F] = model(x)
%
% MODEL returns the constraints needed to model a variable related to an
% extended operator such as min, max, abs, norm, geomean, ...
%
% Examples :
%
% sdpvar x y;
% t = min(x,y);
% [properties,F] = model(t)
% Gives F = [t<=x, t<=y]
extvar = getvariables(X);
arguments = cell(1,length(extvar));
properties = cell(1,length(extvar));
if nargin<2
method = 'graph';
end
if nargin < 3
options = [];
end
if nargin < 5
% Not used
w = [];
end
if nargin<4
extstruct = yalmip('extstruct',extvar);
elseif isempty(extstruct)
extstruct = yalmip('extstruct',extvar);
end
if isempty(extstruct)
error('This is not a nonlinear operator variable');
end
fcn = extstruct.fcn;
try
n = yalmip('nvars');
[F,properties,arguments] = feval(fcn,method,extstruct.var,extstruct.arg{1:end-1});
if isa(F,'constraint')
F = lmi(F);
end
newAux = n+1:yalmip('nvars');
involved = getvariables(extstruct.arg{1});
for i = 2:length(extstruct.arg)-1
vars = getvariables(extstruct.arg{i});
if ~isempty(vars)
involved = union(involved,vars);
end
end
if ~isempty(options)
if ~(strcmp(options.robust.auxreduce,'none'))
% This info is only needed when we do advanced Robust optimization
yalmip('setdependence',[getvariables(extstruct.var) newAux],involved);
yalmip('setdependence',[getvariables(extstruct.var)],newAux);
end
end
catch
error(['Failed when trying to create a model for the "' extstruct.fcn '" operator']);
end
% Make sure all operators have these properties
if ~isempty(properties)
if ~iscell(properties)
properties = {properties};
end
for i = 1:length(properties)
properties{i}.name = fcn;
properties{i} = assertProperty(properties{i},'definiteness','none');
properties{i} = assertProperty(properties{i},'convexity','none');
properties{i} = assertProperty(properties{i},'monotonicity','none');
properties{i} = assertProperty(properties{i},'derivative',[]);
properties{i} = assertProperty(properties{i},'inverse',[]);
properties{i} = assertProperty(properties{i},'models',getvariables(extstruct.var));
properties{i} = assertProperty(properties{i},'convexhull',[]);
properties{i} = assertProperty(properties{i},'bounds',[]);
properties{i} = assertProperty(properties{i},'domain',[-inf inf]);
switch properties{i}.definiteness
case 'positive'
properties{i} = assertProperty(properties{i},'range',[0 inf]);
case 'negative'
properties{i} = assertProperty(properties{i},'range',[-inf 0]);
otherwise
properties{i} = assertProperty(properties{i},'range',[-inf inf]);
end
properties{i} = assertProperty(properties{i},'model','unspecified');
end
end
% Normalize the callback expression and check for some obsoleted stuff
if ~isempty(properties)
if isequal(properties{1}.model,'callback')
F_normalizing = NormalizeCallback(method,extstruct.var,extstruct.arg{:});
F = F + F_normalizing;
end
if length(extstruct.computes)>1
for i = 1:length(properties)
properties{i}.models = extstruct.computes;
end
end
for i = 1:length(properties)
if ~any(strcmpi(properties{i}.convexity,{'convex','concave','none'}))
disp('More cleaning, strange convextiy returned...Report bug in model.m')
error('More cleaning, strange convextiy returned...Report bug in model.m')
end
end
end
% This is useful in MPT
if ~isempty(F)
F = tag(F,['Expansion of ' extstruct.fcn]);
end
if ~isempty(properties)
% properties = properties{1};
end
function properties = assertProperty(properties,checkfor,default);
if ~isfield(properties,checkfor)
properties = setfield(properties,checkfor,default);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
log.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/log.m
| 2,585 |
utf_8
|
39c91997bea9e861421411a1caa9ff54
|
function varargout = log(varargin)
%LOG (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/LOG CALLED WITH DOUBLE. Report error')
case 'sdpvar'
% Try to detect logsumexp construction etc
varargout{1} = check_for_special_cases(varargin{:});
% Nope, then just define this logarithm
if isempty(varargout{1})
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
end
case 'char'
X = varargin{3};
F = (X >= 1e-8);
operator = struct('convexity','concave','monotonicity','increasing','definiteness','none','model','callback');
operator.convexhull = @convexhull;
operator.bounds = @bounds;
operator.domain = [0 inf];
operator.derivative = @(x)(1./(abs(x)+eps));
operator.inverse = @(x)(exp(x));
varargout{1} = F;
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/LOG called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xL <= 0
% The variable is not bounded enough yet
L = -inf;
else
L = log(xL);
end
if xU < 0
% This is an infeasible problem
L = inf;
U = -inf;
else
U = log(xU);
end
function [Ax, Ay, b, K] = convexhull(xL,xU)
K = [];
if xL <= 0
fL = inf;
else
fL = log(xL);
end
fU = log(xU);
dfL = 1/(xL);
dfU = 1/(xU);
%xM = (xU - xL)/(fU-fL);
xM = (xL + xU)/2;
fM = log(xM);
dfM = 1/xM;
[Ax,Ay,b] = convexhullConcave(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
remove = isinf(b) | isinf(Ax) | isnan(b);
if any(remove)
remove = find(remove);
Ax(remove)=[];
b(remove)=[];
Ay(remove)=[];
end
function f = check_for_special_cases(x)
f = [];
% Check for log(1+x)
base = getbase(x);
if all(base(:,1)==1)
f = slog(x-1);
return;
end
% Check if user is constructing log(sum(exp(x)))
if base(1)~=0
return
end
if ~all(base(2:end)==1)
return
end
modelst = yalmip('extstruct',getvariables(x));
if isempty(modelst)
return;
end
if length(modelst)==1
models{1} = modelst;
else
models = modelst;
end
% LOG(DET(X))
if length(models)==1
if strcmp(models{1}.fcn,'det_internal')
n = length(models{1}.arg{1});
try
f = logdet(reshape(models{1}.arg{1},sqrt(n),sqrt(n)));
catch
end
return
end
end
% LOG(EXP(x1)+...+EXP(xn))
for i = 1:length(models)
if ~strcmp(models{i}.fcn,'exp')
return
end
end
p = [];
for i = 1:length(models)
p = [p;models{i}.arg{1}];
end
f = logsumexp(p);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
subsref.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/subsref.m
| 9,032 |
utf_8
|
2f2b19b258a84e0cc39f6afdf6d64c31
|
function varargout = subsref(varargin)
%SUBSREF (overloaded)
% Stupid first slice call (supported by MATLAB)
% x = sdpvar(2);x(1,:,:)
Y = varargin{2};
if length(Y)==1
if length(Y.subs) > 2 && isequal(Y.type,'()')
i = 3;
ok = 1;
while ok && (i <= length(Y.subs))
ok = ok && (isequal(Y.subs{i},1) || isequal(Y.subs{i},':'));
i = i + 1;
end
if ok
Y.subs = {Y.subs{1:2}};
else
error('??? Index exceeds matrix dimensions.');
end
end
end
X = varargin{1};
if ~isempty(X.midfactors)
X = flush(X);
end
try
switch Y(1).type
case '()'
if isa(Y(1).subs{1},'constraint')
error('Conditional indexing not supported.');
end
% Check for simple cases to speed things up (yes, ugly but we all want speed don't we!)
switch size(Y(1).subs,2)
case 1
y = subsref1d(X,Y(1).subs{1},Y);
case 2
y = subsref2d(X,Y.subs{1},Y(1).subs{2},Y);
otherwise
if all( [Y(1).subs{3:end}]==1)
y = subsref2d(X,Y.subs{1},Y(1).subs{2},Y);
else
error('Indexation error.');
end
end
case '{}'
varargout{nargout} = [];
% it could be the case that we have an extended variable
% This is a bit tricky, so we do the best we can; assume that
% we want to replace the internal argument wih the new
% expression
OldArgument = recover(depends(X));
vars = getvariables(X);
mpt_solution = 1;
if all(ismembc(vars,yalmip('extvariables')))
for i = 1:length(X)
nonlinearModel = yalmip('extstruct',vars);
if isequal(nonlinearModel{1}.fcn,'pwa_yalmip') | isequal(nonlinearModel{1}.fcn,'pwq_yalmip')
else
mpt_solution = 0;
end
end
if mpt_solution
assign(nonlinearModel{1}.arg{2},Y(1).subs{:});
XX = double(X);
varargout{1} = double(X);
return
end
end
vars = getvariables(X);
if (length(vars) == 1) & ismembc(vars,yalmip('extvariables'))
nonlinearModel = yalmip('extstruct',vars);
OldArgument = [];
for i = 1:length(nonlinearModel.arg)
if isa(nonlinearModel.arg{i},'sdpvar')
OldArgument = [OldArgument; nonlinearModel.arg{i}];
end
end
if isa([Y.subs{:}],'double')
assign(reshape(OldArgument,[],1),reshape([Y(1).subs{:}],[],1));
varargout{1} = double(X);
return
end
end
y = replace(X,OldArgument,[Y(1).subs{:}]);
if isa(y,'double')
varargout{1} = y;
return
end
case '.'
switch Y(1).subs
case {'minimize','maximize'}
options = [];
constraints = [];
objective = varargin{1};
opsargs = {};
if length(Y)==2
if isequal(Y(2).type,'()')
for i = 1:length(Y(2).subs)
switch class(Y(2).subs{i})
case {'lmi','constraint'}
constraints = [constraints, Y(2).subs{i}];
case 'struct'
options = Y(2).subs{i};
case {'double','char'}
opsargs{end+1} = Y(2).subs{i};
otherwise
error('Argument to minimize should be constraints or options');
end
end
else
error(['What do you mean with ' Y(2).type '?']);
end
end
if length(opsargs)>0
if isempty(options)
options = sdpsettings(opsargs{:});
else
options = sdpsettings(options,opsargs{:});
end
end
if isequal(Y(1).subs,'minimize')
sol = solvesdp(constraints,objective,options);
else
sol = solvesdp(constraints,-objective,options);
end
varargout{1} = varargin{1};
varargout{2} = sol;
return
case 'derivative'
try
m = model(varargin{1});
varargout{1} = m{1}.derivative;
catch
varargout{1} = 1;
end
return
otherwise
error(['Indexation ''' Y.type Y.subs ''' not supported']) ;
end
otherwise
error(['Indexation with ''' Y.type ''' not supported']) ;
end
catch
error(lasterr)
end
if isempty(y.lmi_variables)
y = full(reshape(y.basis(:,1),y.dim(1),y.dim(2)));
else
% Reset info about conic terms
y.conicinfo = [0 0];
end
varargout{1} = y;
function X = subsref1d(X,ind1,Y)
% Get old and new size
n = X.dim(1);
m = X.dim(2);
% Convert to linear indecicies
if islogical(ind1)
ind1 = double(find(ind1));
elseif ischar(ind1)
X.dim(1) = n*m;
X.dim(2) = 1;
return;
elseif ~isnumeric(ind1)
X = milpsubsref(X,Y);
return
end
% Detect X(scalar)
if length(ind1) == 1 & ind1 <= n*m
Z = X.basis.';
Z = Z(:,ind1);
Z = Z.';
nnew = 1;
mnew = 1;
else
% What would the size be for a double
dummy = reshape(X.basis(:,1),n,m);
dummy = dummy(ind1);
nnew = size(dummy,1);
mnew = size(dummy,2);
[nx,mx] = size(X.basis);
if length(ind1) > 1
try
Z = X.basis.';
Z = Z(:,ind1);
Z = Z.';
catch
Z = X.basis(ind1,:);
end
else
Z = X.basis(ind1,:);
end
end
% Find non-zero basematrices
nzZ = find(any(Z(:,2:end),1));
if ~isempty(nzZ)
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = X.lmi_variables(nzZ);
X.basis = Z(:,[1 1+nzZ]);
else
bas = reshape(X.basis(:,1),n,m);
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = [];
X.basis = reshape(bas(ind1),nnew*mnew,1);
end
function X = subsref2d(X,ind1,ind2,Y)
if isnumeric(ind1)
elseif ischar(ind1)
ind1 = 1:X.dim(1);
elseif islogical(ind1)
ind1 = double(find(ind1));
elseif ~isnumeric(ind1)
X = milpsubsref(X,Y);
return
end
if isnumeric(ind2)
elseif ischar(ind2)
ind2 = 1:X.dim(2);
elseif islogical(ind2)
ind2 = double(find(ind2));
elseif ~isnumeric(ind2)
X = milpsubsref(X,Y);
return
end
n = X.dim(1);
m = X.dim(2);
lind2 = length(ind2);
lind1 = length(ind1);
if lind2 == 1
ind1_ext = ind1(:);
else
ind1_ext = kron(ones(lind2,1),ind1(:));
end
if lind1 == 1
ind2_ext = ind2(:);
else
ind2_ext = kron(ind2(:),ones(lind1,1));
end
if any(ind1 > n) || any(ind2 > m)
error('Index exceeds matrix dimensions.');
end
if lind1==1 && lind2==1
if isequal(X.conicinfo,[-1 0])
X.basis = [0 1];
X.lmi_variables = X.lmi_variables(1)+ind1+(ind2-1)*n-1;
X.dim = [1 1];
X.conicinfo = [0 0];
return
end
end
if prod(size(ind1_ext))==0 | prod(size(ind2_ext))==0
linear_index = [];
else
% Speed-up for some bizarre code with loads of indexing of vector
if m==1 & ind2_ext==1
linear_index = ind1_ext;
elseif length(ind2_ext)==1 && length(ind1_ext)==1
linear_index = ind1_ext + (ind2_ext-1)*n;
else
linear_index = sub2ind([n m],ind1_ext,ind2_ext);
end
end
nnew = length(ind1);
mnew = length(ind2);
% Put all matrices in vectors and extract sub matrix
Z = X.basis(linear_index,:);
% Find non-zero basematrices
%nzZ = find(any(Z(:,2:end),1));
nzZ = find(any(Z,1))-1;
if numel(nzZ)>0
if nzZ(1)==0
nzZ = nzZ(2:end);
end
end
if ~isempty(nzZ)
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = X.lmi_variables(nzZ);
X.basis = Z(:,[1 1+nzZ]);
else
bas = reshape(X.basis(:,1),n,m);
X.dim(1) = nnew;
X.dim(2) = mnew;
X.lmi_variables = [];
X.basis = reshape(bas(linear_index),nnew*mnew,1);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sinh.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/sinh.m
| 738 |
utf_8
|
167ff99de55c2333af9b1e2479b71a75
|
function varargout = sinh(varargin)
%SINH (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/ACOT CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)(cosh(x));
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/SINH called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = sinh(xL);
U = sinh(xU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
pwa.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/pwa.m
| 4,366 |
utf_8
|
47c565d662055a330df89467ca9366bd
|
function [p,Bi,Ci,Pn,Pfinal] = PWA(h,Xdomain)
% PWA Tries to create a PWA description
%
% [p,Bi,Ci,Pn,Pfinal] = PWA(h,X)
%
% Input
% h : scalar SDPVAR object
% X : SET object
%
% Output
%
% p : scalar SDPVAR object representing the PWA function
% Bi,Ci,Pn,Pfinal : Data in MPT format
%
% The command tries to expand the nonlinear operators
% (min,max,abs,...) used in the variable h, in order
% to generate an epi-graph model. Given this epigraph model,
% it is projected to the variables of interest and the
% defining facets of the PWA function is extracted. The second
% argument can be used to limit the domain of the PWA function.
% If no second argument is supplied, the PWA function is created
% over the domain -100 to 100.
%
% A new sdpvar object p is created, representing the same
% function as h, but in a slightly different internal format.
% Additionally, the PWA description in MPT format is created.
%
% The function is mainly inteded to be used for easy
% plotting of convex PWA functions
t = sdpvar(1,1);
[F,failure,cause] = expandmodel(lmi(h<=t),[],sdpsettings('allowmilp',0));
if failure
error(['Could not expand model (' cause ')']);
return
end
% Figure out what the actual original variables are
% note, by construction, they
all_initial = getvariables(h);
all_extended = yalmip('extvariables');
all_variables = getvariables(F);
gen_here = getvariables(t);
non_ext_in = setdiff(all_initial,all_extended);
lifted = all_variables(all_variables>gen_here);
vars = union(setdiff(setdiff(setdiff(all_variables,all_extended),gen_here),lifted),non_ext_in);
nx = length(vars);
X = recover(vars);
if nargin == 1
Xdomain = (-100 <= X <= 100);
else
Xdomain = (-10000 <= X <= 10000)+Xdomain;
end
[Ai,Bi,Ci,Pn] = generate_pwa(F,t,X,Xdomain,nx);
Pfinal = union(Pn);
sol.Pn = Pn;
sol.Bi = Bi;
sol.Ci = Ci;
sol.Ai = Ai;
sol.Pfinal = Pfinal;
p = pwf(sol,X,'convex');
%
% binarys = recover(all_variables(find(ismember(all_variables,yalmip('binvariables')))))
% if length(binarys) > 0
%
% Binary_Equalities = [];
% Binary_Inequalities = [];
% Mixed_Equalities = [];
% top = 1;
% for i = 1:length(F)
% Fi = sdpvar(F(i));
% if is(F(i),'equality')
% if all(ismember(getvariables(Fi),yalmip('binvariables')))
% Binary_Equalities = [Binary_Equalities;(top:top-1+prod(size(Fi)))'];
% Mixed_Equalities = [Mixed_Equalities;(top:top-1+prod(size(Fi)))'];
% end
% else
% if all(ismember(getvariables(Fi),yalmip('binvariables')))
% Binary_Inequalities = [Binary_Inequalities;(top:top-1+prod(size(Fi)))'];
% end
% end
% top = top+prod(size(Fi))';
% end
% P = sdpvar(F);
% P_ineq = extsubsref(P,setdiff(1:length(P),[Binary_Equalities; Binary_Inequalities]))
% P_binary_eq = extsubsref(P,Binary_Equalities);HK1 = getbase(P_binary_eq);
% P_binary_ineq = extsubsref(P,Binary_Inequalities);HK2 = getbase(P_binary_ineq);
% nbin = length(binarys);
% enums = dec2decbin(0:2^nbin-1,nbin)'
% if isempty(HK2)
% HK2 = HK1*0;
% end
% for i = 1:size(enums,2)
% if all(HK1*[1;enums(:,i)]==0)
% if all(HK2*[1;enums(:,i)]>=0)
% Pi = replace(P_ineq,binarys,enums(:,i))
% end
% end
% end
%
% else
% [Ai,Bi,Ci,Pn] = generate_pwa(F,t,X,Xdomain,nx);
% end
%
function [Ai,Bi,Ci,Pn] = generate_pwa(F,t,X,Xdomain,nx)
% Project, but remember that we already expanded the constraints
P = polytope(projection(F+(t<=10000)+Xdomain,[X;t],[],1));Xdomain = polytope(Xdomain);
[H,K] = double(P);
facets = find(H(:,end)<0);
region = find(~H(:,end) & any(H(:,1:nx),2) );
Hr = H(region,1:nx);
Kr = K(region,:);
H = H(facets,:);
K = K(facets);
K = K./H(:,end);
H = H./repmat(H(:,end),1,size(H,2));
nx = length(X);
Pn = [];
cib = [H(:,1:nx) K];
Ai = {};
Bi = cell(0);
Ci = cell(0);
if length(Kr > 0)
Xdomain = intersect(Xdomain,polytope(Hr,Kr));
end
[Hr,Kr] = double(Xdomain);
for i = 1:length(K)
j = setdiff(1:length(K),i);
HiKi = repmat(cib(i,:),length(K)-1,1)-cib(j,:);
Pi = polytope([HiKi(:,1:nx);Hr],[HiKi(:,end);Kr]);
if isfulldim(Pi)
Pn = [Pn Pi];
Bi{end+1} = -cib(i,1:end-1);
Ci{end+1} = cib(i,end);
Ai{end+1} = [];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
max.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/max.m
| 4,345 |
utf_8
|
513e8918b0e1fb1684e2ddcd491cbeb8
|
function y = max(varargin)
%MAX (overloaded)
%
% t = max(X)
% t = max(X,Y)
% t = max(X,[],DIM)
%
% Creates an internal structure relating the variable t with convex
% operator max(X).
%
% The variable t is primarily meant to be used in convexity preserving
% operations such as t<=..., minimize t etc.
%
% If the variable is used in a non-convexity preserving operation, such as
% t>=0, a mixed integer model will be derived.
%
% See built-in MAX for syntax.
% To simplify code flow, code for different #inputs
switch nargin
case 1
% Three cases:
% 1. One scalar input, return same as output
% 2. A vector input should give scalar output
% 3. Matrix input returns vector output
X = varargin{1};
if max(size(X))==1
y = X;
return
elseif min(size(X))==1
X = removeInf(X);
if isa(X,'double')
y = max(X);
elseif length(X) == 1
y = X;
else
y = yalmip('define','max_internal',X);
% Some special code to ensure max(x) when x is a simple
% binary vector yields a binary graph variable. This will
% simplify some models
reDeclareForBinaryMax(y,X);
end
return
else
% This is just short-hand for general command
y = max(X,[],1);
end
case 2
X = varargin{1};
Y = varargin{2};
[nx,mx] = size(X);
[ny,my] = size(Y);
if ~((nx*mx==1) | (ny*my==1))
% No scalar, so they have to match
if ~((nx==ny) & (mx==my))
error('Array dimensions must match.');
end
end
% Convert to compatible matrices
if nx*mx==1
X = X*ones(ny,my);
nx = ny;
mx = my;
elseif ny*my == 1
Y = Y*ones(nx,mx);
ny = nx;
my = mx;
end
% Ok, done with error checks etc.
Z = [reshape(X,1,[]);reshape(Y,1,[])];
y = yalmip('define','max_internal',Z);
reDeclareForBinaryMax(y,Z);
y = reshape(y,nx,mx);
case 3
X = varargin{1};
Y = varargin{2};
DIM = varargin{3};
if ~(isa(X,'sdpvar') & isempty(Y))
error('MAX with two matrices to compare and a working dimension is not supported.');
end
if ~isa(DIM,'double')
error('Dimension argument must be 1 or 2.');
end
if ~(length(DIM)==1)
error('Dimension argument must be 1 or 2.');
end
if ~(DIM==1 | DIM==2)
error('Dimension argument must be 1 or 2.');
end
if DIM==1
% Create one extended variable per column
y = [];
for i = 1:size(X,2)
inparg = extsubsref(X,1:size(X,1),i);
if isa(inparg,'sdpvar')
inparg = removeInf(inparg);
if isa(inparg,'double')
y = [y max(inparg)];
elseif length(inparg) == 1
y = [y max(inparg)];
else
z = yalmip('define','max_internal',inparg);
y = [y z];
% Some special code to ensure max(x) when x is a simple
% binary vector yields a binary graph variable. This will
% improve some models
reDeclareForBinaryMax(z,inparg);
end
else
y = [y max(inparg)];
end
end
else
% Re-use code recursively
y = max(X',[],1)';
end
otherwise
error('Too many input arguments.');
end
function X = removeInf(X)
Xbase = getbase(X);
infs = find( isinf(Xbase(:,1)) & (Xbase(:,1)<0));
if ~isempty(infs)
X.basis(infs,:) = [];
if X.dim(1)>X.dim(2)
X.dim(1) = X.dim(1) - length(infs);
else
X.dim(2) = X.dim(2) - length(infs);
end
end
infs = find(isinf(Xbase(:,1)) & (Xbase(:,1)>0));
if ~isempty(infs)
X = inf;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
deadhub.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/deadhub.m
| 1,425 |
utf_8
|
19c2ad46cb40a73e2e3512d91f306a52
|
function varargout = deadhub(varargin)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/SIN CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','convex','monotonicity','none','definiteness','positive','model','callback');
operator.bounds = @bounds;
operator.convexhull = @convexhull;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/SIN called with CHAR argument?');
end
function [L,U] = bounds(xL,xU,lambda)
fL = deadhub(xL,lambda);
fU = deadhub(xU,lambda);
U = max(fL,fU);
L = min(fL,fU);
if xL<0 & xU>0
L = 0;
end
function [Ax, Ay, b, K] = convexhull(xL,xU,lambda)
K.l = 0;
K.f = 0;
fL = deadhub(xL,lambda);
fU = deadhub(xU,lambda);
if xL>=-lambda & xU<=lambda
Ax = 0;Ay = 1;b = 0;K.f = 1;
elseif xU < -3*lambda
Ax = 1;Ay = 1;b = 2*lambda^2;K.f = 1;
elseif xL > 3*lambda
Ax = -1;Ay = 1;b = 2*lambda^2;K.f = 1;
else
dfL = derivative(xL,lambda);
dfU = derivative(xU,lambda);
[Ax,Ay,b,K] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
end
function df=derivative(x,lambda)
ax = abs(x);
if ax<lambda
df=0;
elseif ax>3*lambda
df = lambda;
elseif ax<=3*lambda
df = 0.25*(2*ax-6*lambda)+lambda;
end
if x<0
df=-df;
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.