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
|
mtimes.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/mtimes.m
| 30,871 |
utf_8
|
a02bcbc2cab008ade86fac60c7baef00
|
function Z = mtimes(X,Y)
%MTIMES (overloaded)
% Cannot use isa here since blkvar is marked as sdpvar
X_class = class(X);
Y_class = class(Y);
X_is_spdvar = strcmp(X_class,'sdpvar');
Y_is_spdvar = strcmp(Y_class,'sdpvar');
% Convert block objects
if ~X_is_spdvar
if isa(X,'blkvar')
X = sdpvar(X);
X_is_spdvar = isa(X,'sdpvar');
end
end
if ~Y_is_spdvar
if isa(Y,'blkvar')
Y = sdpvar(Y);
Y_is_spdvar = isa(Y,'sdpvar');
end
end
% Lame special cases, make sure to reurn
% empty matrices in the sense that the
% used MATLAB version
if isempty(X)
YY = full(reshape(Y.basis(:,1),Y.dim(1),Y.dim(2)));
Z = X*YY;
return
elseif isempty(Y)
XX = full(reshape(X.basis(:,1),X.dim(1),X.dim(2)));
Z = XX*Y;
return
end
% Optimized calls in different order?
if X_is_spdvar && Y_is_spdvar
manytimesfew = length(X.lmi_variables) > 5*length(Y.lmi_variables);
if manytimesfew
Z = (Y'*X')'; % Optimized for this order (few variables * many variables)
return
end
end
if ~X_is_spdvar
if any(isnan(X))
error('Multiplying NaN with an SDPVAR makes no sense.');
end
end
if ~Y_is_spdvar
if any(isnan(Y))
error('Multiplying NaN with an SDPVAR makes no sense.');
end
end
% Different code for
% 1 : SDPVAR * DOUBLE
% 2 : DOUBLE * SDPVAR
% 3 : SDPVAR * SDPVAR
switch 2*X_is_spdvar+Y_is_spdvar
case 3
if ~isempty(X.midfactors)
X = flush(X);
end
if ~isempty(Y.midfactors)
Y = flush(Y);
end
try
% HACK: Return entropy when user types x*log(x)
if isequal(Y.extra.opname,'log')
Z = check_for_special_case(Y,X);
if ~isempty(Z)
return
end
elseif isequal(X.extra.opname,'log')
Z = check_for_special_case(X,Y);
if ~isempty(Z)
return
end
end
ny = Y.dim(1);
my = Y.dim(2);
nx = X.dim(1);
mx = X.dim(2);
x_isscalar = nx*mx==1;
y_isscalar = ny*my==1;
[mt,oldvariabletype,mt_hash,hash] = yalmip('monomtable');
% Super-special hack to speed up QP formulations
% Requires that the involved variables never have been used
% before in a nonlinear expression. By exploiting this fact, we
% can avoid using findhash, which typically is the bottle-neck.
if (nx == 1) && (my == 1) && isequal(X.lmi_variables,Y.lmi_variables)
% Looks like w'Qw or similiar
% Check that no nonlinear have been defined before, and that
% the arguments are linear.
if all(oldvariabletype(X.lmi_variables)==0) && nnz(mt(find(oldvariabletype),X.lmi_variables)) == 0
Z = super_fast_quadratic_multiplication(X,Y,mt,oldvariabletype,mt_hash,hash);
return
end
end
% Are the involved variables disjoint
if X.lmi_variables(end) < Y.lmi_variables(1)
disconnected = 1;
elseif Y.lmi_variables(end) < X.lmi_variables(1)
disconnected = 2;
elseif isequal(Y.lmi_variables,X.lmi_variables)
disconnected = -1; % Same
else
disconnected = 0; % Tangled up
end
% Optimized unique
switch disconnected
case -1
all_lmi_variables = [X.lmi_variables];
case 1
all_lmi_variables = [X.lmi_variables Y.lmi_variables];
case 2
all_lmi_variables = [Y.lmi_variables X.lmi_variables];
otherwise
all_lmi_variables = uniquestripped([X.lmi_variables Y.lmi_variables]);
end
% Create clean SDPVAR object
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
switch disconnected
case -1
index_X = [ones(1,length(X.lmi_variables))];
index_Y = index_X;
case 1
oX = ones(1,length(X.lmi_variables));
oY = ones(1,length(Y.lmi_variables));
index_X = [oX 0*oY];
index_Y = [oX*0 oY];
case 2
index_X = [zeros(1,length(Y.lmi_variables)) ones(1,length(X.lmi_variables))];
index_Y = [ones(1,length(Y.lmi_variables)) zeros(1,length(X.lmi_variables))];
otherwise
index_X = double(ismembcYALMIP(all_lmi_variables,X.lmi_variables));
index_Y = double(ismembcYALMIP(all_lmi_variables,Y.lmi_variables));
end
iX=find(index_X);
iY=find(index_Y);
index_X(iX)=1:length(iX);index_X=index_X(:);
index_Y(iY)=1:length(iY);index_Y=index_Y(:);
% Pre-allocate under assumption that product is fairly sparse
% If more is required later, it will be expanded
Z.lmi_variables = [Z.lmi_variables zeros(1,length(X.lmi_variables)+length(Y.lmi_variables))];
%Z.lmi_variables = [Z.lmi_variables zeros(1,length(X.lmi_variables)*length(Y.lmi_variables))];
% Pre-calc identity (used a lot
speyemy = sparse(1:my,1:my,1,my,my);
% Linear terms
inner_vector_product = (nx==1 && my==1 && (mx == ny));
if inner_vector_product
base1=Xbase*Y.basis;base1=base1(2:end);
base2=Ybase.'*X.basis;base2=base2(2:end);
[i1,j1,k1]=find(base1);
[i2,j2,k2]=find(base2);
base1 = sparse(i1,iY(j1),k1,1,length(all_lmi_variables));
base2 = sparse(i2,iX(j2),k2,1,length(all_lmi_variables));
Z.basis = [Xbase*Ybase base1+base2];
else
base0 = Xbase*Ybase;
if x_isscalar
base1 = Xbase*Y.basis(:,2:end);
base2 = Ybase(:)*X.basis(:,2:end);
elseif y_isscalar
base1 = Xbase(:)*Y.basis;base1=base1(:,2:end);
base2 = X.basis*Ybase;base2=base2(:,2:end);
else
base1 = kron(speyemy,Xbase)*Y.basis(:,2:end);
base2 = kron(Ybase.',speye(nx))*X.basis(:,2:end);
end
[i1,j1,k1]=find(base1);
[i2,j2,k2]=find(base2);
base1 = sparse(i1,iY(j1),k1,size(base0(:),1),length(all_lmi_variables));
base2 = sparse(i2,iX(j2),k2,size(base0(:),1),length(all_lmi_variables));
Z.basis = [base0(:) base1+base2];
end
% Loop start for nonlinear terms
i = length(all_lmi_variables)+1;
% [mt,oldvariabletype,mt_hash,hash] = yalmip('monomtable');
% Check if problem is bilinear. We can exploit this later
% to improve performance significantly...
bilinearproduct = 0;
candofastlocation = 0;
if all(oldvariabletype(X.lmi_variables)==0) && all(oldvariabletype(Y.lmi_variables)==0)
% if isempty(intersect(X.lmi_variables,Y.lmi_variables))
% members = ismembcYALMIP(X.lmi_variables,Y.lmi_variables);
if disconnected == 1 || disconnected == 2%~any(members)
bilinearproduct = 1;
try
dummy = ismembc2(1,1); % Not available in all versions (needed in ismember)
candofastlocation = 1;
catch
end
end
end
oldmt = mt;
local_mt = mt(all_lmi_variables,:);
used_variables = any(local_mt,1);
local_mt = local_mt(:,used_variables);
possibleOld = find(any(mt(:,used_variables),2));
if all(oldvariabletype <=3)
% All monomials have non-negative integer powers
% no chance of x^2*x^-1, hence all products
% are nonlinear
possibleOld = possibleOld(find(oldvariabletype(possibleOld)));
if size(possibleOld,1)==0
possibleOld = [];
end
end
if bilinearproduct && ~isempty(possibleOld)
if length(X.lmi_variables)<=length(Y.lmi_variables)
temp = mt(:,X.lmi_variables);
temp = temp(possibleOld,:);
possibleOld=possibleOld(find(any(temp,2)));
else
temp = mt(:,Y.lmi_variables);
temp = temp(possibleOld,:);
possibleOld=possibleOld(find(any(temp,2)));
end
end
theyvars = find(index_Y);
thexvars = find(index_X);
% We work with three sets of hashed data.
% 1. The hashes that were available from the start. These are
% sorted
possibleOldHash = mt_hash(possibleOld);
[possibleOldHashSorted, sortedHashLocs] = sort(possibleOldHash);
oldhash = hash;
hash = hash(used_variables);
% 2. The hashes that were introduced in the previous outer
% iteration, i.e. those generated when multiplying x(ix) with
% all y. These are sorted every iteration
new_mt_hash = [];
%new_mt_hash_aux = spalloc(length(X.lmi_variables)*length(Y.lmi_variables),1,0);
new_mt_hash_aux = zeros(min(1e3,length(X.lmi_variables)*length(Y.lmi_variables)),1);
new_mt_hash_counter = 0;
% % 3. Those that are generated at the current iteration. These
% % are not sorted
% currwent_new_mt_hash_aux = zeros(length(X.lmi_variables)*length(Y.lmi_variables),1);
% current_new_mt_hash_counter = 0;
new_mt = [];
changed_mt = 0;
local_mt = local_mt';
nvar = size(mt,1);
old_new_mt_hash_counter = new_mt_hash_counter;
possibleNewHashSorted = {};
sortedNewHashLocs = {};
possibleOldBlocked{1} = possibleOld;
sortedHashLocsBlocked{1} = sortedHashLocs;
possibleOldHashSortedBlocked{1} = possibleOldHashSorted;
possibleOldHashSortedBlockedFull{1} = full(possibleOldHashSorted);
current_offset = size(mt_hash,1);
YB = Y.basis(:,1+index_Y(theyvars(:)'));
if isequal(YB,speye(size(YB,1)))
simpleMultiplicationwithI = 1;
else
simpleMultiplicationwithI = 0;
end
for ix = thexvars(:)'
mt_x = local_mt(:,ix);
testthese = theyvars(:)';
% Compute [vec(Xbasis*Ybasis1) vec(Xbasis*Ybasis2) ...]
% in one shot using vectorization and Kronecker tricks
% Optimized and treat special case scalar*matrix etc
if x_isscalar
allprodbase = X.basis(:,1+index_X(ix));
%allprodbase = Xibase * Y.basis(:,1+index_Y(testthese));
allprodbase = allprodbase * YB;
elseif y_isscalar
allprodbase = X.basis(:,1+index_X(ix));
%allprodbase = Xibase * Y.basis(:,1+index_Y(testthese));
allprodbase = allprodbase * YB;
elseif inner_vector_product
allprodbase = X.basis(:,1+index_X(ix)).';
%allprodbase = Xibase*Y.basis(:,1+index_Y(testthese));
if ~simpleMultiplicationwithI
allprodbase = allprodbase*YB;
end
else
allprodbase = reshape(X.basis(:,1+index_X(ix)),nx,mx);
allprodbase = kron(speyemy,allprodbase);
%allprodbase = temp * Y.basis(:,1+index_Y(testthese));
allprodbase = allprodbase * YB;
end
% Keep non-zero matrices
if size(allprodbase,1)==1
nonzeromatrices = find(allprodbase);
nonzeromatrices = nonzeromatrices(find(abs(allprodbase(nonzeromatrices))>1e-12));
else
nonzeromatrices = find(sum(abs(allprodbase),1)>1e-12);
end
testthese = testthese(nonzeromatrices);
allprodbase = allprodbase(:,nonzeromatrices);
% Some data for vectorization
nyvars = length(testthese);
if prod(size(mt_x))==1 % Bug in Solaris and Linux, ML 6.X
allmt_xplusy = local_mt(:,testthese) + sparse(repmat(full(mt_x),1,nyvars));
else
allmt_xplusy = bsxfun(@plus,local_mt(:,testthese),mt_x);
% allmt_xplusy = local_mt(:,testthese) + repmat(mt_x,1,nyvars);
end
allhash = allmt_xplusy'*hash;
thesewhereactuallyused = zeros(1,nyvars);
copytofrom = ones(1,nyvars);
acounter = 0;
% Special case : x*inv(x) and similiar...
sum_to_constant = abs(allhash)<eps;
add_these = find(sum_to_constant);
if ~isempty(add_these)
prodbase = allprodbase(:,add_these);
Z.basis(:,1) = Z.basis(:,1) + sum(prodbase,2);
copytofrom(add_these) = 0;
end
indicies = find(~sum_to_constant);
indicies = indicies(:)';
allbefore_in_old = 1;
if bilinearproduct && candofastlocation
[dummy,allbefore_in_old] = ismember(allhash,possibleOldHash);
end
if bilinearproduct && candofastlocation && (nnz(allbefore_in_old)==0)
% All nonlinear variables are new, so we can create them at once
changed_mt=1;
thesewhereactuallyused = thesewhereactuallyused+1;
Z.lmi_variables = expandAllocation(Z.lmi_variables,(i+length(indicies)-1));
Z.lmi_variables(i:(i+length(indicies)-1)) = (nvar+1):(nvar+length(indicies));
nvar = nvar + length(indicies);
i = i + length(indicies);
else
for acounter = indicies
current_hash = allhash(acounter);
% Ok, braze your self for some horrible special case
% treatment etc...
if (new_mt_hash_counter == 0) || bilinearproduct % only search among old monomials
if bilinearproduct && candofastlocation
before = allbefore_in_old(acounter);
if before==0
before = [];
else
before = possibleOld(before);
end
else
before = possibleOld(sortedHashLocs(findhashsorted(possibleOldHashSorted,current_hash)));
end
else
% length(new_mt_hash_aux)
before = findhash(new_mt_hash_aux,current_hash,new_mt_hash_counter); % first among new monomials
if before
before=before+current_offset;
else
sb = 1;
cth = full(current_hash);
while isempty(before) && sb <= length(possibleOldBlocked)
testitfull = possibleOldHashSortedBlockedFull{sb};
mmm=findhashsorted(testitfull,cth);
if mmm
mmm=sortedHashLocsBlocked{sb}(mmm);
before = possibleOldBlocked{sb}(mmm);
end
sb = sb+1;
end
end
end
if before
Z.lmi_variables = expandAllocation(Z.lmi_variables,i);
Z.lmi_variables(i) = before;
else
changed_mt=1;
thesewhereactuallyused(acounter) = 1;
new_mt_hash_counter = new_mt_hash_counter + 1;
if new_mt_hash_counter>length(new_mt_hash_aux)
new_mt_hash_aux = [new_mt_hash_aux;zeros(length(new_mt_hash_aux),1)];
end
new_mt_hash_aux(new_mt_hash_counter) = current_hash;
nvar = nvar + 1;
Z.lmi_variables = expandAllocation(Z.lmi_variables,i);
Z.lmi_variables(i) = nvar;
end
i = i+1;
end
end % End y-variables
if all(copytofrom)
Z.basis = [Z.basis allprodbase];
else
Z.basis = [Z.basis allprodbase(:,find(copytofrom))];
end
if all(thesewhereactuallyused)
new_mt = [new_mt allmt_xplusy];
else
new_mt = [new_mt allmt_xplusy(:,find(thesewhereactuallyused))];
end
bsize = 100;
if new_mt_hash_counter>5
bsize = new_mt_hash_counter-1;
end
if new_mt_hash_counter > bsize
ship = new_mt_hash_aux(1:bsize);
mt_hash = [mt_hash;ship];
new_mt_hash_aux = new_mt_hash_aux(bsize+1:new_mt_hash_counter);
new_mt_hash_counter = nnz(new_mt_hash_aux);
[newHashSorted, sortednewHashLocs] = sort(ship);
possibleOldBlocked{end+1} = (1:bsize)+current_offset;
sortedHashLocsBlocked{end+1} = sortednewHashLocs;
possibleOldHashSortedBlocked{end+1} = (newHashSorted);
possibleOldHashSortedBlockedFull{end+1} = full(newHashSorted);
current_offset = current_offset + bsize;
end
end % End x-variables
if ~isempty(new_mt)
[i1,j1,k1] = find(mt);
[ii1,jj1,kk1] = find(new_mt');
uv = find(used_variables);uv=uv(:);
mt = sparse([i1(:);ii1(:)+size(mt,1)],[j1(:);uv(jj1(:))],[k1(:);kk1(:)],size(mt,1)+size(new_mt,2),size(mt,2));
end
% We pre-allocated a sufficiently long, now pick the ones we
% actually filled with values
Z.lmi_variables = Z.lmi_variables(1:i-1);
% Fucked up order (lmi_variables should be sorted)
Z = fix_variable_order(Z);
if changed_mt%~isequal(mt,oldmt)
newmt = mt(size(oldmt,1)+1:end,:);
nonlinear = ~(sum(newmt,2)==1 & sum(newmt~=0,2)==1);
newvariabletype = spalloc(size(newmt,1),1,nnz(nonlinear))';
nonlinearvariables = find(nonlinear);
newvariabletype = sparse(nonlinearvariables,ones(length(nonlinearvariables),1),3,size(newmt,1),1)';
if ~isempty(nonlinear)
%mt = internal_sdpvarstate.monomtable;
%newvariabletype(nonlinear) = 3;
quadratic = sum(newmt,2)==2;
newvariabletype(quadratic) = 2;
bilinear = max(newmt,[],2)<=1;
newvariabletype(bilinear & quadratic) = 1;
sigmonial = any(0>newmt,2) | any(newmt-fix(newmt),2);
newvariabletype(sigmonial) = 4;
end
% yalmip('setmonomtable',mt,[oldvariabletype newvariabletype],[mt_hash;new_mt_hash],oldhash);
yalmip('setmonomtable',mt,[oldvariabletype newvariabletype],[mt_hash;new_mt_hash_aux(1:new_mt_hash_counter)],oldhash);
end
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 = clean(Z);
case 2
n_X = X.dim(1);
m_X = X.dim(2);
[n_Y,m_Y] = size(Y);
x_isscalar = (n_X*m_X==1);
y_isscalar = (n_Y*m_Y==1);
if ~x_isscalar
if ((m_X~= n_Y && ~y_isscalar))
error('Inner matrix dimensions must agree.')
end
end
n = n_X;
m = m_Y;
Z = X;
if x_isscalar
if y_isscalar
if Y==0
Z = 0;
return
else
Z.basis = Z.basis*Y;
% Reset info about conic terms
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = addrightfactor(Z,Y);
return
end
else
if ~isa(Y,'double')
Y = double(Y);
end
Z.dim(1) = n_Y;
Z.dim(2) = m_Y;
Z.basis = kron(Z.basis,Y(:));
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = addrightfactor(Z,Y);
Z = addleftfactor(Z,speye(size(Y,1)));
Z = clean(Z);
return
end
elseif y_isscalar
if ~isa(Y,'double')
Y = double(Y);
end
Z.dim(1) = n_X;
Z.dim(2) = m_X;
Z.basis = Z.basis*Y;
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = addrightfactor(Z,Y);
Z = addleftfactor(Z,speye(size(Y,1)));
Z = clean(Z);
return
end
Z.dim(1) = n;
Z.dim(2) = m;
if (n_X==1) && is(X,'lpcone') && (n_Y == m_Y) && (size(X.basis,1)==size(X.basis,2-1)) && isequal(X.basis*[0 1:size(X.basis,2)-1]',(1:size(X.basis,2)-1)')
% special case to speed up x'*Q, Q square. typically
% encountered in large-scale QPs
Z.basis = [X.basis(:,1) Y.'];
else
if ~isa(Y,'double')
Y = double(Y);
end
Z.basis = kron(Y.',speye(n_X))*X.basis;
end
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = addrightfactor(Z,Y);
Z = clean(Z);
case 1
n_Y = Y.dim(1);
m_Y = Y.dim(2);
[n_X,m_X] = size(X);
x_isscalar = (n_X*m_X==1);
y_isscalar = (n_Y*m_Y==1);
if ~x_isscalar
if ((m_X~= n_Y && ~y_isscalar))
error('Inner matrix dimensions must agree.')
end
end
n = n_X;
m = m_Y;
Z = Y;
% Special cases
if x_isscalar
if y_isscalar
if X==0
Z = 0;
return
else
Z.basis = Z.basis*X;
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = addleftfactor(Z,X);
return
end
else
try
Z.basis = X*Z.basis;
catch
% This works better when low on memory in some cases
[i,j,k] = find(Y.basis);
Z.basis = sparse(i,j,X*k,size(Y.basis,1),size(Y.basis,2));
end
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = addleftfactor(Z,X);
if X==0
Z = clean(Z);
end
return
end
elseif y_isscalar
Z.dim(1) = n_X;
Z.dim(2) = m_X;
Z.basis = X(:)*Y.basis;
Z = addleftfactor(Z,X);
Z = addrightfactor(Z,speye(size(X,2)));
Z = clean(Z);
return
end
if m_Y==1
if issparse(X)
Z.basis = X*Y.basis;
else
if (size(X,1) > 100000) && isdiagonal(X)
try
Z.basis = bsxfun(@times,Y.basis,sparse(diag(X)));
catch
Z.basis = sparse(X)*Y.basis;
end
else
Z.basis = sparse(X)*Y.basis;
end
end
else
try
if ~isa(X,'double')
X = double(X);
end
speyemy = speye(m_Y);
kronX = kron(speyemy,X);
Z.basis = kronX*Y.basis;
catch
disp('Multiplication of SDPVAR object caused memory error');
disp('Continuing using unvectorized version which is extremely slow');
Z.basis = [];
if ~isa(X,'double')
X = double(X);
end
for i = 1:size(Y.basis,2);
dummy = X*reshape(Y.basis(:,i),Y.dim(1),Y.dim(2));
Z.basis = [Z.basis dummy(:)];
end
end
end
Z.dim(1) = n;
Z.dim(2) = m;
Z.conicinfo = [0 0];
Z.extra.opname='';
Z = addleftfactor(Z,X);
Z = clean(Z);
otherwise
error('Logical error in mtimes. Report bug')
end
function Z=clean(X)
temp = any(X.basis,1);
temp = temp(2:end);
index = find(temp);
if ~isempty(index)
Z = X;
if length(index)~=length(Z.lmi_variables)
Z.basis = Z.basis(:,[1 1+index]);
Z.lmi_variables = Z.lmi_variables(index);
end
else
Z = full(reshape(X.basis(:,1),X.dim(1),X.dim(2)));
end
function Z = fix_variable_order(Z)
% Fucked 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:end,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
function Z = super_fast_quadratic_multiplication(X,Y,mt,oldvariabletype,mt_hash,hash);
Q = X.basis(:,2:end);
R = Y.basis(:,2:end);
Q = (Q.')*R;
Q = Q + Q.' - diag(diag(Q));
if nnz(Q-diag(diag(Q)))==0
% Special case, only quadratic terms
% Exploit this!
n = length(X.lmi_variables);
new_mt = sparse(1:n,X.lmi_variables,2*ones(n,1),n,size(mt,2));
newvariabletype = ones(n,1)*2;
Q = diag(Q);Q = Q(:)';
else
indicies = find(tril(ones(length(Q))));
Q = Q(indicies);
Q = Q(:).';
n = length(X.lmi_variables);
V = mt(X.lmi_variables,:);
if 1
m1 = kron((1:n)',ones(n,1));
m2 = kron(ones(n,1),(1:n)');
r = reshape(1:n^2,n,n);
r = r(find(tril(r)));
m1 = m1(r);
m2 = m2(r);
VV = V';
VV = VV(:,m1) + VV(:,m2);
new_mt = VV';
else
new_mt = kron(V,ones(n,1)) + kron(ones(n,1),V);
r = reshape(1:n^2,n,n);
new_mt = new_mt(r(find(tril(r))),:);
end
newvariabletype = max((new_mt),[],2);
end
yalmip('setmonomtable',[mt;new_mt],[oldvariabletype newvariabletype'],[mt_hash;new_mt*hash],hash);
Z = X;
varbase = [(X.basis(:,1).')*Y.basis(:,2:end)+(Y.basis(:,1).')*X.basis(:,2:end) Q];
Z.basis = [(X.basis(:,1).')*Y.basis(:,1) varbase(find(varbase))];
Z.lmi_variables = [X.lmi_variables size(mt,1) + (1:length(Q))];
Z.lmi_variables = Z.lmi_variables(find(varbase));
Z.dim(1) = 1;
Z.dim(2) = 1;
Z.conicinfo = [0 0];
Z.extra.opname='';
function Z = check_for_special_case(Y,X)
% X*Y = X*log(?)
args = yalmip('getarguments',Y);
args = args.arg{1};
if isequal(X,args)
Z = -entropy(X);
return
end
if 0%isequal(getvariables(args),getvariables(X))
% Possible f(x)*log(f(x))
[i,j,k] = find(getbase(args));
[ii,jj,kk] = find(getbase(X));
if isequal(i,ii) && isequal(j,jj)
scale = kk(1)./k(1)
if all(abs(kk./k - kk(1)./k(1)) <= 1e-12)
Z = -scale*entropy(args);
return
end
end
end
if isequal(getbase(args),[0 1]) && isequal(getbase(X),[0 1])
mt = yalmip('monomtable');
v = mt(getvariables(args),:);
vb = v(find(v));
if v(getvariables(X))==1 && min(vb)==-1 && max(vb)==1
Z = plog([X;recover(find(v==-1))]);
else
Z = [];
end
else
Z = [];
end
function yes = isdiagonal(X)
yes = 0;
if size(X,1) == size(X,2)
[i,j] = find(X);
if all(i==j)
yes = 1;
end
end
function x = expandAllocation(x,n)
if length(x) < n
x = [x zeros(1,2*n-length(x))];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
cosh.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/cosh.m
| 867 |
utf_8
|
c13a2d8c9f1f455224d9d5fc5a232af4
|
function varargout = cosh(varargin)
%COSH (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/COSH CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','none','definiteness','positive','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @(x)(sinh(x));
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/COSH called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xL<0 & xU>0
L = 0;
U = max([cosh(xL) cosh(xU)]);
elseif xL<0
L = cosh(xU);
U = cosh(xL);
else
L = cosh(xL);
U = cosh(xU);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
det.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/det.m
| 2,020 |
utf_8
|
c62ed564f88ca694ab3f483f7c7664ef
|
function varargout = det(varargin)
%DET (overloaded)
%
% t = DET(X)
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 n~=m
error('Matrix must be square.')
end
if nargin == 2
if strcmp(varargin{2},'polynomial')
varargout{1} = polynomialform(X);
return
else
error('If you use two arguments in @sdpvar/det, the second should be ''polynomial''');
end
end
if n==1
varargout{1} = X;
return
else
y = yalmip('define','det_internal',reshape(X,[],1));
end
varargout{1} = y;
otherwise
end
function d = polynomialform(X)
n = X.dim(1);
m = X.dim(2);
if n~=m
error('Matrix must be square.');
else
switch n
case 1
d = X;
case 2
% Freakin overloading on multiplication doesn't work. Probalby
% stupid code...
Y1.type = '()';
Y2.type = '()';
Y3.type = '()';
Y4.type = '()';
Y1.subs = {1,1};
Y2.subs = {2,2};
Y3.subs = {1,2};
Y4.subs = {2,1};
d = subsref(X,Y1)*subsref(X,Y2)-subsref(X,Y3)*subsref(X,Y4);
otherwise
d = 0;
Y.type = '()';
for i = 1:n
Y.subs = {i,1};
xi = subsref(X,Y);
if ~isequal(xi,0)
Y.subs = {[1:1:i-1 i+1:1:n],2:n};
subX = subsref(X,Y);
if isa(subX,'sdpvar')
d = d + (-1)^(i+1)*xi*polynomialform(subX);
else
d = d + (-1)^(i+1)*xi*det(subX);
end
end
end
end
end
% Reset info about conic terms
if isa(d,'sdpvar')
d.conicinfo = [0 0];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
value.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/value.m
| 11,462 |
utf_8
|
ec8d9598bf4fccc447aff873eb963275
|
function [sys,values] = value(X,allextended,allevaluators,allStruct,mt,variabletype,solution,values)
%VALUE Returns current numerical value of an SDPVAR object
%
% After solving an optimization problem, we can extract the current
% solution by applying VALUE on a variable of interest
%
% xvalue = value(x)
%
% If you have solved a multiple problems simultaneously by using a
% non-scalar objective function, you can select the solution by using a
% second argument
%
% xvalue = value(x,i)
% Normal users might use the second arguement in order to select solution
if nargin == 2
if prod(size(allextended))==1
try
selectsolution(allextended);
sys = value(X);
selectsolution(1);
return
catch
error(['Solution ' num2str(allextended) ' not available']);
end
else
error(['Solution number should be a positive scalar']);
end
end
% Definition of nonlinear variables
if nargin == 1
[mt,variabletype] = yalmip('monomtable');
solution = yalmip('getsolution');
end
lmi_variables = X.lmi_variables;
opt_variables = solution.variables;
nonlinears = lmi_variables(find(variabletype(X.lmi_variables)));
% FIXME: This code does not work
% if ~isempty(solution.values)
% if max(lmi_variables) <= length(solution.values) && isempty(nonlinears)
% if ~any(isnan(solution.values(lmi_variables(:))))
% % Yihoo, we can do this really fast by
% % re-using the old values
% sys = X.basis*[1;solution.values(lmi_variables(:))];
% if X.typeflag==10
% sys = eig(full(reshape(sys,X.dim(1),X.dim(2))));
% else
% sys = full(reshape(sys,X.dim(1),X.dim(2)));
% end
% return
% end
% end
% end
% Okey, we could not do it really fast...
if nargin == 1
% Definition of nonlinear variables
allextended = yalmip('extvariables');
allevaluators = [];
allStruct = yalmip('extstruct');
end
if isempty(nonlinears) && isempty(allextended)
members = ismembcYALMIP(lmi_variables,solution.variables);
if all(members)
% speed up code for simple linear case
values = solution.values;
if isempty(solution.values)
values = sparse(solution.variables,ones(length(solution.variables),1),solution.optvar,size(mt,1),1);
yalmip('setvalues',values);
else
if any(isnan(solution.values(lmi_variables(:))))
values = sparse(solution.variables,ones(length(solution.variables),1),solution.optvar,size(mt,1),1);
yalmip('setvalues',values);
end
end
sys = X.basis*[1;values(lmi_variables(:))];
if X.typeflag==10
sys = eig(full(reshape(sys,X.dim(1),X.dim(2))));
else
sys = full(reshape(sys,X.dim(1),X.dim(2)));
end
return
end
end
if nargin == 1
% All double values
values(size(mt,1),1)=nan;values(:)=nan;
values(solution.variables) = solution.optvar;
clear_these = allextended;
if ~isempty(allStruct)
if ~isempty(strfind([allStruct.fcn],'semivar'))
for i = 1:length(allStruct)
if strcmp(allStruct(i).fcn,'semivar')%isequal(allStruct(i).fcn,'semivar')
clear_these = setdiff(clear_these,allextended(i));
end
end
end
end
values(clear_these) = nan;
end
% Evaluate the extended operators
if ~isempty(allextended)
extended_variables = find(ismembcYALMIP(X.lmi_variables,allextended));
if ~isempty(extended_variables)
for i = 1:length(extended_variables)
extvar = lmi_variables(extended_variables(i));
if isnan(values(extvar))
extstruct = allStruct(find(X.lmi_variables(extended_variables(i)) == allextended));
for k = 1:length(extstruct.arg)
if isa(extstruct.arg{k},'sdpvar')
[extstruct.arg{k},values] = value(extstruct.arg{k},allextended,allevaluators,allStruct,mt,variabletype,solution,values);
elseif isa(extstruct.arg{k},'constraint')
extstruct.arg{k} = value(extstruct.arg{k});
end
end
switch extstruct.fcn
case 'sort'
[w,loc] = sort(extstruct.arg{1});
if extstruct.arg{2}.isthisloc
val = loc(extstruct.arg{2}.i);
else
val = w(extstruct.arg{2}.i);
end
case 'semivar'
% A bit messy, since it not really is a nonlinear
% operator. semivar(1) does not return 1, but a new
% semivar variable...
val = values(getvariables(extstruct.var));
case 'geomean' % Not 100% MATLAB consistent (Hermitian case differ)
val = extstruct.arg{1};
if ~any(any(isnan(val)))
[n,m] = size(val);
if n == m
if isessentiallyhermitian(val)
val = max(0,real(det(val)))^(1/n);
else
val = prod(val).^(1./(size(val,1)));
end
elseif min(n,m)>1
val = prod(val).^(1./(size(val,1)));
else
val = prod(val).^(1./(length(val)));
end
else
val = nan;
end
case 'pwf'
% Has to be placed here due to the case when
% all functions are double, since in this case,
% we cannot determine in pwf if we want the double or
% create a pw constant function...
n = length(extstruct.arg-1)/2;
i = 1;
val = nan;
while i<=n
if min(checkset(extstruct.arg{2*i}))>=0
val = extstruct.arg{2*i-1};
break
end
i = i + 1;
end
case 'or'
temp = [extstruct.arg{1:end-1}];
if any(isnan(temp))
val = NaN;
else
val = any(temp);
end
case 'and'
temp = [extstruct.arg{1:end-1}];
if any(isnan(temp))
val = NaN;
else
val = all(temp);
end
case 'xor'
temp = [extstruct.arg{1:end-1}];
if any(isnan(temp))
val = NaN;
else
val = nnz([extstruct.arg{1:end-1}]) == 1;
end
case 'abs'
try
% ABS has predefined binary appended to
% argument list
val = feval(extstruct.fcn,extstruct.arg{1:end-2});
catch
val = nan;
end
otherwise
try
val = feval(extstruct.fcn,extstruct.arg{1:end-1});
catch
val = nan;
end
end
values(extstruct.computes) = full(val);
end
end
end
end
if ~isempty(nonlinears)
mt_t = mt'; %Working columnwise is faster
use_these = find(ismember(lmi_variables,nonlinears));
all_extended_variables = yalmip('extvariables');
for i = use_these
monom_i = mt_t(:,lmi_variables(i));
used_in_monom = find(monom_i);
if ~isempty(all_extended_variables)
extended_variables = find(ismembcYALMIP(used_in_monom,all_extended_variables));
if ~isempty(extended_variables)
for ii = 1:length(extended_variables)
extvar = used_in_monom(extended_variables(ii));
%extstruct = yalmip('extstruct',extvar);
%extstruct = getExtStruct(allStruct,extvar);
extstruct = allStruct(find([allStruct.computes] == extvar));
for k = 1:length(extstruct.arg)
if isa(extstruct.arg{k},'sdpvar')
extstruct.arg{k} = value(extstruct.arg{k});
end
end
switch extstruct.fcn
case 'abs'
val = feval(extstruct.fcn,extstruct.arg{1:end-2});
case 'sort'
w = sort(extstruct.arg{1});
val = w(extstruct.arg{2});
case 'semivar'
val = values(getvariables(extstruct.var));
case 'geomean' % Not 100% MATLAB consistent (Hermitian case differ)
val = extstruct.arg{1};
if ~any(any(isnan(val)))
[n,m] = size(val);
if n == m
if issymmetric(val)
val = max(0,real(det(val)))^(1/n);
else
val = geomean(val);
end
else
val = geomean(val);
end
else
val = nan;
end
otherwise
val = feval(extstruct.fcn,extstruct.arg{1:end-1});
end
values(extstruct.computes) = full(val);
end
end
end
% This code is a bit shaky due to the 0^0 bug in linux 6.5
%the_product = prod(values(used_in_monom).^monom_i(used_in_monom));
the_product = 1;
for j = 1:length(used_in_monom)
the_product = the_product*values(used_in_monom(j))^monom_i(used_in_monom(j));
end
values(lmi_variables(i)) = the_product;
end
end
sys = X.basis*[1;values(lmi_variables(:))];
if X.typeflag==10
sys = eig(full(reshape(sys,X.dim(1),X.dim(2))));
else
sys = full(reshape(sys,X.dim(1),X.dim(2)));
end
function extstruct = getExtStruct(allStruct,extvar)
found = 0;
extstruct = [];
i = 1;
while ~found && i <=length(allStruct)
if extvar == getvariables(allStruct(i).var)
found = 1;
extstruct = allStruct(i);
end
i = i + 1;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
cos.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/cos.m
| 1,708 |
utf_8
|
8f6b7d263e781c2959afd94381b1a131
|
function varargout = cos(varargin)
%COS (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/COS CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWiseUnitary(mfilename,varargin{:});
case 'char'
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.bounds = @bounds;
operator.derivative = @(x)(-sin(x));
operator.range = [-1 1];
operator.convexhull = @convexhull;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/COS called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xU-xL >= 2*pi
L = -1;
U = 1;
else
xL = xL + pi/2;
xU = xU + pi/2;
n = floor(( (xL + xU)/2/(2*pi)));
xL = xL - n*2*pi;
xU = xU - n*2*pi;
yL = sin(xL);
yU = sin(xU);
L = min([yL yU]);
U = max([yL yU]);
if (xL<pi/2 & xU>pi/2) | (xL<-3*pi/2 & xU>-3*pi/2)
U = 1;
end
if (xL < 3*pi/2 & xU > 3*pi/2) | (xL < -pi/2 & xU > -pi/2)
L = -1;
end
end
function [Ax, Ay, b] = convexhull(xL,xU)
% Convert to sin
xL = xL + pi/2;
xU = xU + pi/2;
if sin(xL)>=0 & sin(xU)>=0 & xU-xL<pi
fL = sin(xL);
fU = sin(xU);
dfL = cos(xL);
dfU = cos(xU);
[Ax,Ay,b] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);
elseif sin(xL)<=0 & sin(xU)<=0 & xU-xL<pi
fL = sin(xL);
fU = sin(xU);
dfL = cos(xL);
dfU = cos(xU);
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
else
[Ax,Ay,b] = convexhullGeneral(xL,xU,@sin);
end
% Back to cos
b=b-Ax*pi/2;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
erfcx.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/erfcx.m
| 674 |
utf_8
|
1f0ede69a805c09aa20815d4ee2aa46b
|
function varargout = erfcx(varargin)
%ERFCX (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/ERFCX 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;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ERFCX called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = erfcx(xU);
U = erfcx(xL);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sin.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/sin.m
| 1,835 |
utf_8
|
70d381366a829f9cd6b32d6075ea3ce2
|
function varargout = sin(varargin)
%SIN (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/SIN CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWiseUnitary(mfilename,varargin{:});
%varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
% General operator
operator = struct('convexity','none',...
'monotonicity','none',...
'definiteness','none',...
'model','callback');
operator.bounds = @bounds;
operator.convexhull = @convexhull;
operator.derivative = @(x)(cos(x));
operator.range = [-1 1];
operator.domain = [-inf inf];
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/SIN called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xU-xL >= 2*pi
L = -1;
U = 1;
else
n = floor(( (xL + xU)/2/(2*pi)));
xL = xL - n*2*pi;
xU = xU - n*2*pi;
yL = sin(xL);
yU = sin(xU);
L = min([yL yU]);
U = max([yL yU]);
if (xL<pi/2 & xU>pi/2) | (xL<-3*pi/2 & xU>-3*pi/2)
U = 1;
end
if (xL < 3*pi/2 & xU > 3*pi/2) | (xL < -pi/2 & xU > -pi/2)
L = -1;
end
end
function [Ax, Ay, b] = convexhull(xL,xU)
if sin(xL)>=0 & sin(xU)>=0 & xU-xL<pi
xM = (xL+xU)/2;
fL = sin(xL);
fM = sin(xM);
fU = sin(xU);
dfL = cos(xL);
dfM = cos(xM);
dfU = cos(xU);
[Ax,Ay,b] = convexhullConcave(xL,xM,xU,fL,fM,fU,dfL,dfM,dfU);
elseif sin(xL)<=0 & sin(xU)<=0 & xU-xL<pi
fL = sin(xL);
fU = sin(xU);
dfL = cos(xL);
dfU = cos(xU);
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
else
[Ax,Ay,b] = convexhullGeneral(xL,xU,@sin);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
min.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/min.m
| 4,676 |
utf_8
|
3e49b9ee5fa32b5c1891a289f51da69d
|
function y=min(varargin)
%MIN (overloaded)
%
% t = MIN(X)
% t = MIN(X,Y)
% t = MIN(X,[],DIM)
%
% Creates an internal structure relating the variable t with concave
% operator MIN(X).
%
% The variable t is primarily meant to be used in convexity preserving
% operations such as t>=0, maximize 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 MIN for syntax.
% MIN is implemented as a nonlinear operator.
% However, for performance issues, it is not
% implemented in the default high-level way.
%
% The return of the double value and the
% construction of the epigraph/milp is done
% in the file model.m
%
% To study a better example of how to create
% your own nonlinear operator, check the
% function sdpvar/norm instead
% 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 = min(X);
elseif length(X) == 1
y = X;
else
y = yalmip('define','min_internal',X);
reDeclareForBinaryMax(y,X);
end
return
else
% This is just short hand for general command
y = min(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.
% Introduce one extended variable/element
% Lame code since we cannot call overloaded
% subsref from inside of SDPVAR object...
% This is most likely not a often used syntax,
% so performance is neglected here...
y = [];
for i = 1:nx
temp = [];
for j = 1:mx
Xij = extsubsref(X,i,j);
Yij = extsubsref(Y,i,j);
yij = min([Xij Yij]);
temp = [temp yij];
end
y = [y;temp];
end
case 3
X = varargin{1};
Y = varargin{2};
DIM = varargin{3};
if ~(isa(X,'sdpvar') & isempty(Y))
error('MIN 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,'double')
y = [y min(inparg)];
return
end
inparg = removeInf(inparg);
if isa(inparg,'double')
y = [y min(inparg)];
elseif isa(inparg,'sdpvar')
z = yalmip('define','min_internal',inparg);
y = [y z];
reDeclareForBinaryMax(z,inparg);
else
y = [y min(inparg)];
end
end
else
% Re-use code recursively
y = min(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
|
pow2.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/pow2.m
| 975 |
utf_8
|
39f0baec231cb6e3e01ff432c5ec3237
|
function varargout = pow2(varargin)
%POW2 (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/POW2 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/POW2 called with CHAR argument?');
end
function df = derivative(x)
df = log(2)*pow2(x);
function [L,U] = bounds(xL,xU)
L = pow2(xL);
U = pow2(xU);
function [Ax, Ay, b] = convexhull(xL,xU)
fL = pow2(xL);
fU = pow2(xU);
dfL = log(2)*fL;
dfU = log(2)*fU;
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
acosh.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/acosh.m
| 716 |
utf_8
|
b0d93d0f408c0c67ffbc9791f4e52e1b
|
function varargout = acosh(varargin)
%ACOSH (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.convexhull = [];
operator.bounds = @bounds;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ACOSH called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xU<=-1
L = acosh(xU);
U = acosh(xL);
elseif xL>=1
L = acosh(xL);
U = acosh(xU);
else
L = -inf;
U = inf;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
diff.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/diff.m
| 2,025 |
utf_8
|
2a39574fd1ff1b4b733230eeead686ba
|
function Y=diff(varargin)
%DIFF (overloaded)
X = varargin{1};
n = X.dim(1);
m = X.dim(2);
switch nargin
case 1
if n == 1
% Default is diff along first dimension, unless we only have
% one row. This happens to be the case in which the core function operates
Y = differ(X);
else
% MATLAB stadnard, just diff along first dimension. Reuse core
% code by transposing matrix
Y = differ(X')';
end
return
case 2
% Note that MATLAB diff(randn(2,4),2) will cause a diff in two
% different directions.
if n == 1
if varargin{2}==1 || isempty(varargin{2})
Y = differ(X);
else
% Recursive use
Y = diff(differ(X),varargin{2}-1);
end
else
if varargin{2}==1 || isempty(varargin{2})
Y = differ(X')';
else
% Recursive use
Y = diff(differ(X')',varargin{2}-1);
end
end
case 3
if X.dim(varargin{3})-varargin{2} <=0
dim = X.dim;
dim(varargin{3}) = 0;
Y = zeros(dim);
elseif varargin{2}==1
if varargin{3} == 2
Y = differ(X);
elseif varargin{3} == 1 || isempty(varargin{3})
Y = differ(X')';
end
elseif varargin{2} > 1
% Recursive call for higher-order diff
Y = diff(diff(X,varargin{2}-1,varargin{3}),1,varargin{3});
return
end
otherwise
error('To many input arguments.')
end
function Y = differ(X)
n = X.dim(1);
m = X.dim(2);
Y = X;
shift = [-speye(m-1) spalloc(m-1,1,0)] + [spalloc(m-1,1,0) speye(m-1)];
shift = kron(shift,speye(n));
Y.basis = shift*X.basis;
Y.dim(1) = n;
Y.dim(2) = m - 1;
% Reset info about conic terms
Y.conicinfo = [0 0];
Y = flush(Y);
Y = clean(Y);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
erfinv.m
|
.m
|
LMI-Matlab-master/yalmip/@sdpvar/erfinv.m
| 803 |
utf_8
|
810f64595d183f3910c960d722dcc702
|
function varargout = erfinv(varargin)
%ERFINV (overloaded)
switch class(varargin{1})
case 'double'
error('Overloaded SDPVAR/ERFINV CALLED WITH DOUBLE. Report error')
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
X = varargin{3};
F = (-1+1e-9 <= X <= 1-1e-9);
operator = struct('convexity','none','monotonicity','increasing','definiteness','none','model','callback');
operator.bounds = @bounds;
varargout{1} = F;
varargout{2} = operator
varargout{3} = X;
otherwise
error('SDPVAR/ERF called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
if xL<=-1
L = -inf
else
L = erfinv(xL);
end
if xU>=1
U = inf;
else
U = erfinv(xU);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callkypd.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callkypd.m
| 4,451 |
utf_8
|
62267054f26da5f4af3119e87fecc8f8
|
function diagnostic = callkypd(F,h,options)
%F = constraint2kyp(F);
kyps = is(F,'kyp');
if all(kyps)
kypConstraints = F;
otherConstraints = lmi;
else
kypConstraints = F(find(kyps));
otherConstraints = F(find(~kyps));
end
% Trivial case
if length(kypConstraints) == 0
if ~isempty(options)
options.solver = '';
else
options = sdpsettings;
end
diagnostic = solvesdp(F,h,options)
return;
end
p_variables = [];
x_variables = [];
for i = 1:length(kypConstraints)
[A{i},B{i},P{i},M{i},negated{i}] = extractkyp(sdpvar(kypConstraints(i)));
if ~isa(P{i},'sdpvar') | ~isempty(intersect(p_variables,getvariables(P{i})))
diagnostic.solvertime = 0;
diagnostic.problem = -4;
diagnostic.info = yalmiperror(-4);
return;
end
P_base = getbase(P{i});
[n,m] = size(P{i});
if (n~=m) | (nnz(P_base)~=n*n) | (sum(sum(P_base))~=n*n)
diagnostic.solvertime = 0;
diagnostic.problem = -4;
diagnostic.info = yalmiperror(-4);
return;
end
p_variables = [p_variables getvariables(P{i})];
x_variables = [x_variables getvariables(M{i})];
end
if intersect(p_variables,getvariables(h))
diagnostic.solvertime = 0;
diagnostic.problem = -4;
diagnostic.info = yalmiperror(-4);
return;
end
start = length(A);k = 1;
for i = 1:length(otherConstraints)
if is(otherConstraints(i),'lmi')
A{k+start}=[];
B{k+start}=[];
P{k+start}=[];
M{k+start} = sdpvar(otherConstraints(i));
x_variables = [x_variables getvariables(M{k+start})];
k = k + 1;
elseif is(otherConstraints(i),'elementwise')
X = sdpvar(otherConstraints(i));
for ii = 1:size(X,1)
for jj = 1:size(X,2)
A{k+start}=[];
B{k+start}=[];
P{k+start}=[];
M{k+start} = X(ii,jj);
x_variables = [x_variables getvariables(X(ii,jj))];
k = k + 1;
end
end
end
end
% Objective function variables
x_variables = unique([x_variables getvariables(h)]);
% Are P and x independent
if ~isempty(intersect(p_variables,x_variables))
error
end
% Generate the M-matrices
for i = 1:length(M)
m_variables = getvariables(M{i});
n = length(M{i});
M0{i} = getbasematrix(M{i},0);
for j = 1:length(x_variables)
Mi{i,j} = getbasematrix(M{i},x_variables(j));
end
end
c = zeros(length(x_variables),1);
if ~isempty(h)
for i = 1:length(x_variables)
c(i) = getbasematrix(h,x_variables(i));
end
end
for i = 1:length(M)
matrixinfo.n(i) = length(A{i});
matrixinfo.nm(i) = length(M{i});
end
matrixinfo.K = length(x_variables);
matrixinfo.c = c;
matrixinfo.N = length(A);
matrixinfo.A = A;
matrixinfo.B = B;
matrixinfo.M0 = M0;
matrixinfo.M = Mi;
matrixinfo.A = A;
try
solvertime = tic;
[u,Popt,xopt,Zopt] = kypd_solver(matrixinfo,options);
solvertime = toc(solvertime);
% SAVE PRIMALS
setsdpvar(recover(x_variables),xopt);
for i = 1:length(kypConstraints)
if negated{i}
setsdpvar(P{i},-Popt{i});
else
setsdpvar(P{i},Popt{i});
end
end
% SAVE DUALS
lmi_index = [];
j = 1;
for i = 1:length(kypConstraints)
%W = struct(kypConstraints(i));lmiid = W.LMIid;
lmiid = getlmiid(kypConstraints(i));
lmi_index = [lmi_index;lmiid];
duals{j}=Zopt{j};j = j+1;
end
for i = 1:length(otherConstraints)
%W = struct(otherConstraints(i));lmiid = W.LMIid;
lmiid = getlmiid(otherConstraints(i));
lmi_index = [lmi_index;lmiid];
duals{j}=Zopt{j};j = j+1;
end
yalmip('setdual',lmi_index,duals);
diagnostic.solvertime = solvertime;
diagnostic.info = yalmiperror(0,'KYPD');
diagnostic.problem = 0;
catch
solvertime = etime(clock,solvertime);
diagnostic.solvertime = solvertime;
diagnostic.info = yalmiperror(9,'KYPD');
diagnostic.problem = 9;
end
function Fout = constraint2kyp(F)
Fout = [];
for i = 1:length(F)
if is(F(i),'lmi')
[l,m,r] = factors(sdpvar(F(i)));
[constants,general,singles,pairs] = classifyfactors(l,m,r);
[constants,general,singles,pairs] = compressfactors2(constants,general,singles,pairs);
else
Fout = Foput + F(i);
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callscs.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callscs.m
| 5,222 |
utf_8
|
f7780f5b754144a484627c8bbc36f191
|
function output = callscs(model)
% Retrieve needed data
options = model.options;
F_struc = model.F_struc;
c = model.c;
K = model.K;
ub = model.ub;
lb = model.lb;
% *********************************************
% Bounded variables converted to constraints
% N.B. Only happens when caller is BNB
% *********************************************
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
data.A = -F_struc(:,2:end);
data.b = full(F_struc(:,1));
data.c = full(c);
cones = [];
cones.f = K.f;
cones.l = K.l;
cones.q = K.q;
cones.s = K.s;
% Now add exponential cone information
[data,cones,output] = addExponentialCone(data,cones,model);
if output.problem
return
end
if options.showprogress;showprogress(['Calling ' model.solver.tag],options.showprogress);end
params = options.scs;
params.verbose = options.verbose;
if params.eliminateequalities
tempmodel.F_struc = [data.b -data.A];
tempmodel.c = data.c;
tempmodel.K = cones;
[tempmodel,xsol,H] = removeequalitiesinmodel(tempmodel);
data.b = full(tempmodel.F_struc(:,1));
data.A = -tempmodel.F_struc(:,2:end);
data.c = full(tempmodel.c);
cones = tempmodel.K;
else
H = 1;
xsol = 0;
end
if options.savedebug
save scsdebug data cones params
end
% Extract lower diagonal form for new SCS format
if ~isempty(cones.s) && any(cones.s)
sdpA = data.A(1+cones.l + cones.f+sum(cones.q):end,:);
sdpb = data.b(1+cones.l + cones.f+sum(cones.q):end,:);
expA = data.A(end-3*cones.ep+1:end,:);
expb = data.b(end-3*cones.ep+1:end,:);
data.A = data.A(1:cones.l + cones.f+sum(cones.q),:);
data.b = data.b(1:cones.l + cones.f+sum(cones.q),:);
top = 1;
for i = 1:length(cones.s)
A = sdpA(top:top + cones.s(i)^2-1,:);
b = sdpb(top:top + cones.s(i)^2-1,:);
n = cones.s(i);
ind = find(speye(n));
b(ind) = b(ind)/sqrt(2);
A(ind,:) = A(ind,:)/sqrt(2);
ind = find(tril(ones(n)));
A = A(ind,:);
b = b(ind);
data.A = [data.A;A];
data.b = [data.b;b];
top = top + cones.s(i)^2;
end
data.A = [data.A;expA];
data.b = [data.b;expb];
end
t = tic;
problem = 0;
switch model.solver.tag
case 'scs-direct'
[x_s,y_s,s,info] = scs_direct(data,cones,params);
otherwise
[x_s,y_s,s,info] = scs_indirect(data,cones,params);
end
solvertime = toc(t);
% Internal format. Only recover the original variables
Primal = H*x_s+xsol;
Primal = Primal(1:length(model.c));
if ~isempty(model.evalMap)
% No support for duals when exponential cones yet
Dual = [];
else
% Map to full format from tril
Dual = y_s(1:cones.f+cones.l+sum(cones.q));
if ~isempty(cones.s) && any(cones.s)
top = 1 + cones.f + cones.l + sum(cones.q);
for i = 1:length(cones.s)
n = cones.s(i);
sdpdual = y_s(top:top + n*(n+1)/2-1,:);
Z = zeros(n);
Z(find(tril(ones(n)))) = sdpdual;
Z = (Z + Z')/2;
ind = find(speye(n));
Z(ind) = Z(ind)/sqrt(2);
Dual = [Dual;Z(:)];
top = top + n*(n+1)/2;
end
end
end
if nnz(data.c)==0 && isequal(info.status,'Unbounded/Inaccurate')
info.status = 'Infeasible';
end
switch info.status
case 'Solved'
problem = 0;
case 'Infeasible'
problem = 1;
case 'Unbounded'
problem = 2;
otherwise
status = 9;
end
infostr = yalmiperror(problem,model.solver.tag);
% Save ALL data sent to solver
if options.savesolverinput
solverinput.data = data;
solverinput.cones = cones;
solverinput.params = params;
else
solverinput = [];
end
% Save ALL data from the solution?
if options.savesolveroutput
solveroutput.x = x_s;
solveroutput.y = y_s;
solveroutput.s = s;
solveroutput.info = info;
else
solveroutput = [];
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function [model,x0,H] = removeequalitiesinmodel(model)
if model.K.f > 0
% Extract the inequalities
A_equ = model.F_struc(1:model.K.f,2:end);
b_equ = -model.F_struc(1:model.K.f,1);
if 1
% Find a basis for the column space of A_equ
[L,U,P] = lu(A_equ');
r = colspaces(L');
AA = L';
H1 = AA(:,r);
H2 = AA(:,setdiff(1:size(AA,2),r));
try
x0 = P'*linsolve(full(L'),linsolve(full(U'),full(b_equ),struct('LT',1==1)),struct('UT',1==1));
catch
x0 = A_equ\b_equ;
end
% FIX : use L and U stupid!
H = P'*[-H1\H2;eye(size(H2,2))];
else
H = null(full(A_equ));
x0 = A_equ\b_equ;
end
model.c = H'*model.c;
model.F_struc(:,1) = model.F_struc(:,1) + model.F_struc(:,2:end)*x0;
model.F_struc = [model.F_struc(:,1) model.F_struc(:,2:end)*H];
model.F_struc(1:model.K.f,:)=[];
model.K.f = 0;
else
H = speye(length(model.c));
x0 = zeros(length(model.c),1);
end
function [indx]=colspaces(A)
indx = [];
for i = 1:size(A,2)
s = max(find(A(:,i)));
indx = [indx s];
end
indx = unique(indx);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callsdpnal.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callsdpnal.m
| 3,766 |
utf_8
|
301376600dc2200cedc573f6f81ce14e
|
function output = callsdpnal(interfacedata)
% Retrieve needed data
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
K = interfacedata.K;
x0 = interfacedata.x0;
ub = interfacedata.ub;
lb = interfacedata.lb;
% Bounded variables converted to constraints
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
[blk,A,C,b,oldKs]=sedumi2sdpt3(F_struc(:,1),F_struc(:,2:end),c,K,1);
if options.savedebug
ops = options.sdpnal;
save sdpnaldebug blk A C b ops -v6
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
if options.verbose==0
evalc('[obj,X,y,Z,info,runhist] = sdpnal(blk,A,C,b,options.sdpnal);');
else
switch interfacedata.solver.tag
case 'SDPNAL-0.3'
%[obj,X,y,Z,info,runhist] = sdpnalplus(blk,A,C,b,[],[],[],[],[],options.sdpnal);
[obj,X,s,y,Z,Z2,y2,v,info,runhist] = sdpnalplus(blk,A,C,b,[],[],[],[],[],options.sdpnal);
otherwise
[obj,X,y,Z,info,runhist] = sdpNAL(blk,A,C,b,options.sdpnal);
end
end
solvertime = toc(solvertime);
% Create YALMIP dual variable and slack
Dual = [];
Slack = [];
top = 1;
if K.f>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top+1;
end
if K.l>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top + 1;
end
if K.q(1)>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top + 1;
end
if K.s(1)>0
% Messy format in SDPT3 to block and sort small SDPs
u = blk(:,1);
u = find([u{:}]=='s');
s = 1;
for top = u
ns = blk(top,2);ns = ns{1};
k = 1;
for i = 1:length(ns)
Xi{oldKs(s)} = X{top}(k:k+ns(i)-1,k:k+ns(i)-1);
Zi{oldKs(s)} = Z{top}(k:k+ns(i)-1,k:k+ns(i)-1);
s = s + 1;
k = k+ns(i);
end
end
for i = 1:length(Xi)
Dual = [Dual;Xi{i}(:)];
Slack = [Slack;Zi{i}(:)];
end
end
Primal = -y; % Primal variable in YALMIP
% No error code available
if isfield(info,'termcode')
switch info.termcode
case -1
problem = 4;
case 0
problem = 0;
case 1
problem = 5;
case 2
problem = 3;
otherwise
problem = 11;
end
else
if isfield(info,'msg')
if isequal(info.msg,'maximum iteration reached')
problem = 3;
else
problem = 9;
end
end
end
infostr = yalmiperror(problem,interfacedata.solver.tag);
if options.savesolveroutput
solveroutput.obj = obj;
solveroutput.X = X;
solveroutput.y = y;
solveroutput.Z = Z;
solveroutput.info = info;
solveroutput.runhist = runhist;
else
solveroutput = [];
end
if options.savesolverinput
solverinput.blk = blk;
solverinput.A = A;
solverinput.C = C;
solverinput.b = b;
solverinput.options = options.sdpnal;
else
solverinput = [];
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function [F_struc,K] = deblock(F_struc,K);
X = any(F_struc(end-K.s(end)^2+1:end,:),2);
X = reshape(X,K.s(end),K.s(end));
[v,dummy,r,dummy2]=dmperm(X);
blks = diff(r);
lint = F_struc(1:end-K.s(end)^2,:);
logt = F_struc(end-K.s(end)^2+1:end,:);
newlogt = [];
for i = 1:size(logt,2)
temp = reshape(logt(:,i),K.s(end),K.s(end));
temp = temp(v,v);
newlogt = [newlogt temp(:)];
end
logt = newlogt;
pattern = [];
for i = 1:length(blks)
pattern = blkdiag(pattern,ones(blks(i)));
end
F_struc = [lint;logt(find(pattern),:)];
K.s(end) = [];
K.s = [K.s blks];
K.m = blks;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callquadprogbb.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callquadprogbb.m
| 2,112 |
utf_8
|
9c075a2736463b4b85a7c58e6fa44997
|
function output = callquadprogbb(interfacedata)
options = interfacedata.options;
model = yalmip2quadprog(interfacedata);
if options.savedebug
save debugfile model
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
solveroutput = callsolver(model,options);
solvertime = toc(solvertime);
solution = quadprogsol2yalmipsol(solveroutput,model);
% Save all data sent to solver?
if ~options.savesolverinput
model = [];
end
% Save all data from the solver?
if ~options.savesolveroutput
solveroutput = [];
end
% Standard interface
Primal = solution.x(:);
Dual = solution.D_struc;
problem = solution.problem;
infostr = yalmiperror(solution.problem,interfacedata.solver.tag);
if ~options.savesolverinput
solverinput = [];
else
solverinput = model;
end
if ~options.savesolveroutput
solveroutput = [];
else
solveroutput = solveroutput;
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function solveroutput = callsolver(model,options)
x = [];
fmin = [];
flag = [];
output = [];
lambda = [];
options.quadprogbb.constant = model.f;
if options.verbose
options.quadprogbb.verbosity = options.verbose - 1;
[x,fval,time,stat] = quadprogbb(model.Q,model.c,model.A,model.b,model.Aeq,model.beq,model.lb,model.ub,options.quadprogbb);
else
options.quadprogbb.verbosity = 0;
evalc('[x,fval,time,stat] = quadprogbb(model.Q,model.c,model.A,model.b,model.Aeq,model.beq,model.lb,model.ub,options.quadprogbb);');
end
solveroutput.x = x;
solveroutput.fval = fval;
solveroutput.time = time;
solveroutput.stat = stat;
function solution = quadprogsol2yalmipsol(solveroutput,model)
solution.x = solveroutput.x(:);
solution.D_struc = [];
switch solveroutput.stat.status
case 'opt_soln'
solution.problem = 0;
case 'inf_or_unb'
solution.problem = 12;
case 'num_issues'
solution.problem = 4;
case 'time_limit'
solution.problem = 3;
otherwise
solution.problem = -1;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callmpt3.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callmpt3.m
| 3,688 |
utf_8
|
ad7eb3b682d81797392f46cd553fad13
|
function output = callmpt3(interfacedata)
% Speeds up solving LPs in mpmilp
global MPTOPTIONS
if ~isstruct(MPTOPTIONS)
mpt_error
end
% Convert
Matrices = yalmip2mpt(interfacedata);
% Get some MPT options
options = interfacedata.options;
options.mpt.lpsolver = MPTOPTIONS.lpsolver;
options.mpt.milpsolver = MPTOPTIONS.milpsolver;
options.mpt.verbose = options.verbose;
if options.savedebug
save mptdebug Matrices
end
if options.mp.unbounded
Matrices = removeExplorationConstraints(Matrices);
end
[dummy,un] = unique([Matrices.G Matrices.E Matrices.W],'rows');
Matrices.G = Matrices.G(un,:);
Matrices.E = Matrices.E(un,:);
Matrices.W = Matrices.W(un,:);
if isempty(Matrices.binary_var_index)
showprogress('Calling MPT',options.showprogress);
solvertime = tic;
if options.mp.presolve
[Matrices.lb,Matrices.ub] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);
end
if any(Matrices.lb(end-Matrices.nx+1:end) == Matrices.ub(end-Matrices.nx+1:end))
model = [];
else
model = mpt_solvenode(Matrices,Matrices.lb,Matrices.ub,Matrices,[],options);
end
solvertime = toc(solvertime);
else
% Pre-solve required on binary problems
options.mp.presolve = 1;
solvertime = tic;
switch options.mp.algorithm
case 1
showprogress('Calling MPT via enumeration',options.showprogress);
model = mpt_enumeration_mpmilp(Matrices,options);
case 2
% Still experimental and just for fun. Not working!
showprogress('Calling MPT via parametric B&B',options.showprogress);
model = mpt_parbb(Matrices,options);
case 3
showprogress('Calling MPT via delayed enumeration',options.showprogress);
[Matrices.SOS,Matrices.SOSVariables] = mpt_detect_sos(Matrices);
[Matrices.lb,Matrices.ub] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);
model = mpt_de_mpmilp(Matrices,options,[]);
otherwise
end
solvertime = toc(solvertime);
end
if isempty(model)
model = {model};
end
if options.verbose
if ~isempty(model{1})
if length(model) == 1
disp(['-> Generated 1 partition.'])
else
disp(['-> Generated ' num2str(length(model)) ' partitions.'])
end
end
end
problem = 0;
infostr = yalmiperror(problem,'MPT');
% Save all data sent to solver?
if options.savesolverinput
solverinput.Matrices = Matrices;
solverinput.options = [];
else
solverinput = [];
end
% Save all data from the solver?
% This always done
if options.savesolveroutput
solveroutput.model = model;
solveroutput.U = interfacedata.used_variables(Matrices.free_var);%(Matrices.free_var <= length( interfacedata.used_variables)));
solveroutput.x = interfacedata.used_variables(Matrices.param_var);
else
solveroutput = [];
end
% Standard interface
Primal = nan*ones(length(interfacedata.c),1);
Dual = [];
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function Matrices = removeExplorationConstraints(Matrices);
candidates = find((~any(Matrices.G,2)) & (sum(Matrices.E | Matrices.E,2) == 1));
if ~isempty(candidates)
Matrices.bndA = -Matrices.E(candidates,:);
Matrices.bndb = Matrices.W(candidates,:);
Matrices.G(candidates,:) = [];
Matrices.E(candidates,:) = [];
Matrices.W(candidates,:) = [];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callsedumi.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callsedumi.m
| 4,208 |
utf_8
|
06ea0482ba007c5e4e0f579308a9def3
|
function output = callsedumi(model)
% Retrieve needed data
options = model.options;
F_struc = model.F_struc;
c = model.c;
K = model.K;
ub = model.ub;
lb = model.lb;
% Create the parameter structure
pars = options.sedumi;
pars.fid = double(options.verbose);
% *********************************************
% Bounded variables converted to constraints
% N.B. Only happens when caller is BNB
% *********************************************
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
% Avoid bug (by design?) in SeDuMi on 1D second order cones
if any(K.q == 2)
[F_struc,K] = fix1Dqcone(F_struc,K);
end
if options.savedebug
save sedumidebug F_struc c K pars
end
% *********************************************
% Call SeDuMi
% *********************************************
if options.showprogress;showprogress(['Calling ' model.solver.tag],options.showprogress);end
problem = 0;
warnState = warning;
solvertime = tic;
try
[x_s,y_s,info] = sedumi(-F_struc(:,2:end),-c,F_struc(:,1),K,pars);
catch
if findstr(lasterr,'Out of memory')
error(lasterr)
end
try
if options.verbose > 0
disp(' ');
disp('SeDuMi had unexplained problems, maybe due to linear dependence?')
disp('YALMIP tweaks the problem (adds 1e6 magnitude bounds on all variables) and restarts...')
disp(' ');
end
% Boring issue in sedumi for trivial problem min x+y, s.t x+y>0
n = length(c);
[F_struc,K] = addbounds(F_struc,K,ones(n,1)*1e6,-ones(n,1)*1e6);
[x_s,y_s,info] = sedumi(-F_struc(:,2:end),-c,F_struc(:,1),K,pars);
x_s((1:2*n)+K.f)=[];
K.l=K.l-2*n;
catch
disp('Nope, unexplained crash in SeDuMi! (could be memory issues or wrong binary)')
disp('Make sure you have a recent and compiled version')
disp(' ')
disp(' ')
disp('For better diagnostics, use sdpsettings(''debug'',1)')
disp(' ')
disp(' ')
end
end
warning(warnState);
solvertime = toc(solvertime);
% Internal format
Primal = y_s;
Dual = x_s;
temp = info.pinf;
pinf = info.dinf;
dinf = temp;
% Check for reported errors
if (pinf==0) & (dinf==0)
problem = 0; % No problems
end
% We can only report one error, use priorities
if (problem==0) & (pinf==1)
problem = 1; % Primal infeasability
end
if (problem==0) & (dinf==1)
problem = 2; % Dual infeasability
end
if (problem==0) & (info.numerr==1) | (info.numerr==2)
problem = 4; %Numerical problems
end
if (problem==0) & (info.iter >= options.sedumi.maxiter)
% Did we need exactly maxiter iterations to find optimum
if (pinf==0) & (dinf==0) & (info.numerr==0)
problem = 0; % Yes
else
problem = 3; % No, we are not optimal yet
end
end
if (problem==0) & (info.feasratio<0.98)
problem = 4;
end
% Fix for cases not really explained in documentation of sedumi?
if (abs(info.feasratio+1)<0.1) & (pinf==0) & (dinf==0)
problem = 1;
end
if (abs(info.feasratio+1)<0.1) & (pinf==0) & (dinf==0) & (c'*y_s<-1e10)
problem = 2;
end
infostr = yalmiperror(problem,model.solver.tag);
% Save ALL data sent to solver
if options.savesolverinput
solverinput.A = -F_struc(:,2:end);
solverinput.c = F_struc(:,1);
solverinput.b = -c;
solverinput.K = K;
solverinput.pars = pars;
else
solverinput = [];
end
% Save ALL data from the solution?
if options.savesolveroutput
solveroutput.x = x_s;
solveroutput.y = y_s;
solveroutput.info = info;
else
solveroutput = [];
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function [new_F_struc,K] = fix1Dqcone(F_struc,K);
new_F_struc = F_struc(1:(K.l+K.f),:);
top = K.f + K.l + 1;
for i = 1:length(K.q)
if K.q(i) == 2
new_F_struc = [new_F_struc;F_struc(top,:);F_struc(top+1,:);F_struc(top,:)*0];
K.q(i) = 3;
top = top + 2;
else
new_F_struc = [new_F_struc;F_struc(top:top+K.q(i)-1,:)];
top = top + K.q(i);
end
end
new_F_struc = [new_F_struc;F_struc(top:end,:)];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callscipnl.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callscipnl.m
| 6,643 |
utf_8
|
eb1a63a10553a041f4b536ce146a8c68
|
function output = callscipnl(model)
% This sets up everything and more. Can be simplified significantly since
% baron handles its own computational tree etc
model = yalmip2nonlinearsolver(model);
% [Anonlinear*f(x) <= b;Anonlinear*f(x) == b]
cu = full([model.bnonlinineq;model.bnonlineq]);
cl = full([repmat(-inf,length(model.bnonlinineq),1);model.bnonlineq]);
Anonlinear = [ model.Anonlinineq; model.Anonlineq];
% Create string representing objective
obj = createmodelstring(model.c,model);
obj = strrep(obj,'sqrtm_internal','sqrt');
if nnz(model.Q)>0
obj = [obj '+' createQstring(model.Q,model)];
end
if model.f > 0
obj = [obj '+' num2str(model.f)];
end
if isempty(obj)
obj = [];
else
if obj(1)=='+'
obj = obj(2:end);
end
% Append quadratic term
obj = ['@(x) ' obj];
obj = eval(obj);
end
% Create string representing nonlinear constraints
if length(cu)>0
con = '[';
remove = [];
for i = 1:length(cu)
if isinf(cl(i)) & isinf(cu(i))
remove = [remove;i];
else
con = [con createmodelstring(Anonlinear(i,:),model) ';'];
end
end
cl(remove) = [];
cu(remove) = [];
con = [con ']'];
con = strrep(con,'sqrtm_internal','sqrt');
con = strrep(con,'slog(x','log(1+x');
con = ['@(x) ' con];
con = eval(con);
else
cu = [];
cl = [];
con = [];
end
% Linear constraints
ru = full([model.b;model.beq]);
rl = full([repmat(-inf,length(model.b),1);model.beq]);
A = [model.A; model.Aeq];
if length(ru)>0
remove = find(isinf(rl) & isinf(ru));
A(remove,:)=[];
rl(remove) = [];
ru(remove) = [];
end
lb = model.lb;
ub = model.ub;
xtype = [];
xtype = repmat('C',length(lb),1);
xtype(model.binary_variables) = 'B';
xtype(model.integer_variables) = 'I';
x0 = model.x0;
opts = model.options.scip;
switch model.options.verbose
case 0
opts.display = 'off';
otherwise
opts.display = 'iter';
end
if model.options.savedebug
save scipnldebug obj con A ru rl cl cu xtype lb ub x0 opts
end
solvertime = tic;
[x,fval,exitflag,info] = opti_scipnl(obj,A,rl,ru,lb,ub,con,cl,cu,xtype,[],opts);%,x0,opts);
solvertime = toc(solvertime);
% Check, currently not exhaustive...
switch exitflag
case 0
if ~isempty(strfind(info.Status,'Exceed'))
problem = 3;
else
problem = 9;
end
case 1
problem = 0;
case {2,-1}
problem = 1;
case 3
problem = 2;
case {4,5}
problem = 11;
otherwise
problem = 9;
end
% Save all data sent to solver?
if model.options.savesolverinput
solverinput.obj = obj;
solverinput.A = A;
solverinput.rl = rl;
solverinput.ru = ru;
solverinput.lb = lb;
solverinput.ub = ub;
solverinput.con = con;
solverinput.cl = cl;
solverinput.cu = cu;
solverinput.xtype = xtype;
solverinput.opts = opts;
else
solverinput = [];
end
% Save all data from the solver?
if model.options.savesolveroutput
solveroutput.x = x;
solveroutput.fval = fval;
solveroutput.exitflag = exitflag;
solveroutput.info=info;
solveroutput.allsol=allsol;
else
solveroutput = [];
end
if ~isempty(x)
x = RecoverNonlinearSolverSolution(model,x);
end
% Standard interface
output = createoutput(x,[],[],problem,'SCIP-NL',solverinput,solveroutput,solvertime);
function z = createOneterm(i,model)
[evalPos,pos] = ismember(i,model.evalVariables);
if pos
% This is a nonlinear operator
map = model.evalMap{pos};
% We might hqave vectorized things to compute several expressions at the same time
if length(map.computes) == 1 && length(map.variableIndex) > 1
if isequal(map.fcn,'plog')
j1 = find(model.linearindicies == map.variableIndex(1));
j2 = find(model.linearindicies == map.variableIndex(2));
if isempty(j1)
z1 = createmonomstring(model.monomtable(map.variableIndex(1),:),model);
else
z1 = ['x(' num2str(j1) ')'];
end
if isempty(j2)
z1 = createmonomstring(model.monomtable(map.variableIndex(2),:),model);
else
z2 = ['x(' num2str(j2) ')'];
end
z = [z1 '*log(' z2 '/' z1 ')'];
else
z = [map.fcn '('];
for j = map.variableIndex
jl = find(model.linearindicies == j);
if isempty(jl)
z = [z createmonomstring(model.monomtable(j,:),model)];
else
z = [z 'x(' num2str(jl) ')'];
end
if j == length(map.variableIndex)
z = [z ')'];
else
z = [z ','];
end
end
end
else
j = find(map.computes == i);
j = map.variableIndex(j);
% we have f(x(j)), but have to map back to linear indicies
jl = find(model.linearindicies == j);
if isempty(jl)
z = [map.fcn '(' createmonomstring(model.monomtable(j,:),model) ')'];
else
z = [map.fcn '(x(' num2str(jl) '))'];
end
end
else
i = find(model.linearindicies == i);
z = ['x(' num2str(i) ')'];
end
function monomstring = createmonomstring(v,model)
monomstring = '';
for i = find(v)
z = createOneterm(i,model);
if v(i)==1
monomstring = [monomstring z '*'];
else
monomstring = [monomstring z '^' num2str(v(i),12) '*'];
end
end
monomstring = monomstring(1:end-1);
function string = createmodelstring(row,model)
string = '';
index = find(row);
for i = index(:)'
monomstring = createmonomstring(model.monomtable(i,:),model);
string = [string num2str(row(i),12) '*' monomstring '+'];
end
string = string(1:end-1);
string = strrep(string,'+-','-');
string = strrep(string,')-1*',')-');
string = strrep(string,')+1*',')+');
function string = createQstring(Q,model)
% Special code for the quadratic term
string = '';
[ii,jj,c]= find(triu(Q));
for i = 1:length(ii)
if ii(i)==jj(i)
% Quadratic term
monomstring = createmonomstring(sparse(1,ii(i),1,1,size(Q,1)),model);
string = [string num2str(c(i),12) '*' monomstring '^2' '+'];
else
% Bilinear term
monomstring1 = createmonomstring(sparse(1,ii(i),1,1,size(Q,1)),model);
monomstring2 = createmonomstring(sparse(1,jj(i),1,1,size(Q,1)),model);
string = [string num2str(c(i),12) '*2*' monomstring1 '*' monomstring2 '+'];
end
end
string = string(1:end-1);
string = strrep(string,'+-','-');
string = strrep(string,'-1*','-');
string = strrep(string,'+1*','+');
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callsdplr.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callsdplr.m
| 5,257 |
utf_8
|
e6972916ac1a58d754eb41383f04cc74
|
function output = callsdplr(interfacedata)
% Retrieve needed data
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
K = interfacedata.K;
ub = interfacedata.ub;
lb = interfacedata.lb;
lowrankdetails = interfacedata.lowrankdetails;
% Create the parameter structure
pars = options.sdplr;
pars.printlevel = options.verbose;
% *********************************************
% Bounded variables converted to constraints
% N.B. Only happens when caller is BNB
% *********************************************
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
% rmfield is slow...
Knew.l = K.l;
Knew.s = K.s;
K = Knew;
if options.savedebug
save sdplrdebug F_struc c K pars -V6
end
% *********************************************
%FIND LOW RANK STRUCTURES
% *********************************************
problem = 0;
lrA = [];
if ~isempty(lowrankdetails) | (options.sdplr.maxrank>0 & (K.s(1)>0))
showprogress('Detecting low rank data',options.showprogress);
sdploc = K.l+cumsum([1 K.s.^2]);
k = 1;
% FIX : Lazy code copy...
[ix,jx,sx] = find(F_struc);
if isempty(lowrankdetails)
% Okay, this means we have to go through everything...
% Get all data in F_struc for later
for lmiid = 1:length(K.s)
removethese = zeros(1,size(F_struc,2)-1);
for i = 1:size(F_struc,2)-1
Fi = reshape(F_struc(sdploc(lmiid):sdploc(lmiid+1)-1,i+1),K.s(lmiid),K.s(lmiid));
if nnz(Fi)>0
[D,V] = getfactors(Fi);
if length(D) <= options.sdplr.maxrank
lrA(k).cons = i;
lrA(k).start = sdploc(lmiid);
lrA(k).D = D;
lrA(k).V = V;
k = k+1;
removethese(i) = 1;
end
end
end
removethese = find(removethese);
if ~isempty(removethese)
these = find((sdploc(lmiid+1)-1>= ix) & (ix>=sdploc(lmiid)) & ismember(jx,1+removethese));
sx(these) = 0;
end
end
else
% Just check those constraints declared low-rank by user
for lrdef = 1:length(lowrankdetails)
for lrconstraint = 1:length(lowrankdetails{lrdef}.id)
lmiid = lowrankdetails{lrdef}.id(lrconstraint);
removethese = zeros(1,size(F_struc,2)-1);
checkthese = lowrankdetails{lrdef}.variables;
if isempty(checkthese)
checkthese = 1:size(F_struc,2)-1;
end
for i = checkthese
Fi = reshape(F_struc(sdploc(lmiid):sdploc(lmiid+1)-1,i+1),K.s(lmiid),K.s(lmiid));
if nnz(Fi)>0
[D,V] = getfactors(Fi);
if (options.sdplr.maxrank == 0) | (options.sdplr.maxrank ~= 0 & (length(D) <= options.sdplr.maxrank))
lrA(k).cons = i;
lrA(k).start = sdploc(lmiid);
lrA(k).D = D;
lrA(k).V = V;
k = k+1;
removethese(i) = 1;
end
end
end
removethese = find(removethese);
if ~isempty(removethese)
these = find((sdploc(lmiid+1)-1>= ix) & (ix>=sdploc(lmiid)) & ismember(jx,1+removethese));
sx(these) = 0;
%F_struc(sdploc(lmiid):sdploc(lmiid+1)-1,1+removethese) = 0;
end
end
end
F_struc = sparse(ix,jx,sx,size(F_struc,1),size(F_struc,2));
end
end
% *********************************************
% CALL SDPLR
% *********************************************
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
if isempty(lrA)
[x_s,y_s,info] = sdplr(F_struc(:,2:end),c,F_struc(:,1),K);
else
% pars.reduce = 0;
[x_s,y_s,info] = sdplr(F_struc(:,2:end),full(c),full(F_struc(:,1)),K,pars,lrA);
end
solvertime = toc(solvertime);
% YALMIP format
D_struc = x_s;
x = -y_s;
% No error codes currently...
problem = 0;
infostr = yalmiperror(problem,interfacedata.solver.tag);
% Save ALL data sent to solver
if options.savesolverinput
solverinput.A = F_struc(:,2:end);
solverinput.c = F_struc(:,1);
solverinput.b = c;
solverinput.K = K;
solverinput.pars = pars;
else
solverinput = [];
end
% Save ALL data from the solution?
if options.savesolveroutput
solveroutput.x = x_s;
solveroutput.y = y_s;
solveroutput.info = info;
else
solveroutput = [];
end
% Standard interface
output = createOutputStructure(x(:),D_struc,[],problem,infostr,solverinput,solveroutput,solvertime);
function [D,V] = getfactors(Fi)
if nnz(Fi)>0
[v,d] = eig(full(Fi));
d = diag(d);
keep = find(abs(d)>1e-6);
V = v(:,keep);
D = d(keep);
% lrA(k).cons = i;
% lrA(k).start = sdploc(j);
% lrA(k).D = D;
% lrA(k).V = V;
% k = k+1;
else
D = [];
V = [];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callmpt.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callmpt.m
| 4,404 |
utf_8
|
d55f6f404d70471bb0592d9456465ffd
|
function output = callmpt(interfacedata)
% This file is kept for MPT2 compatability
% Speeds up solving LPs in mpmilp
global mptOptions
if ~isstruct(mptOptions)
mpt_error
end
% Convert
% interfacedata = pwa_linearize(interfacedata);
Matrices = yalmip2mpt(interfacedata);
% Get some MPT options
options = interfacedata.options;
options.mpt.lpsolver = mptOptions.lpsolver;
options.mpt.milpsolver = mptOptions.milpsolver;
options.mpt.verbose = options.verbose;
if options.savedebug
save mptdebug Matrices
end
if options.mp.unbounded
Matrices = removeExplorationConstraints(Matrices);
end
[dummy,un] = unique([Matrices.G Matrices.E Matrices.W],'rows');
Matrices.G = Matrices.G(un,:);
Matrices.E = Matrices.E(un,:);
Matrices.W = Matrices.W(un,:);
if isempty(Matrices.binary_var_index)
showprogress('Calling MPT',options.showprogress);
solvertime = clock;
if options.mp.presolve
[Matrices.lb,Matrices.ub] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);
end
if any(Matrices.lb(end-Matrices.nx+1:end) == Matrices.ub(end-Matrices.nx+1:end))
model = [];
else
model = mpt_solvenode(Matrices,Matrices.lb,Matrices.ub,Matrices,[],options);
end
solvertime = etime(clock,solvertime);
else
% Pre-solve required on binary problems
options.mp.presolve = 1;
solvertime = tic;
% if Matrices.qp & options.mp.algorithm == 3
% options.mp.algorithm = 1;
% end
switch options.mp.algorithm
case 1
showprogress('Calling MPT via enumeration',options.showprogress);
model = mpt_enumeration_mpmilp(Matrices,options);
case 2
% Still experimental and just for fun. Not working!
showprogress('Calling MPT via parametric B&B',options.showprogress);
model = mpt_parbb(Matrices,options);
case 3
showprogress('Calling MPT via delayed enumeration',options.showprogress);
%Matrices = initialize_binary_equalities(Matrices)
[Matrices.SOS,Matrices.SOSVariables] = mpt_detect_sos(Matrices);
[Matrices.lb,Matrices.ub] = mpt_detect_and_improve_bounds(Matrices,Matrices.lb,Matrices.ub,Matrices.binary_var_index,options);
model = mpt_de_mpmilp(Matrices,options,[]);
otherwise
end
solvertime = toc(solvertime);
end
if isempty(model)
model = {model};
end
if options.verbose
if ~isempty(model{1})
if length(model) == 1
disp(['-> Generated 1 partition.'])
else
disp(['-> Generated ' num2str(length(model)) ' partitions.'])
end
end
end
problem = 0;
infostr = yalmiperror(problem,'MPT');
% Save all data sent to solver?
if options.savesolverinput
solverinput.Matrices = Matrices;
solverinput.options = [];
else
solverinput = [];
end
% Save all data from the solver?
% This always done
if options.savesolveroutput
solveroutput.model = model;
solveroutput.U = interfacedata.used_variables(Matrices.free_var);%(Matrices.free_var <= length( interfacedata.used_variables)));
solveroutput.x = interfacedata.used_variables(Matrices.param_var);
else
solveroutput = [];
end
% Standard interface
Primal = nan*ones(length(interfacedata.c),1);
Dual = [];
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function Matrices = initialize_binary_equalities(Matrices)
binary_var_index = Matrices.binary_var_index;
notbinary_var_index = setdiff(1:Matrices.nu,binary_var_index);
% Detect and extract pure binary equalities. Used for simple pruning
nbin = length(binary_var_index);
only_binary = ~any(Matrices.Aeq(:,notbinary_var_index),2);
Matrices.Aeq_bin = Matrices.Aeq(find(only_binary),binary_var_index);
Matrices.beq_bin = Matrices.beq(find(only_binary),:);
function Matrices = removeExplorationConstraints(Matrices);
candidates = find((~any(Matrices.G,2)) & (sum(Matrices.E | Matrices.E,2) == 1));
if ~isempty(candidates)
Matrices.bndA = -Matrices.E(candidates,:);
Matrices.bndb = Matrices.W(candidates,:);
Matrices.G(candidates,:) = [];
Matrices.E(candidates,:) = [];
Matrices.W(candidates,:) = [];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callpenbmim.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callpenbmim.m
| 8,291 |
utf_8
|
55f1ccca944ad4f85054c6f277ec359f
|
function output = callpenbmi(interfacedata);
if any(interfacedata.variabletype > 2)
% Polynomial problem, YALMIP has to bilienarize
interfacedata.high_monom_model=[];
output = callpenbmi_with_bilinearization(interfacedata);
else
% Old standard code
output = callpenbmi_without_bilinearization(interfacedata);
end
function output = callpenbmi_without_bilinearization(interfacedata);
% Retrieve needed data
clear penbmim
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
Q = interfacedata.Q;
K = interfacedata.K;
x0 = interfacedata.x0;
monomtable = interfacedata.monomtable;
ub = interfacedata.ub;
lb = interfacedata.lb;
% Linear before bilinearize
temp = sum(monomtable,2)>1;
tempnonlinearindicies = find(temp);
templinearindicies = find(~temp);
% Any stupid constant>0 constraints
% FIX : Recover duals afterwards
% Better fix : Do this outside
zrow = [];
if K.l >0
zrow = find(any(F_struc(1:K.l+K.f,:),2)==0);
if ~isempty(zrow)
K.l = K.l - nnz(zrow>K.f);
K.f = K.f - nnz(zrow<=K.f);
F_struc(zrow,:) = [];
end
end
% Bounded variables converted to constraints
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
% This one only occurs if called from bmibnb
if K.f>0
F_struc = [-F_struc(1:K.f,:);F_struc];
F_struc(1:K.f,1) = F_struc(1:K.f,1)+sqrt(eps);
K.l = K.l + 2*K.f;
K.f = 0;
end
if isempty(monomtable)
monomtable = eye(length(c));
end
temp = sum(monomtable,2)>1;
nonlinearindicies = find(temp);
linearindicies = find(~temp);
c0 = c;
c = c(linearindicies);
Q = Q(linearindicies,linearindicies);
nonlinear_scalars = [];
% Any non-linear scalar inequalities?
% Move these to the BMI part
if K.l>0
nonlinear_scalars = find(any(full(F_struc(1:K.l,[nonlinearindicies(:)'+1])),2));
if ~isempty(nonlinear_scalars)
Kold = K;
% SETDIFF DONE FASTER
aa = 1:K.l;
bb = nonlinear_scalars;
tf = ~(ismembc(aa,bb));
cc = aa(tf);
cc = unique(cc);
linear_scalars = cc;
% linear_scalars = setdiff1(1:K.l,nonlinear_scalars);
F_struc = [F_struc(linear_scalars,:);F_struc(nonlinear_scalars,:);F_struc(K.l+1:end,:)];
K.l = K.l-length(nonlinear_scalars);
if (length(K.s)==1) & (K.s==0)
K.s = [repmat(1,1,length(nonlinear_scalars))];
K.rank = repmat(1,1,length(nonlinear_scalars));
else
K.s = [repmat(1,1,length(nonlinear_scalars)) K.s];
K.rank = [repmat(1,1,length(nonlinear_scalars)) K.rank];
end
end
end
if ~isempty(F_struc)
pen = sedumi2pen(F_struc(:,[1 linearindicies(:)'+1]),K,c,x0);
else
pen = sedumi2pen([],K,c,x0);
end
if ~isempty(nonlinearindicies)
bmi = sedumi2pen(F_struc(:,[nonlinearindicies(:)'+1]),K,[],[]);
pen.ki_dim = bmi.ai_dim;
% Nonlinear index
pen.ki_dim = bmi.ai_dim;
pen.ki_row = bmi.ai_row;
pen.ki_col = bmi.ai_col;
pen.ki_nzs = bmi.ai_nzs;
pen.ki_val = bmi.ai_val;
if 0
for i = 1:length(bmi.ai_idx)
nl = nonlinearindicies(1+bmi.ai_idx(i));
v = find(monomtable(nl,:));
if length(v)==1
v(2)=v(1);
end
pen.ki_idx(i)=find(linearindicies == v(1));
pen.kj_idx(i)=find(linearindicies == v(2));
end
else
top = 1;
[ii,jj,kk] = find(monomtable(nonlinearindicies(1+bmi.ai_idx),:)');
pen.ki_idx = zeros(1,length(bmi.ai_idx));
pen.kj_idx = zeros(1,length(bmi.ai_idx));
for i = 1:length(bmi.ai_idx)
if kk(top)==2
v(1) = ii(top);
v(2) = ii(top);
top = top + 1;
else
v(1) = ii(top);
v(2) = ii(top+1);
top = top + 2;
end
% FIX : precompute this map
pen.ki_idx(i)=find(linearindicies == v(1));
pen.kj_idx(i)=find(linearindicies == v(2));
end
end
else
pen.ki_dim = 0*pen.ai_dim;
pen.ki_row = 0;
pen.ki_col = 0;
pen.ki_nzs = 0;
pen.ki_idx = 0;
pen.kj_idx = 0;
pen.kj_val = 0;
end
if nnz(Q)>0
[row,col,vals] = find(triu(Q));
pen.q_nzs = length(row);
pen.q_val = vals';
pen.q_col = col'-1;
pen.q_row = row'-1;
else
pen.q_nzs = 0;
pen.q_val = 0;
pen.q_col = 0;
pen.q_row = 0;
end
ops = struct2cell(options.penbmi);ops = [ops{1:end}];
pen.ioptions = ops(1:12);
pen.foptions = ops(13:end);
pen.ioptions(4) = max(0,min(3,options.verbose+1));
if pen.ioptions(4)==1
pen.ioptions(4)=0;
end
% ****************************************
% UNCOMMENT THIS FOR PENBMI version 1
% ****************************************
%pen.ioptions = pen.ioptions(1:8);
%pen.foptions = pen.foptions(1:8);
if ~isempty(x0)
pen.x0(isnan(pen.x0)) = 0;
pen.x0 = x0(linearindicies);
pen.x0 = pen.x0(:)';
end
if options.savedebug
save penbmimdebug pen
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
[f,xout,u,iflag,niter,feas] = penbmim(pen);
solvertime = toc(solvertime);
if options.saveduals & isempty(zrow)
% Get dual variable
% First, get the nonlinear scalars treated as BMIs
if ~isempty(nonlinear_scalars)
n_orig_scalars = length(nonlinear_scalars)+K.l;
linear_scalars = setdiff(1:n_orig_scalars,nonlinear_scalars);
u_nonlinear=u(K.l+1:K.l+length(nonlinear_scalars));
u(K.l+1:K.l+length(nonlinear_scalars))=[];
u_linear = u(1:K.l);
u_scalar = zeros(1,n_orig_scalars);
u_scalar(linear_scalars)=u_linear;
u_scalar(nonlinear_scalars)=u_nonlinear;
u = [u_scalar u(1+K.l:end)];
K = Kold;
end
u = u(:);
D_struc = u(1:1:K.l);
if length(K.s)>0
if K.s(1)>0
pos = K.l+1;
for i = 1:length(K.s)
temp = zeros(K.s(i),K.s(i));
vecZ = u(pos:pos+0.5*K.s(i)*(K.s(i)+1)-1);
top = 1;
for j = 1:K.s(i)
len = K.s(i)-j+1;
temp(j:end,j)=vecZ(top:top+len-1);top=top+len;
end
temp = (temp+temp');j = find(speye(K.s(i)));temp(j)=temp(j)/2;
D_struc = [D_struc;temp(:)];
pos = pos + (K.s(i)+1)*K.s(i)/2;
end
end
end
else
D_struc = [];
end
%Recover solution
if isempty(nonlinearindicies)
x = xout(:);
else
x = zeros(length(interfacedata.c),1);
for i = 1:length(templinearindicies)
x(templinearindicies(i)) = xout(i);
end
end
problem = 0;
switch iflag
case 0
problem = 0; % OK
case {1,3}
problem = 4;
case 2
problem = 1; % INFEASIBLE
case 4
problem = 3; % Numerics
case 5
problem = 7;
case {6,7}
problem = 11;
otherwise
problem = -1;
end
infostr = yalmiperror(problem,interfacedata.solver.tag);
if options.savesolveroutput
solveroutput.f = f;
solveroutput.xout = xout;
solveroutput.u = u;
solveroutput.iflag = iflag;
solveroutput.niter = niter;
solveroutput.feas = feas;
else
solveroutput = [];
end
if options.savesolverinput
solverinput.pen = pen;
else
solverinput = [];
end
% Standard interface
output = createOutputStructure(x(:),D_struc,[],problem,infostr,solverinput,solveroutput,solvertime);
function output = callpenbmi_with_bilinearization(interfacedata);
% Bilinearize
[p,changed] = convert_polynomial_to_quadratic(interfacedata);
% Convert bilinearizing equalities to inequalities
if p.K.f>0
p.F_struc = [-p.F_struc(1:p.K.f,:);p.F_struc];
p.F_struc(1:p.K.f,1) = p.F_struc(1:p.K.f,1)+sqrt(eps);
p.K.l = p.K.l + 2*p.K.f;
p.K.f = 0;
end
% Solve bilinearized problem
output = callpenbmi_without_bilinearization(p);
% Get our original variables & duals
output.Primal = output.Primal(1:length(interfacedata.c));
if ~isempty(output.Dual)
n_equ = p.K.f - interfacedata.K.f;
% First 2*n_eq are the duals for the new inequalities
output.Dual = output.Dual(1+2*n_equ:end);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
yalmip2xpress.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/yalmip2xpress.m
| 3,380 |
utf_8
|
939c179fa34ef53a916b36c325cff8ab
|
function model = yalmip2xpress(interfacedata)
options = interfacedata.options;
F_struc = interfacedata.F_struc;
H = interfacedata.Q;
c = interfacedata.c;
K = interfacedata.K;
x0 = interfacedata.x0;
integer_variables = interfacedata.integer_variables;
binary_variables = interfacedata.binary_variables;
semicont_variables = interfacedata.semicont_variables;
ub = interfacedata.ub;
lb = interfacedata.lb;
showprogress('Calling Xpress',options.showprogress);
if ~isempty(semicont_variables)
% Bounds must be placed in LB/UB
[lb,ub,cand_rows_eq,cand_rows_lp] = findulb(F_struc,K,lb,ub);
F_struc(K.f+cand_rows_lp,:)=[];
F_struc(cand_rows_eq,:)=[];
K.l = K.l-length(cand_rows_lp);
K.f = K.f-length(cand_rows_eq);
redundant = find(lb<=0 & ub>=0);
semicont_variables = setdiff(semicont_variables,redundant);
end
% Notation used
f = c;
A = -F_struc(:,2:end);
b = F_struc(:,1);
rtype = repmat('L',size(F_struc,1),1);
rtype(1:K.f) = 'E';
% XPRESS assumes semi-continuous variables only can take positive values so
% we negate semi-continuous violating this
NegativeSemiVar = [];
if ~isempty(semicont_variables)
NegativeSemiVar = find(lb(semicont_variables) < 0);
if ~isempty(NegativeSemiVar)
temp = ub(semicont_variables(NegativeSemiVar));
ub(semicont_variables(NegativeSemiVar)) = -lb(semicont_variables(NegativeSemiVar));
lb(semicont_variables(NegativeSemiVar)) = -temp;
if ~isempty(A)
A(:,semicont_variables(NegativeSemiVar)) = -A(:,semicont_variables(NegativeSemiVar));
end
f(semicont_variables(NegativeSemiVar)) = -f(semicont_variables(NegativeSemiVar));
H(:,semicont_variables(NegativeSemiVar)) = -H(:,semicont_variables(NegativeSemiVar));
H(semicont_variables(NegativeSemiVar),:) = -H(semicont_variables(NegativeSemiVar),:);
end
end
clim = zeros(length(f),1);
clim(semicont_variables) = lb(semicont_variables);
ctype = char(ones(length(f),1)*67);
ctype(setdiff(integer_variables,semicont_variables)) = 'I';
ctype(binary_variables) = 'B';
ctype(setdiff(semicont_variables,integer_variables)) = 'S';
ctype(intersect(semicont_variables,integer_variables)) = 'R';
options.xpress = setupOptions(options);
if options.verbose == 0
options.xpress.OUTPUTLOG = 0;
options.xpress.MIPLOG = 0;
options.xpress.LPLOG = 0;
end
sos = [];
if ~isempty(K.sos.type)
for i = 1:length(K.sos.weight)
sos(i).type = K.sos.type(i);
sos(i).ind = K.sos.variables{i}-1;
sos(i).wt = (1:length(K.sos.weight{i}))';
end
end
if size(A,1)==0
A = zeros(1,length(f));
b = 1;
end
model.H = 2*H;
model.f = f;
model.A = A;
model.b = b;
model.lb = lb;
model.ub = ub;
model.ctype = ctype;
model.rtype = rtype;
model.clim = clim;
model.sos = sos;
model.ops = options.xpress;
model.extra.semicont_variables = semicont_variables;
model.extra.integer_variables = integer_variables;
model.extra.binary_variables = binary_variables;
model.extra.NegatedSemiVar = NegativeSemiVar;
function ops = setupOptions(options);
ops = options;
if options.verbose == 0
ops.OUTPUTLOG = 0;
ops.MIPLOG = 0;
ops.LPLOG = 0;
end
% cNames = fieldnames(options.xpress);
% for i = 1:length(cNames)
% s = getfield(options.xpress,cNames{i});
% if ~isempty(s)
% ops = setfield(ops,cNames{i},s);
% end
% end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
calllogdetppa.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/calllogdetppa.m
| 4,738 |
utf_8
|
5e811439e286c2bc2cfa708872c26cb3
|
function output = calllogdetppa(interfacedata)
% Retrieve needed data
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
K = interfacedata.K;
x0 = interfacedata.x0;
ub = interfacedata.ub;
lb = interfacedata.lb;
% Bounded variables converted to constraints
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
% SDPNAL does not support multiple blocks
options.sdpt3.smallblkdim = 0;
% Convert from internal (sedumi-like) format
[blk,A,C,b,oldKs]=sedumi2sdpt3(F_struc(:,1),F_struc(:,2:end),c,K,options.sdpt3.smallblkdim);
% Setup the logarithmic barrier cost. We exploit the fact that we know that
% the only logaritmic cost is in the last SDP constraint
if abs(K.m) > 0
for i = 1:size(blk,1)
if isequal(blk{i,1},'l')
options.sdpt3.parbarrier{i,1} = zeros(1,blk{i,2});
else
options.sdpt3.parbarrier{i,1} = 0*blk{i,2};
end
end
n_sdp_logs = nnz(K.m > 1);
n_lp_logs = nnz(K.m == 1);
if n_lp_logs>0
lp_count = n_lp_logs;
end
if n_sdp_logs>0
sdp_count = n_sdp_logs;
end
for i = 1:length(K.m)
if K.m(i) == 1
% We placed it in the linear cone
options.sdpt3.parbarrier{1,1}(end-lp_count+1) = -K.maxdetgain(i);
lp_count = lp_count-1;
elseif K.m(i) > 1
% We placed it in the SDP cone
options.sdpt3.parbarrier{end-sdp_count+1,1} = -K.maxdetgain(i);
sdp_count = sdp_count-1;
end
end
%options.saveduals = 0;
mu0 = [options.sdpt3.parbarrier{:}];
else
mu0 = zeros(K.l+length(find(K.s)),1);
end
%options.logdetppa.mu0 = [options.sdpt3.parbarrier{:}];
if options.savedebug
ops = options.logdetppa;
save logdetppadebug blk A C b ops x0 -v6
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
if options.verbose==0 % SDPT3 does not run silent despite printyes=0!
evalc('[obj,X,y,Z,info,runhist] = logdetPPA(blk,A,C,b,mu0,options.logdetppa);');
else
[obj,X,y,Z,info,runhist] = logdetPPA(blk,A,C,b,mu0,options.logdetppa);
end
solvertime = toc(solvertime);
% Create YALMIP dual variable and slack
Dual = [];
Slack = [];
top = 1;
if K.f>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top+1;
end
if K.l>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top + 1;
end
if K.q(1)>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top + 1;
end
if K.s(1)>0
% Messy format in SDPT3 to block and sort small SDPs
u = blk(:,1);
u = find([u{:}]=='s');
s = 1;
for top = u
ns = blk(top,2);ns = ns{1};
k = 1;
for i = 1:length(ns)
Xi{oldKs(s)} = X{top}(k:k+ns(i)-1,k:k+ns(i)-1);
Zi{oldKs(s)} = Z{top}(k:k+ns(i)-1,k:k+ns(i)-1);
s = s + 1;
k = k+ns(i);
end
end
for i = 1:length(Xi)
Dual = [Dual;Xi{i}(:)];
Slack = [Slack;Zi{i}(:)];
end
end
if any(K.m > 0)
% Dual = [];
end
Primal = -y; % Primal variable in YALMIP
problem = -7;
%
% % Convert error code
% switch info.termcode
% case -1
% problem = 4;
% case 0
% problem = 0;
% case 1
% problem = 5;
% case 2
% problem = 3;
% otherwise
% problem = 11;
% end
infostr = yalmiperror(problem,interfacedata.solver.tag);
if options.savesolveroutput
solveroutput.obj = obj;
solveroutput.X = X;
solveroutput.y = y;
solveroutput.Z = Z;
solveroutput.info = info;
solveroutput.runhist = runhist;
else
solveroutput = [];
end
if options.savesolverinput
solverinput.blk = blk;
solverinput.A = A;
solverinput.C = C;
solverinput.b = b;
solverinput.X0 = [];
solverinput.y0 = x0;
solverinput.Z0 = [];
solverinput.options = options.sdpt3;
else
solverinput = [];
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function [F_struc,K] = deblock(F_struc,K);
X = any(F_struc(end-K.s(end)^2+1:end,:),2);
X = reshape(X,K.s(end),K.s(end));
[v,dummy,r,dummy2]=dmperm(X);
blks = diff(r);
lint = F_struc(1:end-K.s(end)^2,:);
logt = F_struc(end-K.s(end)^2+1:end,:);
newlogt = [];
for i = 1:size(logt,2)
temp = reshape(logt(:,i),K.s(end),K.s(end));
temp = temp(v,v);
newlogt = [newlogt temp(:)];
end
logt = newlogt;
pattern = [];
for i = 1:length(blks)
pattern = blkdiag(pattern,ones(blks(i)));
end
F_struc = [lint;logt(find(pattern),:)];
K.s(end) = [];
K.s = [K.s blks];
K.m = blks;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callbaron.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callbaron.m
| 5,132 |
utf_8
|
f37bb6f75fdde9f4e8b566d0e92d6c76
|
function output = callbaron(model)
% This sets up everything and more. Can be simplified significantly since
% baron handles its own computational tree etc
model = yalmip2nonlinearsolver(model);
% [Anonlinear*f(x) <= b;Anonlinear*f(x) == b]
cu = full([model.bnonlinineq;model.bnonlineq]);
cl = full([repmat(-inf,length(model.bnonlinineq),1);model.bnonlineq]);
Anonlinear = [ model.Anonlinineq; model.Anonlineq];
% Create string representing objective
obj = createmodelstring(model.c,model);
obj = strrep(obj,'sqrtm_internal','sqrt');
if nnz(model.Q)>0
obj = [obj '+' createQstring(model.Q,model)];
end
if model.f > 0
obj = [obj '+' num2str(model.f)];
end
if length(obj)>0
obj = strrep(obj,'+-','-');
obj = ['@(x) ' obj];
obj = eval(obj);
else
obj = @(x)0;
end
% Create string representing nonlinear consdbqtraints
if length(cu)>0
con = '[';
remove = [];
for i = 1:length(cu)
if isinf(cl(i)) & isinf(cu(i))
remove = [remove;i];
else
con = [con createmodelstring(Anonlinear(i,:),model) ';'];
end
end
cl(remove) = [];
cu(remove) = [];
con = [con ']'];
con = strrep(con,'sqrtm_internal','sqrt');
con = ['@(x) ' con];
con = eval(con);
else
cu = [];
cl = [];
con = [];
end
% Linear constraints
ru = full([model.b;model.beq]);
rl = full([repmat(-inf,length(model.b),1);model.beq]);
A = [model.A; model.Aeq];
if length(ru)>0
remove = find(isinf(rl) & isinf(ru));
A(remove,:)=[];
rl(remove) = [];
ru(remove) = [];
end
lb = model.lb;
ub = model.ub;
xtype = [];
xtype = repmat('C',length(lb),1);
xtype(model.binary_variables) = 'B';
xtype(model.integer_variables) = 'I';
x0 = model.x0;
opts = model.options.baron;
opts.prlevel = model.options.verbose;
if model.options.savedebug
save barondebug obj con A ru rl cl cu lb ub x0 opts
end
solvertime = tic;
[x,fval,exitflag,info,allsol] = baron(obj,A,rl,ru,lb,ub,con,cl,cu,xtype,x0,opts);
solvertime = toc(solvertime);
% Check, currently not exhaustive...
switch exitflag
case 1
problem = 0;
case 2
problem = 1;
case 3
problem = 2;
case {4,5}
problem = 11;
otherwise
problem = 9;
end
% Save all data sent to solver?
if model.options.savesolverinput
solverinput.obj = obj;
solverinput.A = A;
solverinput.rl = rl;
solverinput.ru = ru;
solverinput.lb = lb;
solverinput.ub = ub;
solverinput.con = con;
solverinput.cl = cl;
solverinput.cu = cu;
solverinput.xtype = xtype;
solverinput.opts = opts;
else
solverinput = [];
end
% Save all data from the solver?
if model.options.savesolveroutput
solveroutput.x = x;
solveroutput.fval = fval;
solveroutput.exitflag = exitflag;
solveroutput.info=info;
solveroutput.allsol=allsol;
else
solveroutput = [];
end
if ~isempty(x)
x = RecoverNonlinearSolverSolution(model,x);
end
% Standard interface
output = createoutput(x,[],[],problem,'BARON',solverinput,solveroutput,solvertime);
function z = createOneterm(i,model)
[evalPos,pos] = ismember(i,model.evalVariables);
if pos
% This is a nonlinear operator
map = model.evalMap{pos};
% We might hqave vectorized things to compute several expressions at the same time
j = find(map.computes == i);
j = map.variableIndex(j);
% we have f(x(j)), but have to map back to linear indicies
jl = find(model.linearindicies == j);
if isempty(jl)
z = [map.fcn '(' createmonomstring(model.monomtable(j,:),model) ')'];
else
z = [map.fcn '(x(' num2str(jl) '))'];
end
else
i = find(model.linearindicies == i);
z = ['x(' num2str(i) ')'];
end
function monomstring = createmonomstring(v,model)
monomstring = '';
for i = find(v)
z = createOneterm(i,model);
if v(i)==1
monomstring = [monomstring z '*'];
else
monomstring = [monomstring z '^' num2str(v(i),12) '*'];
end
end
monomstring = monomstring(1:end-1);
function string = createmodelstring(row,model)
string = '';
index = find(row);
for i = index(:)'
monomstring = createmonomstring(model.monomtable(i,:),model);
string = [string num2str(row(i),12) '*' monomstring '+'];
end
string = string(1:end-1);
string = strrep(string,'+-','-');
string = strrep(string,')-1*',')-');
string = strrep(string,')+1*',')+');
function string = createQstring(Q,model)
% Special code for the quadratic term
string = '';
[ii,jj,c]= find(triu(Q));
for i = 1:length(ii)
if ii(i)==jj(i)
% Quadratic term
monomstring = createmonomstring(sparse(1,ii(i),1,1,size(Q,1)),model);
string = [string num2str(c(i),12) '*' monomstring '^2' '+'];
else
% Bilinear term
monomstring1 = createmonomstring(sparse(1,ii(i),1,1,size(Q,1)),model);
monomstring2 = createmonomstring(sparse(1,jj(i),1,1,size(Q,1)),model);
string = [string num2str(c(i),12) '*2*' monomstring1 '*' monomstring2 '+'];
end
end
string = string(1:end-1);
string = strrep(string,'+-','-');
string = strrep(string,'-1*','-');
string = strrep(string,'+1*','+');
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
mpcvx.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/mpcvx.m
| 11,816 |
utf_8
|
9c49d6f2332bc7a0b4d072b435a732a1
|
function output = mpcvx(p)
%MPCVX Approximate multi-parametric programming
%
% MPCVX is never called by the user directly, but is called by
% YALMIP from SOLVESDP, by choosing the solver tag 'mpcvx' in sdpsettings
%
% The behaviour of MPCVX can be altered using the fields
% in the field 'mpcvx' in SDPSETTINGS
%
% Implementation of
% A. Bemporad and C. Filippi,
% An Algorithm for Approximate Multiparametric Convex Programming
% Computational Optimization and Applications Volume 35, Number 1 /
% September, 2006
% *************************************************************************
% INITIALIZE DIAGNOSTICS IN YALMIP
% *************************************************************************
mpsolvertime = clock;
showprogress('mpcvx started',p.options.showprogress);
% *************************************************************************
% Display-logics
% *************************************************************************
switch max(min(p.options.verbose,3),0)
case 0
p.options.bmibnb.verbose = 0;
case 1
p.options.bmibnb.verbose = 1;
p.options.verbose = 0;
case 2
p.options.bmibnb.verbose = 2;
p.options.verbose = 0;
case 3
p.options.bmibnb.verbose = 2;
p.options.verbose = 1;
otherwise
p.options.bmibnb.verbose = 0;
p.options.verbose = 0;
end
% *************************************************************************
% No reason to save
% *************************************************************************
p.options.saveduals = 0;
% *************************************************************************
% The solver for approximation bounds
% *************************************************************************
solver = eval(['@' p.solver.lower.call]);
% *************************************************************************
% Generate an exploration set by finding an inner approximation of feasible
% parametric space
% *************************************************************************
[THETA,problem] = ray_shoot(p,solver);
% *************************************************************************
% Calculate optimal solution (x) in each initial vertex of exploration set
% *************************************************************************
X = [];
OBJ = [];
for i = 1:size(THETA,2)
[x_i,obj_i] = solve_node(p,solver,THETA(:,i));
X = [X x_i];
OBJ = [OBJ obj_i];
end
% *************************************************************************
% Partition initial set to simplicies
% *************************************************************************
node_keeper;
node_keeper(THETA,X,OBJ);
T = delaunayn(THETA',{'Qz','Qt'});
if p.options.mpcvx.plot
figure
hold on
plot(polytope(THETA'));
end
% *************************************************************************
% Run approximate algorithm recursively on all simplcies
% *************************************************************************
optimal_simplicies = [];
for i = 1:size(T,1)
optimal_simplicies = [optimal_simplicies mp_simplex(p,solver,T(i,:)')];
end
mpsolvertime = etime(clock,mpsolvertime);
% *************************************************************************
% Create output compatible with MPT
% *************************************************************************
Pn = polytope;
j = 1;
for i = 1:size(optimal_simplicies,2)
[theta,x,obj] = node_keeper(optimal_simplicies(:,i));
m = size(theta,1);
Minv = inv([ones(1,m+1);theta]);
Vbar = obj'*Minv;
Pn = [Pn polytope(theta')];
Gi{j} = x(find(~ismember(1:length(p.c),p.parametric_variables)),:)*Minv(:,1);
Fi{j} = x(find(~ismember(1:length(p.c),p.parametric_variables)),:)*Minv(:,2:end);
Bi{i} = Vbar(2:end);
Ci{i} = Vbar(1);
j = j + 1;
end
% Prepare for generating costs
n = length(p.c) - length(p.parametric_variables);
m = length(p.parametric_variables);
Matrices = yalmip2mpt(p);
Matrices.getback.S1 = eye(n);
Matrices.getback.S2 = zeros(n,m);
Matrices.getback.S3 = zeros(n,1);
[Fi,Gi,details] = mpt_project_back_equality(Matrices,Fi,Gi,[],Matrices);
[Fi,Gi] = mpt_select_rows(Fi,Gi,Matrices.requested_variables);
[Fi,Gi] = mpt_clean_optmizer(Fi,Gi);
details.Ai = [];
details.Bi = Bi;
details.Ci = Ci;
output.problem = problem;
output.Primal = nan*ones(length(p.c),1);
output.Dual = [];
output.Slack = [];
output.infostr = yalmiperror(output.problem,'MPCVX');
output.solverinput = 0;
output.solveroutput.model = mpt_appendmodel([],polytope(THETA'),Pn,Fi,Gi,details);
output.solveroutput.U = p.used_variables(Matrices.free_var);
output.solveroutput.x = p.used_variables(Matrices.param_var);
output.solvertime = mpsolvertime;
function simplex_solution = mp_simplex(p,solver,theta_indicies)
% Get the vertices, the optimal solution in the vertices and the optimal
% cost in the vertices
[theta,x,obj] = node_keeper(theta_indicies);
% Parametric dimension
m = size(theta,1);
% Define the polytope defined by the vertices, and add this polytope as a
% constraint to the YALMIP numerical model
Minv = inv([ones(1,m+1);theta]);
M1 = Minv(:,1);
M2 = zeros(size(M1,1),length(p.c));
M2(:,p.parametric_variables) = Minv(:,2:end);
pbound = p;
pbound.F_struc = [p.F_struc(1:p.K.f,:);M1 M2;p.F_struc(p.K.f + 1:end,:)];
pbound.K.l = pbound.K.l + size(M1,1);
% Save original linear cost
c = pbound.c;
% Linear approximation of optimal cost (which is an upper bound)
Vbar = obj'*Minv;
c2 = zeros(length(pbound.c),1);
c2(pbound.parametric_variables) = -Vbar(2:end);
% This should be the difference between bound and true optima
pbound.c = pbound.c + c2;
pbound.f = pbound.f - Vbar(1);
% Find minimum (we have negated error so this is the maximum, i.e. the
% point where the linear approximation of the optimal cost is worst)
output = feval(solver,pbound);
if p.options.mpcvx.plot
plot(polytope(theta'),struct('color',rand(3,1)))
end
% Dig deeper?
upper = Vbar*[1;output.Primal(pbound.parametric_variables)];
lower = p.c'*output.Primal+output.Primal'*p.Q*output.Primal + p.f;
%eps_CP_S = -(pbound.c'*output.Primal+output.Primal'*pbound.Q*output.Primal + pbound.f);
eps_CP_S_abs = upper - lower;
eps_CP_S_rel = (upper - lower)/(1 + abs(upper) + abs(lower));
if eps_CP_S_abs > p.options.mpcvx.absgaptol & eps_CP_S_rel > p.options.mpcvx.relgaptol
% Put back original cost to the model
pbound.c = p.c;
pbound.f = p.f;
% Worst-case approximation point
thetac = output.Primal(pbound.parametric_variables);
% Optimizer in this point
[x_i,obj_i] = solve_node(pbound,solver,thetac);
% Add to list of vertices
new_index = node_keeper(thetac(:),x_i(:),obj_i);
% Partition current simplex and solve recursively in each new simplex
% THe simplex is split such that the worst/case point is a vertex in
% every new simplex
simplex_solution = [];
test = [];
% [xc,R] = facetcircle(polytope(theta'),1:3);
if 0%min(svd([ones(1,size(theta,2));theta])) < 0.2
% Simplicies are getting too elongated. Add a random cut
P1 = polytope(theta');
% xc = get(P1,'xCheb');
% xc = (0*xc + (1/3)*sum(theta,2))/1;
[xd,R] = facetcircle(polytope(theta'),1:3);
[i,j] = max(R);
[H,K] = double(P1);
x = sdpvar(2,1);
Pnew1 = polytope((H*x <= K) + (null(H(j,:))'*(x-xd(:,j)) >= 0));
Pnew2 = polytope((H*x <= K) + (null(H(j,:))'*(x-xd(:,j)) <= 0));
plot(Pnew1);
plot(Pnew2);
theta1 = extreme(Pnew1)';
theta2 = extreme(Pnew2)';
X1 = [];X2 = [];
OBJ1 = [];OBJ2 = [];
indicies1 = []
indicies2 = []
for i = 1:size(theta1,2)
[x_i,obj_i] = solve_node(p,solver,theta1(:,i));
indicies1 = [indicies1 node_keeper(theta1(:,i),x_i(:),obj_i)];
X1 = [X1 x_i];
OBJ1 = [OBJ1 obj_i];
end
for i = 1:size(theta2,2)
[x_i,obj_i] = solve_node(p,solver,theta2(:,i));
indicies2 = [indicies2 node_keeper(theta2(:,i),x_i(:),obj_i)];
X2 = [X2 x_i];
OBJ2 = [OBJ2 obj_i];
end
T1 = (delaunayn(theta1',{'Qz','Qt'}));
T2 = (delaunayn(theta2',{'Qz','Qt'}));
for i = 1:size(T1,1)
index = indicies1(T1);
simplex_solution = [simplex_solution mp_simplex(p,solver,index(i,:))];
end
for i = 1:size(T2,1)
index = indicies2(T2);
simplex_solution = [simplex_solution mp_simplex(p,solver,index(i,:))];
end
else
for i = 1:(size(theta,1)+1)
j = 1:(size(theta,1)+1);
j(i)=[];
theta_test = [theta(:,j) thetac];
if min(svd([ones(1,size(theta_test,2));theta_test]))>1e-4
simplex_solution = [simplex_solution mp_simplex(p,solver,[theta_indicies(j);new_index])];
end
end
end
% if length(simplex_solution) > 0
% [theta,x,obj] = node_keeper(simplex_solution);
% if max(abs(x(p.requested_variables,:)-mean(x(p.requested_variables,:))) < 1e-5)
% simplex_solution = theta_indicies(:);
% end
% else
% simplex_solution = theta_indicies(:);
% end
else
% This simplex constitutes a node, report back
simplex_solution = theta_indicies(:);
end
function varargout = node_keeper(varargin)
persistent savedTHETA
persistent savedX
persistent savedOBJ
switch nargin
case 0 % CLEAR
savedTHETA = [];
savedX = [];
savedOBJ = [];
case 3 % Append
savedTHETA = [savedTHETA varargin{1}];
savedX = [savedX varargin{2}];
savedOBJ = [savedOBJ varargin{3}];
varargout{1} = size(savedTHETA,2);
case 1 % Get data
varargout{1} = savedTHETA(:,varargin{1});
varargout{2} = savedX(:,varargin{1});
varargout{3} = savedOBJ(:,varargin{1});varargout{3} = varargout{3}(:);
otherwise
error('!')
end
function [THETA,problem] = ray_shoot(p,solver)
THETA = [];
p_temp = p;
p_temp.c = p_temp.c*0;
p_temp.Q = 0*p_temp.Q;
n = length(p.parametric_variables);
for i = 1:eval(p.options.mpcvx.rays)
p_temp.c(p.parametric_variables) = randn(length(p.parametric_variables),1);
output = feval(solver,p_temp);
THETA = [THETA output.Primal(p.parametric_variables)];
end
% Select unique and generate center
THETA = unique(fix(THETA'*1e4)/1e4,'rows')';
center = sum(THETA,2)/size(THETA,2);
THETA = [THETA*0.999+repmat(0.001*center,1,size(THETA,2))];
problem = 0;
function [x_i,obj_i] = solve_node(p,solver,theta);
p_temp = p;
p_temp.F_struc(:,1) = p_temp.F_struc(:,1) + p_temp.F_struc(:,1+p.parametric_variables)*theta;
p_temp.F_struc(:,1+p.parametric_variables) = [];
empty_rows = find(~any(p_temp.F_struc(p.K.f+1:p.K.f+p.K.l,2:end),2));
if ~isempty(empty_rows)
if all(p_temp.F_struc(p.K.f+empty_rows,1)>=-1e-7)
p_temp.F_struc(p.K.f+empty_rows,:)=[];
p_temp.K.l = p_temp.K.l - length(empty_rows);
else
feasible = 0;
end
end
x_var = find(~ismember(1:length(p.c),p.parametric_variables));
theta_var = p.parametric_variables;
Q11 = p.Q(x_var,x_var);
Q12 = p.Q(x_var,theta_var);
Q22 = p.Q(theta_var,theta_var);
c1 = p.c(x_var);
c2 = p.c(theta_var);
p_temp.Q = Q11;
p_temp.c = c1+2*Q12*theta;
p_temp.lb(theta_var) = [];
p_temp.ub(theta_var) = [];
%p_temp.c(p.parametric_variables) = [];
%p_temp.Q(:,p.parametric_variables) = [];
%p_temp.Q(p.parametric_variables,:) = [];
output = feval(solver,p_temp);
% Recover complete [x theta]
x_i = zeros(length(p.c),1);
x_i(find(~ismember(1:length(p.c),p.parametric_variables))) = output.Primal;
x_i(p.parametric_variables) = theta;
obj_i = x_i'*p.Q*x_i+p.c'*x_i;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callvsdp.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callvsdp.m
| 4,295 |
utf_8
|
3db429710eaea8f4494a100384c6f9e9
|
function output = callvsdp(interfacedata)
% Retrieve needed data
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
K = interfacedata.K;
x0 = interfacedata.x0;
ub = interfacedata.ub;
lb = interfacedata.lb;
% Bounded variables converted to constraints
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
% Convert from internal (sedumi-like) format to VSDPs sdpt3-like format
[blk,A,C,b]=sedumi2vsdp(F_struc(:,1),F_struc(:,2:end),c,K);
if options.savedebug
ops = options.sdpt3;
save sdpt3debug blk A C b ops -v6
end
% Solver to be used in VSDP
options.vsdp.model = interfacedata;
solvertime = tic;
[objt,Xt,yt,Zt,info] = mysdps_yalmip(blk,A',C,b,options);
% Compute rigorous lower bound (default behaviour)
if options.vsdp.verifiedlower
[fL, Y, dL] = vsdplow_yalmip(blk,A',C,b,Xt,yt,Zt,[],options);
if isnan(Y)
info(1) = 11;
end
%[fL, Y, dL] = vsdplow(blk,A,C,b,Xt,yt,Zt)
else
Y = [];
fL = [];
dL = [];
end
% Compute rigorous lower bound
if options.vsdp.verifiedupper
%[fL, Y, dL] = vsdplow_yalmip(blk,A,C,b,[],[],[],[],options)
% Now compute rigorous lower bound
[fU, X, lb] = vsdpup_yalmip(blk,A',C,b,Xt,yt,Zt,[],options);
%[fU, X, lb] = vsdpup(blk,A,C,b,Xt,yt,Zt);
else
fU = [];
X = [];
lb = [];
end
solvertime = toc(solvertime);
Dual = [];
Slack = [];
top = 1;
if K.f>0
Dual = [Dual;Xt{top}(:)];
Slack = [Slack;Zt{top}(:)];
top = top+1;
end
if K.l>0
Dual = [Dual;[Xt{1:K.l}]'];
Slack = [Slack;[Zt{1:K.l}]'];
top = top + K.l;
end
if K.q(1)>0
Dual = [Dual;Xt{top}(:)];
Slack = [Slack;Zt{top}(:)];
top = top + 1;
end
if K.s(1)>0
for i = 1:length(K.s)
Dual = [Dual;Xt{top+i-1}(:)];
Slack = [Slack;Zt{top+i-1}(:)];
end
end
if ~isempty(Y) & ~isnan(Y)
Primal = Y; % Primal variable in YALMIP
else
Primal = yt; % Primal variable in YALMIP
end
% Convert error code
switch info(1)
case 0
problem = 0; % No problems detected
case {-1,-5}
problem = 5; % Lack of progress
case {-2,-3,-4,-7}
problem = 4; % Numerical problems
case -6
problem = 3; % Maximum iterations exceeded
case -10
problem = 7; % YALMIP sent incorrect input to solver
case 1
problem = 2; % Dual feasibility
case 2
problem = 1; % Primal infeasibility
case 11
problem = 11;
otherwise
problem = -1; % Unknown error
end
infostr = yalmiperror(problem,interfacedata.solver.tag);
% always save output
if options.savesolveroutput
solveroutput.objt = objt;
solveroutput.Xt = Xt;
solveroutput.yt = yt;
solveroutput.Zt = Zt;
solveroutput.fL = fL;
solveroutput.Y = Y;
solveroutput.dL = dL;
solveroutput.fU = fU;
solveroutput.X = X;
solveroutput.lb = lb;
solveroutput.info = info;
else
solveroutput = [];
end
if options.savesolverinput
solverinput.blk = blk;
solverinput.A = A;
solverinput.C = C;
solverinput.b = b;
solverinput.options = options.sdpt3;
else
solverinput = [];
end
% Standard interface
output = createOutputStructure(Primal,Dual,Slack,problem,infostr,solverinput,solveroutput,solvertime);
function [blk,A,C,b]=sedumi2vsdp(Cin,Ain,c,K);
C = {};
A = {};
b = -c;
blk = {};
top = 1;
k = 1;
if K.f > 0
C{k,1} = Cin(top:top+K.f-1);
% A{k} = -Ain(top:top+K.f-1,:);
for j = 1:length(c)
A{j,k} = -Ain(top:top+K.f-1,j);
end
blk{k,1} = 'u';
blk{k,2} = K.f;
top = top + K.f;
k = k + 1;
end
if K.l > 0
K.s = [repmat(1,1,K.l) K.s];
K.s(K.s == 0) = [];
% C{k,1} = Cin(top:top+K.l-1);
% % A{k} = -Ain(top:top+K.l-1,:);
% for j = 1:length(c)
% A{j,k} = -Ain(top:top+K.l-1,j);
% end
% blk{k,1} = 'l';
% blk{k,2} = K.l;
% top = top + K.l;
% k = k + 1;
end
if K.s(1)>0
for i = 1:length(K.s)
C{k,1} = reshape(Cin(top:top+K.s(i)^2-1),K.s(i),K.s(i));
for j = 1:length(c)
A{j,k} = reshape(-Ain(top:top+K.s(i)^2-1,j),K.s(i),K.s(i));
end
blk{k,1} = 's';
blk{k,2} = K.s(i);
k = k + 1;
top = top + K.s(i)^2;
end
end
A = A';
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callsparsecolo.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callsparsecolo.m
| 4,501 |
utf_8
|
376b38f73357ddec826c7ac3db7e6704
|
function output = callsparsecolo(interfacedata)
% Retrieve needed data
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
K = interfacedata.K;
x0 = interfacedata.x0;
ub = interfacedata.ub;
lb = interfacedata.lb;
% Bounded variables converted to constraints
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
A = -F_struc(:,2:end)';
C = F_struc(:,1);
b = -c;
if options.savedebug
ops = options.sparsecolo;
save sparsecolodebug K A C b
end
ops = options.sparsecolo;
ops.SDPsolver = lower(interfacedata.solver.sdpsolver.tag);
ops.SDPAoptions = options.sdpa;
ops.sedumipar = options.sedumi;
ops.sdpt3OPTIONS = options.sdpt3;
ops.sdpt3OPTIONS.printlevel = options.verbose;
ops.printlevel = options.verbose;
if options.verbose==0
ops.SDPAoptions.print = 'no';
else
ops.SDPAoptions.print = 'display';
end
if options.savedebug
save sparsecolodebug K A C b ops
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
if options.verbose==0 % Sparsecolo does not run silent
evalc('[x,y,infoCoLO,cliqueDomain,cliqueRange,LOP] = sparseCoLO(A,b,C,K,[],ops);');
else
[x,y,infoCoLO,cliqueDomain,cliqueRange,LOP] = sparseCoLO(A,b,C,K,[],ops);
end
solvertime = toc(solvertime);
% Create YALMIP dual variable and slack
Dual = x;
Primal = y;
switch lower(interfacedata.solver.sdpsolver.tag)
case 'sdpt3'
switch infoCoLO.SDPsolver.termcode
case 0
problem = 0; % No problems detected
case {-1,-5}
problem = 5; % Lack of progress
case {-2,-3,-4,-7}
problem = 4; % Numerical problems
case -6
problem = 3; % Maximum iterations exceeded
case -10
problem = 7; % YALMIP sent incorrect input to solver
case 1
problem = 2; % Dual feasibility
case 2
problem = 1; % Primal infeasibility
otherwise
problem = -1; % Unknown error
end
case 'sedumi'
problem = sedumicode(infoCoLO.SDPsolver,options);
case 'sdpa'
switch (infoCoLO.SDPsolver.phasevalue)
case 'pdOPT'
problem = 0;
case {'noINFO','pFEAS','dFEAS','pdFEAS'}
problem = 3;
case 'pFEAS_dINF'
problem = 2;
case 'pINF_dFEAS'
problem = 1;
case 'pUNBD'
problem = 2;
case 'dUNBD'
problem = 1;
case 'pdINF'
problem = 12;
otherwise
problem = -1;
end
end
infostr = yalmiperror(problem,interfacedata.solver.tag);
if options.savesolveroutput
solveroutput.obj = obj;
solveroutput.X = X;
solveroutput.y = y;
solveroutput.Z = Z;
solveroutput.info = info;
solveroutput.runhist = runhist;
else
solveroutput = [];
end
if options.savesolverinput
solverinput.blk = blk;
solverinput.A = A;
solverinput.C = C;
solverinput.b = b;
solverinput.X0 = [];
solverinput.y0 = x0;
solverinput.Z0 = [];
solverinput.options = options.sdpt3;
else
solverinput = [];
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function problem = sedumicode(info,options)
temp = info.pinf;
pinf = info.dinf;
dinf = temp;
% Check for reported errors
if (pinf==0) & (dinf==0)
problem = 0; % No problems
end
% We can only report one error, use priorities
if (problem==0) & (pinf==1)
problem = 1; % Primal infeasability
end
if (problem==0) & (dinf==1)
problem = 2; % Dual infeasability
end
if (problem==0) & (info.numerr==1) | (info.numerr==2)
problem = 4; %Numerical problems
end
if (problem==0) & (info.iter >= options.sedumi.maxiter)
% Did we need exactly maxiter iterations to find optimum
if (pinf==0) & (dinf==0) & (info.numerr==0)
problem = 0; % Yes
else
problem = 3; % No, we are not optimal yet
end
end
if (problem==0) & (info.feasratio<0.98)
problem = 4;
end
% Fix for cases not really explained in documentation of sedumi?
if (abs(info.feasratio+1)<0.1) & (pinf==0) & (dinf==0)
problem = 1;
end
if (abs(info.feasratio+1)<0.1) & (pinf==0) & (dinf==0) & (c'*y_s<-1e10)
problem = 2;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
yalmip2mosek.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/yalmip2mosek.m
| 2,991 |
utf_8
|
b793cd2a38c2e96dcf47933b6a79a456
|
function prob = yalmip2mosek(interfacedata);
% Retrieve needed data
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
Q = interfacedata.Q;
K = interfacedata.K;
x0 = interfacedata.x0;
integer_variables = interfacedata.integer_variables;
binary_variables = interfacedata.binary_variables;
extended_variables = interfacedata.extended_variables;
ub = interfacedata.ub;
lb = interfacedata.lb;
mt = interfacedata.monomtable;
% *********************************
% What type of variables do we have
% *********************************
linear_variables = find((sum(abs(mt),2)==1) & (any(mt==1,2)));
nonlinear_variables = setdiff((1:size(mt,1))',linear_variables);
sigmonial_variables = find(any(0>mt,2) | any(mt-fix(mt),2));
if ~isempty(sigmonial_variables) | isequal(interfacedata.solver.version,'GEOMETRIC')
prob = create_mosek_geometric(options,F_struc,c,Q,K,ub,lb,mt,linear_variables,extended_variables);
else
prob = create_mosek_lpqp(options,F_struc,c,Q,K,ub,lb,mt,linear_variables,integer_variables);
end
function prob = create_mosek_lpqp(options,F_struc,c,Q,K,ub,lb,mt,linear_variables,integer_variables);
prob.c = c;
if ~isempty(F_struc)
prob.a = -F_struc(:,2:end);
prob.buc = full(F_struc(:,1));
prob.blc = repmat(-inf,length(prob.buc),1);
else
prob.a = sparse(ones(1,length(c))); % Dummy constraint
prob.buc = inf;
prob.blc = -inf;
end
if isempty(lb)
prob.blx = repmat(-inf,1,length(c));
else
prob.blx = lb;
end
if isempty(ub)
prob.bux = repmat(inf,1,length(c));
else
prob.bux = ub;
end
if K.f>0
prob.blc(1:K.f) = prob.buc(1:K.f);
end
[prob.qosubi,prob.qosubj,prob.qoval] = find(tril(sparse(2*Q)));
if K.q(1)>0
nof_new = sum(K.q);
prob.a = [prob.a [spalloc(K.f,nof_new,0);spalloc(K.l,nof_new,0);speye(nof_new)]];
%prob.a(1+K.f+K.l:end,1:length(c)) = prob.a(1+K.f+K.l:end,1:length(c));
prob.blc(1+K.f+K.l:end) = prob.buc(1+K.f+K.l:end);
prob.buc(1+K.f+K.l:end) = prob.buc(1+K.f+K.l:end);
prob.c = [prob.c;zeros(nof_new,1)];
top = size(F_struc,2)-1;
for i = 1:length(K.q)
prob.cones{i}.type = 'MSK_CT_QUAD';
prob.cones{i}.sub = top+1:top+K.q(i);
prob.blx(top+1:top+K.q(i)) = -inf;
prob.bux(top+1:top+K.q(i)) = inf;
top = top + K.q(i);
end
end
if ~isempty(integer_variables)
prob.ints.sub = integer_variables;
end
prob.param = options.mosek;
function prob = create_mosek_geometric(options,F_struc,c,Q,K,ub,lb,mt,linear_variables,extended_variables);
x = [];
D_struc = [];
res = [];
solvertime = 0;
[prob,problem] = yalmip2geometric(options,F_struc,c,Q,K,ub,lb,mt,linear_variables,extended_variables);
if problem == 0
% Mosek does not support equalities
if ~isempty(prob.G)
prob.A = [prob.A;prob.G;-prob.G];
prob.b = [prob.b;prob.h;1./prob.h];
prob.map = [prob.map;max(prob.map) + (1:2*length(prob.h))'];
end
else
prob = [];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callsdpt34.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callsdpt34.m
| 8,427 |
utf_8
|
b646fbbeaba6c0cdbbbbf847b0314fdd
|
function output = callsdpt34(interfacedata)
% Retrieve needed data
options = interfacedata.options;
F_struc = interfacedata.F_struc;
c = interfacedata.c;
K = interfacedata.K;
x0 = interfacedata.x0;
ub = interfacedata.ub;
lb = interfacedata.lb;
% Bounded variables converted to constraints
if ~isempty(ub)
[F_struc,K] = addbounds(F_struc,K,ub,lb);
end
if any(K.m > 0)
% Messy to keep track of
options.sdpt3.smallblkdim = 0;
end
if ~isempty(interfacedata.lowrankdetails)
options.sdpt3.smallblkdim = 1;
end
if isempty(K.schur_funs)
% Simple...
[blk,A,C,b,oldKs]=sedumi2sdpt3(F_struc(:,1),F_struc(:,2:end),c,K,options.sdpt3.smallblkdim);
else
% A bit messy if we have a Schur compiler (i.e. STRUL)
% SDPT3 reorders SDP constraints in order to put many small ones in a
% common block. Hence, it might happen that it mixes up SDP constraints
% with Schur compilers and those without. At the moment, we take a
% conservative approach. If all SDP constraints have a Schur compiler,
% we allow blocking. If not, we don't. This way our code will work
if ~any(cellfun(@isempty,K.schur_funs))
% All have Schur functions
[blk,A,C,b,oldKs]=sedumi2sdpt3(F_struc(:,1),F_struc(:,2:end),c,K,options.sdpt3.smallblkdim);
else
% Messy case, don't allow blocking for now
options.sdpt3.smallblkdim = 1;
[blk,A,C,b,oldKs]=sedumi2sdpt3(F_struc(:,1),F_struc(:,2:end),c,K,options.sdpt3.smallblkdim);
end
end
options.sdpt3.printyes=double(options.verbose);
options.sdpt3.printlevel=double(options.verbose)*3;
options.sdpt3.expon=options.sdpt3.expon(1);
% Setup the logarithmic barrier cost. We exploit the fact that we know that
% the only logaritmic cost is in the last SDP constraint
if abs(K.m) > 0
lpLogsStart = 1;
for i = 1:size(blk,1)
if isequal(blk{i,1},'l')
options.sdpt3.parbarrier{i,1} = zeros(1,blk{i,2});
elseif isequal(blk{i,1},'u')
lpLogsStart = 2;
options.sdpt3.parbarrier{i,1} = zeros(1,blk{i,2});
else
options.sdpt3.parbarrier{i,1} = 0*blk{i,2};
end
end
n_sdp_logs = nnz(K.m > 1);
n_lp_logs = nnz(K.m == 1);
if n_lp_logs>0
lp_count = n_lp_logs;
end
if n_sdp_logs>0
sdp_count = n_sdp_logs;
end
for i = 1:length(K.m)
if K.m(i) == 1
% We placed it in the linear cone
options.sdpt3.parbarrier{lpLogsStart,1}(end-lp_count+1) = -K.maxdetgain(i);
lp_count = lp_count-1;
elseif K.m(i) > 1
% We placed it in the SDP cone
options.sdpt3.parbarrier{end-sdp_count+1,1} = -K.maxdetgain(i);
sdp_count = sdp_count-1;
end
end
%options.saveduals = 0;
end
% Setup structures for user-defined Schur compilers
if isfield(K,'schur_funs')
top = 1;
if ~isempty(K.schur_funs)
if K.f>0
options.sdpt3.schurfun{top} = '';
options.sdpt3.schurfun_par{top,1} = [];
top = top+1;
end
if K.l > 0
options.sdpt3.schurfun{top} = '';
options.sdpt3.schurfun_par{top,1} = [];
top = top+1;
end
if K.q > 0
options.sdpt3.schurfun{top} = '';
options.sdpt3.schurfun_par{top,1} = [];
top = top+1;
end
if 0
for i = 1:length(K.s)
if ~isempty(K.schur_funs{i})
options.sdpt3.schurfun{top} = 'schurgateway';
S = createSchurFun(options,K,interfacedata,i);
options.sdpt3.schurfun_par{top,1} = S;
V = {S.extra,S.data{:}};
feval(S.fun,[],[],V{:});
else
options.sdpt3.schurfun{top} = '';
options.sdpt3.schurfun_par{top,1} = [];
end
top = top+1;
end
else
iSDP = 1;
while top <= size(blk,1)
for j = 1:length(blk{top,2})
i = oldKs(iSDP);iSDP = iSDP + 1;
if ~isempty(K.schur_funs{i})
Sname = 'schurgateway';
% options.sdpt3.schurfun{top} = 'schurgateway';
S = createSchurFun(options,K,interfacedata,i);
S.j = j;
S.blk = blk(top,2);
options.sdpt3.schurfun_par{top,j} = S;
else
Sname = '';
% options.sdpt3.schurfun{top} = '';
options.sdpt3.schurfun_par{top,1} = [];
end
end
options.sdpt3.schurfun{top} = Sname;
top = top+1;
end
end
end
end
if options.savedebug
ops = options.sdpt3;
save sdpt3debug blk A C b ops x0 -v6
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
[obj,X,y,Z,info,runhist] = sdpt3(blk,A,C,b,options.sdpt3,[],x0,[]);
solvertime = toc(solvertime);
% Create YALMIP dual variable and slack
Dual = [];
Slack = [];
top = 1;
if K.f>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top+1;
end
if K.l>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top + 1;
end
if K.q(1)>0
Dual = [Dual;X{top}(:)];
Slack = [Slack;Z{top}(:)];
top = top + 1;
end
if K.s(1)>0
% Messy format in SDPT3 to block and sort small SDPs
u = blk(:,1);
u = find([u{:}]=='s');
s = 1;
for top = u
ns = blk(top,2);ns = ns{1};
k = 1;
for i = 1:length(ns)
Xi{oldKs(s)} = X{top}(k:k+ns(i)-1,k:k+ns(i)-1);
Zi{oldKs(s)} = Z{top}(k:k+ns(i)-1,k:k+ns(i)-1);
s = s + 1;
k = k+ns(i);
end
end
for i = 1:length(Xi)
Dual = [Dual;Xi{i}(:)];
Slack = [Slack;Zi{i}(:)];
end
end
if any(K.m > 0)
% Dual = [];
end
Primal = -y; % Primal variable in YALMIP
% Convert error code
switch info.termcode
case 0
problem = 0; % No problems detected
case {-1,-5,-9}
problem = 5; % Lack of progress
case {-2,-3,-4,-7}
problem = 4; % Numerical problems
case -6
problem = 3; % Maximum iterations exceeded
case -10
problem = 7; % YALMIP sent incorrect input to solver
case 1
problem = 2; % Dual feasibility
case 2
problem = 1; % Primal infeasibility
otherwise
problem = -1; % Unknown error
end
infostr = yalmiperror(problem,interfacedata.solver.tag);
if options.savesolveroutput
solveroutput.obj = obj;
solveroutput.X = X;
solveroutput.y = y;
solveroutput.Z = Z;
solveroutput.info = info;
solveroutput.runhist = runhist;
else
solveroutput = [];
end
if options.savesolverinput
solverinput.blk = blk;
solverinput.A = A;
solverinput.C = C;
solverinput.b = b;
solverinput.X0 = [];
solverinput.y0 = x0;
solverinput.Z0 = [];
solverinput.options = options.sdpt3;
else
solverinput = [];
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function [F_struc,K] = deblock(F_struc,K);
X = any(F_struc(end-K.s(end)^2+1:end,:),2);
X = reshape(X,K.s(end),K.s(end));
[v,dummy,r,dummy2]=dmperm(X);
blks = diff(r);
lint = F_struc(1:end-K.s(end)^2,:);
logt = F_struc(end-K.s(end)^2+1:end,:);
newlogt = [];
for i = 1:size(logt,2)
temp = reshape(logt(:,i),K.s(end),K.s(end));
temp = temp(v,v);
newlogt = [newlogt temp(:)];
end
logt = newlogt;
pattern = [];
for i = 1:length(blks)
pattern = blkdiag(pattern,ones(blks(i)));
end
F_struc = [lint;logt(find(pattern),:)];
K.s(end) = [];
K.s = [K.s blks];
K.m = blks;
function S = createSchurFun(options,K,interfacedata,i);
S.extra.par = options.sdpt3;
S.data = K.schur_data{i};
[init,loc] = ismember(K.schur_variables{i},interfacedata.used_variables);
S.index = loc;
S.fun = K.schur_funs{i};
S.nvars = length(interfacedata.used_variables);
%options.sdpt3.schurfun_par{top,1} = S;
% V = {S.extra,S.data{:}};
% feval(S.fun,[],[],V{:});
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callquadprog.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callquadprog.m
| 3,531 |
utf_8
|
0dfff0ae70dc7afa1992f59380fc39c4
|
function output = callquadprog(interfacedata)
options = interfacedata.options;
model = yalmip2quadprog(interfacedata);
if options.savedebug
save debugfile model
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
solveroutput = callsolver(model,options);
solvertime = toc(solvertime);
solution = quadprogsol2yalmipsol(solveroutput,model);
% Save all data sent to solver?
if ~options.savesolverinput
model = [];
end
% Save all data from the solver?
if ~options.savesolveroutput
solveroutput = [];
end
% Standard interface
Primal = solution.x(:);
Dual = solution.D_struc;
problem = solution.problem;
infostr = yalmiperror(solution.problem,interfacedata.solver.tag);
if ~options.savesolverinput
solverinput = [];
else
solverinput = model;
end
if ~options.savesolveroutput
solveroutput = [];
else
solveroutput = solveroutput;
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function solveroutput = callsolver(model,options)
x = [];
fmin = [];
flag = [];
output = [];
lambda = [];
if nnz(model.Q) == 0
% BUG in LIN/QUADPROG, computation of lambda crashes in some rare
% cases. To avoid seeing this when we don't want the lambdas anyway, we
% don't ask for it
if options.saveduals
[x,fmin,flag,output,lambda] = linprog(model.c, model.A, model.b, model.Aeq, model.beq, model.lb, model.ub, model.x0,model.ops);
else
lambda = [];
[x,fmin,flag,output] = linprog(model.c, model.A, model.b, model.Aeq, model.beq, model.lb, model.ub, model.x0,model.ops);
end
else
if options.saveduals
[x,fmin,flag,output,lambda] = quadprog(model.Q, model.c, model.A, model.b, model.Aeq, model.beq, model.lb, model.ub, model.x0,model.ops);
else
lambda = [];
[x,fmin,flag,output] = quadprog(model.Q, model.c, model.A, model.b, model.Aeq, model.beq, model.lb, model.ub, model.x0,model.ops);
end
if flag==5
[x,fmin,flag,output,lambda] = quadprog(model.Q, model.c, model.A, model.b, model.Aeq, model.beq, model.lb, model.ub, [],model.ops);
end
end
solveroutput.x = x;
solveroutput.fmin = fmin;
solveroutput.flag = flag;
solveroutput.output = output;
solveroutput.lambda = lambda;
function solution = quadprogsol2yalmipsol(solveroutput,model)
solution.x = solveroutput.x(:);
% Internal format for duals
if ~isempty(solveroutput.lambda)
solution.D_struc = [solveroutput.lambda.eqlin;solveroutput.lambda.ineqlin];
else
solution.D_struc = [];
end
% Check, currently not exhaustive...
problem = 0;
if solveroutput.flag==0
solution.problem = 3;
else
if solveroutput.flag==-3
solution.problem = 2;
elseif solveroutput.flag==-2
solution.problem = 1;
else
if solveroutput.flag>0
solution.problem = 0;
else
if isempty(solveroutput.x)
solution.x = repmat(nan,length(model.f),1);
end
if any((model.A*solveroutput.x-model.b)>sqrt(eps)) | any( abs(model.Aeq*solveroutput.x-model.beq)>sqrt(eps))
solution.problem = 1; % Likely to be infeasible
else
if model.f'*solveroutput.x<-1e10 % Likely unbounded
solution.problem = 2;
else % Probably convergence issues
solution.problem = 5;
end
end
end
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callmosek.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callmosek.m
| 14,228 |
utf_8
|
9584d63092bb2893e014683ac5a5eddb
|
function output = callmosek(model)
% Retrieve needed data
options = model.options;
F_struc = model.F_struc;
c = model.c;
Q = model.Q;
K = model.K;
x0 = model.x0;
integer_variables = model.integer_variables;
binary_variables = model.binary_variables;
extended_variables = model.extended_variables;
ub = model.ub;
lb = model.lb;
mt = model.monomtable;
% *********************************
% What type of variables do we have
% *********************************
model.linear_variables = find((sum(abs(mt),2)==1) & (any(mt==1,2)));
model.nonlinear_variables = setdiff((1:size(mt,1))',model.linear_variables);
model.sigmonial_variables = find(any(0>mt,2) | any(mt-fix(mt),2));
% Some meta-solver thinks we handle binaries
if ~isempty(model.binary_variables)
integer_variables = union(model.integer_variables, model.binary_variables);
if isempty(lb)
lb = repmat(-inf,1,length(model.c));
end
lb(model.binary_variables) = max(lb(model.binary_variables),0);
if isempty(ub)
ub = repmat(inf,1,length(model.c));
end
ub(model.binary_variables) = min(ub(model.binary_variables),1);
model.lb = lb;
model.ub = ub;
end
% Some meta solvers might construct model with empty cones
if any(model.K.s) && any(model.K.s == 0)
model.K.s(model.K.s==0)=[];
end
if any(model.K.q) && any(model.K.q == 0)
model.K.q(model.K.q==0)=[];
end
if ~isempty(model.sigmonial_variables) | isequal(model.solver.version,'GEOMETRIC')
[x,D_struc,problem,r,res,solvertime,prob] = call_mosek_geometric(model);
else
[x,D_struc,problem,r,res,solvertime,prob] = call_mosek_lpqpsocpsdp(model);
end
infostr = yalmiperror(problem,'MOSEK');
% Save all data sent to solver?
if options.savesolverinput
solverinput.prob = prob;
solverinput.param = options.mosek;
else
solverinput = [];
end
% Save all data from the solver?
if options.savesolveroutput
solveroutput.r = r;
solveroutput.res = res;
else
solveroutput = [];
end
% Standard interface
output = createOutputStructure(x,D_struc,[],problem,infostr,solverinput,solveroutput,solvertime);
function [x,D_struc,problem,r,res,solvertime,prob] = call_mosek_lpqpsocpsdp(model);
if nnz(model.Q)==0 & isempty(model.integer_variables) && isempty(model.x0)
% Standard cone problem
[x,D_struc,problem,r,res,solvertime,prob] = call_mosek_lpqpsocpsdpdual(model);
return
elseif model.K.s(1)>0
% Semidefinite program with integer variables or quadratic objective
% or specified initial point
[x,D_struc,problem,r,res,solvertime,prob] = call_mosek_sdp(model);
else
% Integer conic program + possibly quadratic objective
[x,D_struc,problem,r,res,solvertime,prob] = call_mosek_lpqp(model);
end
function [x,D_struc,problem,r,res,solvertime,prob] = call_mosek_geometric(model);
x = [];
D_struc = [];
r = [];
res = [];
solvertime = 0;
[prob,problem] = yalmip2geometric(model.options,model.F_struc,model.c,model.Q,model.K,model.ub,model.lb,model.monomtable,model.linear_variables,model.extended_variables);
if problem == 0
% Mosek does not support equalities
if ~isempty(prob.G)
prob.A = [prob.A;prob.G;-prob.G];
prob.b = [prob.b;prob.h;1./prob.h];
prob.map = [prob.map;max(prob.map) + (1:2*length(prob.h))'];
end
if model.options.savedebug
save mosekdebug prob
end
param = model.options.mosek;
% Call MOSEK
showprogress('Calling MOSEK',model.options.showprogress);
if model.options.verbose == 0
solvertime = tic;
res = mskgpopt(prob.b,prob.A,prob.map,param,'minimize echo(0)');
solvertime = toc(solvertime);
else
solvertime = tic;
res = mskgpopt(prob.b,prob.A,prob.map,param,'minimize');
solvertime = toc(solvertime);
end
sol = res.sol;
x = zeros(length(model.c),1);
x(model.linear_variables)=exp(res.sol.itr.xx);
D_struc = [];
% Check, currently not exhaustive...
switch res.sol.itr.prosta
case 'PRIMAL_AND_DUAL_FEASIBLE'
problem = 0;
case 'PRIMAL_INFEASIBLE'
problem = 1;
case 'DUAL_INFEASIBLE'
problem = 2;
case 'UNKNOWN'
problem = 9;
otherwise
problem = -1;
end
end
function [x,D_struc,problem,r,res,solvertime,prob] = call_mosek_lpqpsocpsdpdual(model)
% Convert if the caller is bnb or bmibnb which might have appended bounds
% Sure, we could setup model with bounds, but...
[model.F_struc,model.K] = addbounds(model.F_struc,model.K,model.ub,model.lb);
param = model.options.mosek;
prob.c = model.F_struc(1:model.K.f+model.K.l+sum(model.K.q),1);
prob.a = -model.F_struc(1:model.K.f+model.K.l+sum(model.K.q),2:end)';
prob.blc = -model.c;
prob.buc = -model.c;
prob.blx = -inf(size(prob.a,2),1);
prob.bux = inf(size(prob.a,2),1);
top = model.K.f+model.K.l;
prob.blx(1+model.K.f:model.K.f+model.K.l) = 0;
if model.K.q(1)>0
for i = 1:length(model.K.q)
prob.cones{i}.type = 'MSK_CT_QUAD';
prob.cones{i}.sub = top+1:top+model.K.q(i);
top = top + model.K.q(i);
end
end
if model.K.s(1)>0
prob = appendSDPdata(model.F_struc,model.K,prob);
end
if model.options.savedebug
ops = model.options;
save mosekdebug prob param ops
end
[r,res,solvertime] = doCall(prob,param,model.options);
try
x = res.sol.itr.y;
catch
x = nan(length(model.c),1);
end
if model.options.saveduals & ~isempty(x)
try
D_struc_SDP = zeros(sum(model.K.s.^2),1);
top = 1;
dtop = 1;
for i = 1:length(model.K.s)
n = model.K.s(i);
I = find(tril(ones(n)));
v = res.sol.itr.barx(top:((top+n*(n+1)/2)-1));
D_struc_SDP(dtop + I - 1) = v;
in = ceil(I/n);
jn = mod(I-1,n)+1;
D_struc_SDP(dtop + (jn-1)*n+in - 1) = v;
top = top + n*(n+1)/2;
dtop = dtop + n^2;
end
D_struc = [res.sol.itr.xx;D_struc_SDP];
catch
D_struc = [];
end
else
D_struc = [];
end
problem = MosekYALMIPError(res);
function [res,sol,solvertime] = doCall(prob,param,options)
showprogress('Calling Mosek',options.showprogress);
if options.verbose == 0
solvertime = tic;
[res,sol] = mosekopt('minimize echo(0)',prob,param);
solvertime = toc(solvertime);
else
solvertime = tic;
[res,sol] = mosekopt('minimize info',prob,param);
solvertime = toc(solvertime);
end
function problem = MosekYALMIPError(res)
if res.rcode == 2001
problem = 1;
return
elseif res.rcode == 10007
problem = 16;
return
end
switch res.sol.itr.prosta
case 'PRIMAL_AND_DUAL_FEASIBLE'
problem = 0;
case 'DUAL_INFEASIBLE'
problem = 1;
case 'PRIMAL_INFEASIBLE'
problem = 2;
case 'MSK_RES_TRM_USER_CALLBACK'
problem = 16;
case 'MSK_RES_TRM_STALL'
problem = 4;
case 'UNKNOWN'
try
if isequal(res.rcodestr,'MSK_RES_TRM_STALL')
problem = 4;
else
problem = 9;
end
catch
problem = 9;
end
otherwise
problem = -1;
end
function model = appendBounds(model);
FstrucNew = [];
if ~isempty(model.lb)
ii = find(~isinf(model.lb));
FstrucNew = [-model.lb(ii) sparse(1:length(ii),ii,size(model.F_struc,2)-1,length(ii))];
end
if ~isempty(model.ub)
ii = find(~isinf(model.ub));
FstrucNew = [model.lb(ii) -sparse(1:length(ii),ii,size(model.F_struc,2)-1,length(ii))];
end
function prob = appendSDPdata(F_struc,K,prob)
prob.bardim = K.s;
prob.barc.subj = [];
prob.barc.subk = [];
prob.barc.subl = [];
prob.barc.val = [];
prob.bara.subi = [];
prob.bara.subj = [];
prob.bara.subk = [];
prob.bara.subl = [];
prob.bara.val = [];
C = F_struc(:,1);
A = -F_struc(:,2:end);
% -- Faster fix by Shahar
tops = [1 cumsum(K.s.^2)+1];
top = 1+K.f+K.l+sum(K.q);
[ii,jj,kk] = find(A(top:top + sum(K.s.^2)-1,:));
allcon = floor(interp1(tops,1:length(tops),ii,'linear'));
all_iilocal = ii-tops(allcon)'+1;
a = all_iilocal;
b = K.s(allcon);
allcol = ceil(a(:)./b(:))';
allrow = a(:)' - (allcol-1).*b(:)';
allvar = jj;
allval = kk;
% sort (for backward compatibility?)
[~,ind_sort] = sort(allcon);
allcon = allcon(ind_sort)';
allcol = allcol(ind_sort)';
allrow = allrow(ind_sort)';
allvar = allvar(ind_sort)';
allval = allval(ind_sort)';
% --
keep = find(allrow >= allcol);
allcol = allcol(keep);
allrow = allrow(keep);
allcon = allcon(keep);
allvar = allvar(keep);
allval = allval(keep);
prob.bara.subi = [prob.bara.subi allvar];
prob.bara.subj = [prob.bara.subj allcon];
prob.bara.subk = [prob.bara.subk allrow];
prob.bara.subl = [prob.bara.subl allcol];
prob.bara.val = [prob.bara.val allval];
for j = 1:length(K.s)
n = K.s(j);
Ci = C(top:top+n^2-1);
Ci = tril(reshape(Ci,n,n));
[k,l,val] = find(Ci);
prob.barc.subj = [prob.barc.subj j*ones(1,length(k))];
prob.barc.subk = [prob.barc.subk k(:)'];
prob.barc.subl = [prob.barc.subl l(:)'];
prob.barc.val = [prob.barc.val val(:)'];
top = top + n^2;
end
function [x,D_struc,problem,r,res,solvertime,prob] = call_mosek_sdp(model)
param = model.options.mosek;
% Convert
[model.F_struc,model.K] = addbounds(model.F_struc,model.K,model.ub,model.lb);
prob = yalmip2SDPmosek(model);
% Debug?
if model.options.savedebug
save mosekdebug prob param
end
if model.options.verbose == 0
solvertime = tic;
[r,res] = mosekopt('minimize echo(0)',prob,param);
solvertime = toc(solvertime);
else
solvertime = tic;
[r,res] = mosekopt('minimize info',prob,param);
solvertime = toc(solvertime);
end
if res.rcode == 2001
res.sol.itr.prosta = 'DUAL_INFEASIBLE';
end
try
x = res.sol.itr.y;
catch
x = nan(length(model.c),1);
end
if model.options.saveduals & ~isempty(x)
D_struc = [res.sol.itr.xx];
D_struc_SDP = sum(model.K.s.^2);
top = 1;
dtop = 1;
for i = 1:length(model.K.s)
X = zeros(model.K.s(i));
n = model.K.s(i);
I = find(tril(ones(n)));
D_struc_SDP(dtop + I - 1) = res.sol.itr.barx(top:((top+n*(n+1)/2)-1));
X(I) = res.sol.itr.barx(top:((top+n*(n+1)/2)-1));
X = X + tril(X,-1)';
D_struc = [D_struc;X(:)];
top = top + n*(n+1)/2;
dtop = dtop + n^2;
end
else
D_struc = [];
end
switch res.sol.itr.prosta
case 'PRIMAL_AND_DUAL_FEASIBLE'
problem = 0;
case 'DUAL_INFEASIBLE'
problem = 1;
case 'PRIMAL_INFEASIBLE'
problem = 2;
case 'UNKNOWN'
try
if isequal(res.rcodestr,'MSK_RES_TRM_STALL')
problem = 4;
else
problem = 9;
end
catch
problem = 9;
end
otherwise
problem = -1;
end
function [x,D_struc,problem,r,res,solvertime,prob] = call_mosek_lpqp(model);
prob.c = model.c;
if ~isempty(model.F_struc)
prob.a = -model.F_struc(:,2:end);
prob.buc = full(model.F_struc(:,1));
prob.blc = repmat(-inf,length(prob.buc),1);
else
prob.a = sparse(ones(1,length(model.c))); % Dummy constraint
prob.buc = inf;
prob.blc = -inf;
end
if isempty(model.lb)
prob.blx = repmat(-inf,1,length(model.c));
else
prob.blx = model.lb;
end
if isempty(model.ub)
prob.bux = repmat(inf,1,length(model.c));
else
prob.bux = model.ub;
end
if model.K.f>0
prob.blc(1:model.K.f) = prob.buc(1:model.K.f);
end
[prob.qosubi,prob.qosubj,prob.qoval] = find(tril(sparse(2*model.Q)));
if model.K.q(1)>0
nof_new = sum(model.K.q);
prob.a = [prob.a [spalloc(model.K.f,nof_new,0);spalloc(model.K.l,nof_new,0);speye(nof_new);spalloc(sum(model.K.s.^2),nof_new,0)]];
prob.blc(1+model.K.f+model.K.l:model.K.f+model.K.l+sum(model.K.q)) = prob.buc(1+model.K.f+model.K.l:model.K.f+model.K.l+sum(model.K.q)); % Note, fixed the SDP cones too
prob.c = [prob.c;zeros(nof_new,1)];
top = size(model.F_struc,2)-1;
for i = 1:length(model.K.q)
prob.cones{i}.type = 'MSK_CT_QUAD';
prob.cones{i}.sub = top+1:top+model.K.q(i);
prob.blx(top+1:top+model.K.q(i)) = -inf;
prob.bux(top+1:top+model.K.q(i)) = inf;
top = top + model.K.q(i);
end
end
if ~isempty(model.integer_variables)
prob.ints.sub = model.integer_variables;
end
param = model.options.mosek;
if ~isempty(model.x0)
if model.options.usex0
prob.sol.int.xx = zeros(max([length(model.Q) size(prob.a,2)]),1);
prob.sol.int.xx(model.integer_variables) = x0(model.integer_variables);
evalc('[r,res] = mosekopt (''symbcon'')');
sc = res.symbcon ;
param.MSK_IPAR_MIO_CONSTRUCT_SOL = sc.MSK_ON;
end
end
% Debug?
if model.options.savedebug
save mosekdebug prob param
end
% Call MOSEK
showprogress('Calling MOSEK',model.options.showprogress);
if model.options.verbose == 0
solvertime = tic;
[r,res] = mosekopt('minimize echo(0)',prob,param);
solvertime = toc(solvertime);
else
solvertime = tic;
[r,res] = mosekopt('minimize',prob,param);
solvertime = toc(solvertime);
end
if (r == 1010) || (r == 1011) | (r==1001)
problem = -5;
x = [];
D_struc = [];
elseif r == 1200
problem = 7;
x = [];
D_struc = [];
else
% Recover solutions
sol = res.sol;
if isempty(model.integer_variables)
x = sol.itr.xx(1:length(model.c)); % Might have added new ones
D_struc = (sol.itr.suc-sol.itr.slc);
error_message = sol.itr.prosta;
else
try
x = sol.int.xx(1:length(model.c)); % Might have added new ones
D_struc = [];
error_message = sol.int.prosta;
catch
x = [];
error_message = 'crash';
D_struc = [];
end
end
switch error_message
case {'PRIMAL_AND_DUAL_FEASIBLE','PRIMAL_FEASIBLE'}
problem = 0;
case 'PRIMAL_INFEASIBLE'
problem = 1;
case 'DUAL_INFEASIBLE'
problem = 2;
case 'PRIMAL_INFEASIBLE_OR_UNBOUNDED'
problem = 12;
otherwise
problem = -1;
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
calllsqlin.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/calllsqlin.m
| 2,847 |
utf_8
|
170763f45e1ac6f29996fc8e82535665
|
function output = calllsqlin(interfacedata)
K = interfacedata.K;
c = interfacedata.c;
CA = interfacedata.F_struc;
options = interfacedata.options;
% To begin with, with try to figure out if this is a simple non-negative
% least squares in disguise
if length(K.q)~=1
output = error_output;
return
end
% total number of variables, #x+1 since YALMIP has introduced an epi-graph
% variable to model norm(Cx-d)
n = size(CA,2)-1;
if nnz(c)~=1
output = error_output;
return
end
if c(end)~=1
output = error_output;
return
end
if c(end)~=1
output = error_output;
return
end
Cones = CA(K.f+K.l+1:end,:);
LPs = CA(1:K.l+K.f,:);
if any(LPs(:,end))
% Epigraph involved in LPs
output = error_output;
return
end
if isempty(LPs)
Aeq = [];
beq = [];
A = [];
b = [];
else
Aeq = -LPs(1:1:K.f,2:end-1);
beq = LPs(1:1:K.f,1);
A =-LPs(K.f+1:end,2:end-1);
b = LPs(K.f+1:end,1);
end
% Is it really cone(C*x-d,t)
if ~all(Cones(1,:) == [zeros(1,n) 1])
output = error_output;
return
end
if ~all(Cones(:,end) == [1;zeros(K.q-1,1)])
output = error_output;
return
end
model.d = -Cones(2:end,1);
model.C = Cones(2:end,2:end-1);
model.Aineq = A;
model.Aeq = Aeq;
model.bineq = b;
model.beq = beq;
model.x0 = [];
model.options = interfacedata.options.lsqlin;
model.solver = 'lsqlin';
if options.savedebug
save debugfile model
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
[X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA] = lsqlin(model);
solvertime = toc(solvertime);
solveroutput.X = X;
solveroutput.RESNORM = RESNORM;
solveroutput.RESIDUAL = RESIDUAL;
solveroutput.EXITFLAG = EXITFLAG;
solveroutput.OUTPUT = OUTPUT;
solveroutput.LAMBDA = LAMBDA;
solution.x = [X;RESNORM];
solution.D_struc = [];
switch EXITFLAG
case 1
solution.problem = 0;
case 2
solution.problem = 1;
case 0
solution.problem = 3;
case {3,-4,-7}
solution.problem = 4;
otherwise
solution.problem = 9;
end
% Save all data sent to solver?
if ~options.savesolverinput
model = [];
end
% Save all data from the solver?
if ~options.savesolveroutput
solveroutput = [];
end
if ~options.savesolverinput
solverinput = [];
else
solverinput = model;
end
if ~options.savesolveroutput
solveroutput = [];
else
solveroutput = solveroutput;
end
% Standard interface
output = createOutputStructure(solution.x(:),solution.D_struc,[],solution.problem,yalmiperror(solution.problem,interfacedata.solver.tag),solverinput,solveroutput,solvertime);
function output = error_output
output.Primal = [];
output.Dual = [];
output.Slack = [];
output.problem = 9;
output.infostr = yalmiperror(-4,'LSQLIN');
output.solvertime = 0;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callbonmin.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callbonmin.m
| 4,532 |
utf_8
|
3e4061b2327fce758da882c69816d9fe
|
function output = callbonmin(model)
model = yalmip2nonlinearsolver(model);
options = [];
try
options.bonmin = optiRemoveDefaults(model.options.bonmin,bonminset());
catch
options.bonmin = model.options.bonmin;
end
options.ipopt = model.options.ipopt;
options.display = model.options.verbose;
if ~model.derivative_available
disp('Derivate-free call to bonmin/ipopt not yet implemented')
error('Derivate-free call to bonmin/ipopt not yet implemented')
end
if model.options.savedebug
save bonmindebug model
end
Fupp = [ repmat(0,length(model.bnonlinineq),1);
repmat(0,length(model.bnonlineq),1);
repmat(0,length(model.b),1);
repmat(0,length(model.beq),1)];
Flow = [ repmat(-inf,length(model.bnonlinineq),1);
repmat(0,length(model.bnonlineq),1);
repmat(-inf,length(model.b),1);
repmat(0,length(model.beq),1)];
if isempty(Flow)
Flow = [];
Fupp = [];
end
% Since ipopt react strangely on lb>ub, we should bail if that is detected
% (ipopt creates an exception)
if ~isempty(model.lb)
if any(model.lb>model.ub)
problem = 1;
solverinput = [];
solveroutput = [];
output = createoutput(model.lb*0,[],[],problem,'BONMIN',solverinput,solveroutput,0);
return
end
end
% These are needed to avoid recomputation due to ipopts double call to get
% f and df, and g and dg
global latest_x_f
global latest_x_g
global latest_df
global latest_f
global latest_G
global latest_g
global latest_xevaled
global latest_x_xevaled
latest_G= [];
latest_g = [];
latest_x_f = [];
latest_x_g = [];
latest_xevaled = [];
latest_x_xevaled = [];
funcs.objective = @(x)ipopt_callback_f(x,model);
funcs.gradient = @(x)ipopt_callback_df(x,model);
if ~isempty(Fupp)
funcs.constraints = @(x)ipopt_callback_g(x,model);
funcs.jacobian = @(x)ipopt_callback_dg(x,model);
end
options.lb = model.lb(:)';
options.ub = model.ub(:)';
if ~isempty(Fupp)
options.cl = Flow;
options.cu = Fupp;
end
if ~isempty(Fupp)
m = length(model.lb);
allA=[model.Anonlinineq; model.Anonlineq];
jacobianstructure = spalloc(size(allA,1),m,0);
depends = allA | allA;
for i = 1:size(depends,1)
vars = find(depends(i,:));
[ii,vars] = find(model.deppattern(vars,:));
vars = unique(vars);
s = size(jacobianstructure,1);
for j = 1:length(vars)
jacobianstructure(i,find(vars(j) == model.linearindicies)) = 1;
end
end
allA=[model.A; model.Aeq];
depends = allA | allA;
jacobianstructure = [jacobianstructure;depends];
Z = sparse(jacobianstructure);
funcs.jacobianstructure = @() Z;
end
if ~model.options.usex0
model.x0 = (options.lb+options.ub)/2;
model.x0(isinf(options.ub)) = options.lb(isinf(options.ub))+1;
model.x0(isinf(options.lb)) = options.ub(isinf(options.lb))-1;
model.x0(isinf(model.x0)) = 0;
end
if ~isempty(model.binary_variables) | ~isempty(model.integer_variables)
options.var_type = zeros(length(model.linearindicies),1);
options.var_type(model.binary_variables) = -1;
options.var_type(model.integer_variables) = 1;
end
showprogress('Calling BONMIN',model.options.showprogress);
solvertime = tic;
[xout,info] = bonmin(model.x0,funcs,options);
solvertime = toc(solvertime);
x = RecoverNonlinearSolverSolution(model,xout);
switch info.status
case {0,2}
problem = 0;
case 1
problem = 1;
case {-1}
problem = 3;
case {3}
problem = 15;
otherwise
problem = -1;
end
% Duals currently not supported
D_struc = [];
% Save all data sent to solver?
if model.options.savesolverinput
solverinput.x0 = model.x0;
solverinput.model = model;
solverinput.options = options;
else
solverinput = [];
end
% Save all data from the solver?
if model.options.savesolveroutput
solveroutput.x = xout;
solveroutput.info = info;
else
solveroutput = [];
end
% Standard interface
output = createoutput(x,D_struc,[],problem,'BONMIN',solverinput,solveroutput,solvertime);
% Code supplied by Jonatan Currie
function opts = removeDefaults(opts,defs)
oFn = fieldnames(opts);
for i = 1:length(oFn)
label = oFn{i};
if(isfield(defs,label))
if(ischar(opts.(label)))
if(strcmpi(defs.(label),opts.(label)))
opts = rmfield(opts,label);
end
else
if(defs.(label) == opts.(label))
opts = rmfield(opts,label);
end
end
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
calllsqnonneg.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/calllsqnonneg.m
| 2,939 |
utf_8
|
f42645b72b16302e04543c90729d2f65
|
function output = calllsqnonneg(interfacedata)
K = interfacedata.K;
c = interfacedata.c;
CA = interfacedata.F_struc;
options = interfacedata.options;
% To begin with, with try to figure out if this is a simple non-negative
% least squares in disguise
if length(K.q)~=1
output = error_output;
return
end
% total number of variables, #x+1 since YALMIP has introduced an epi-graph
% variable to model norm(Cx-d)
n = size(CA,2)-1;
if nnz(c)~=1
output = error_output;
return
end
if c(end)~=1
output = error_output;
return
end
if c(end)~=1
output = error_output;
return
end
if K.l~=n-1
output = error_output;
return
end
Cones = CA(K.l+1:end,:);
LPs = CA(1:K.l,:);
if any(LPs(:,end))
% Epigraph involved in LPs
output = error_output;
return
end
% Are we constraining all x>0
if any(LPs(:,1))
output = error_output;
return
end
[i,j,k] = find(LPs(:,2:end));
if ~all(k==1)
output = error_output;
return
end
if ~all(LPs*ones(n+1,1)==1)
output = error_output;
return
end
% Is it really cone(C*x-d,t)
if ~all(Cones(1,:) == [zeros(1,n) 1])
output = error_output;
return
end
if ~all(Cones(:,end) == [1;zeros(K.q-1,1)])
output = error_output;
return
end
model.d = -Cones(2:end,1);
model.C = Cones(2:end,2:end-1);
model.options = interfacedata.options.lsqnonneg;
if isempty(interfacedata.x0)
model.x0 = [];
else
model.x0 = interfacedata.x0(1:end-1);
end
if options.savedebug
save debugfile model
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
try
[X,RESNORM,RESIDUAL,EXITFLAG] = lsqnonneg(model.C,model.d,model.options);
catch
[X,RESNORM,RESIDUAL,EXITFLAG] = lsqnonneg(model.C,model.d,model.x0,model.options);
end
solvertime = toc(solvertime);
solveroutput.X = X;
solveroutput.RESNORM = RESNORM;
solveroutput.RESIDUAL = RESIDUAL;
solveroutput.EXITFLAG = EXITFLAG;
solution.x = [X;RESNORM];
solution.D_struc = [];
switch EXITFLAG
case 1
solution.problem = 0;
case 0
solution.problem = 3;
otherwise
solution.problem = 9;
end
% Save all data sent to solver?
if ~options.savesolverinput
model = [];
end
% Save all data from the solver?
if ~options.savesolveroutput
solveroutput = [];
end
if ~options.savesolverinput
solverinput = [];
else
solverinput = model;
end
if ~options.savesolveroutput
solveroutput = [];
else
solveroutput = solveroutput;
end
% Standard interface
output = createOutputStructure(solution.x(:),solution.D_struc,[],solution.problem,yalmiperror(solution.problem,interfacedata.solver.tag),solverinput,solveroutput,solvertime);
function output = error_output(e)
if nargin == 0
e = -4;
end
output.Primal = [];
output.Dual = [];
output.Slack = [];
output.problem = e;
output.infostr = yalmiperror(e,'LSQNONNEG');
output.solvertime = 0;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
callqpoases.m
|
.m
|
LMI-Matlab-master/yalmip/solvers/callqpoases.m
| 1,710 |
utf_8
|
42faef3cd8048ea6e498b94d4de8bb35
|
function output = callqpoases(interfacedata)
options = interfacedata.options;
model = yalmip2quadprog(interfacedata);
if options.savedebug
save debugfile model
end
if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end
solvertime = tic;
solution = callsolver(model,options);
solvertime = toc(solvertime);
switch solution.exitflag
case 0
problem = 0;
case 1
problem = 3;
case -2
problem = 1;
case -3
problem = 2;
case -1
problem = 11;
otherwise
problem = -1;
end
% Standard interface
Primal = solution.x(:);
Dual = solution.lambda(:);
infostr = yalmiperror(problem,interfacedata.solver.tag);
if ~options.savesolverinput
solverinput = [];
else
solverinput = model;
end
if ~options.savesolveroutput
solveroutput = [];
else
solveroutput = solution;
end
% Standard interface
output = createOutputStructure(Primal,Dual,[],problem,infostr,solverinput,solveroutput,solvertime);
function solveroutput = callsolver(model,options)
x = [];
fval = [];
exitflag = [];
iter = [];
lambda = [];
lbA = full([model.beq;-inf(length(model.b),1)]);
ubA = full([model.beq;model.b]);
A = [model.Aeq;model.A];
if nnz(model.Q) == 0
options.qpoases.enableRegularisation=1;
end
options.qpoases.printLevel = options.verbose+1;
[x,fval,exitflag,iter,lambda] = qpOASES(model.Q, model.c, A, model.lb,model.ub,lbA,ubA,options.qpoases,qpOASES_auxInput());
solveroutput.x = x;
solveroutput.fval = fval;
solveroutput.exitflag = exitflag;
solveroutput.iter = iter;
if ~isempty(lambda)
solveroutput.lambda = -lambda(1+length(model.lb):end);
else
solveroutput.lambda=[];
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdpfun.m
|
.m
|
LMI-Matlab-master/yalmip/operators/sdpfun.m
| 5,014 |
utf_8
|
0c13f9a11b9b9d4d5504b55e0d04cc52
|
function varargout = sdpfun(varargin)
%SDPFUN Gateway to general (elementwise) functions on SDPVAR variables (overloaded)
if ~isa(varargin{1},'char') && any(strcmp(cellfun(@class,varargin,'UniformOutput',0),'sdpvar'))
fun_handles = zeros(nargin,1);
for i = 1:nargin
if isstr(varargin{end}) && isequal(varargin{i}(1),'@')
fun = eval(varargin{i});
varargin{i} = fun;
fun_handles(i) = 1;
elseif isa(varargin{i},'function_handle')
fun_handles(i) = 1;
end
end
% Temporarily remove derivative info (to avoid change of legacy
% code below)
if nnz(fun_handles) == 2
derivative = varargin{end};
varargin = {varargin{1:end-1}}
else
derivative = [];
end
for i = 1:length(varargin)
% we don't know in which order arguments are applied. If some argument
% is an sdpvar, it means the user is defining the operator
if isa(varargin{i},'sdpvar')
% Overloaded operator for SDPVAR objects. Pass on args and save them.
% try to figure out size of expected output (many->1 or many->many
varargin_copy = varargin;
for j = 1:length(varargin)-1
% Create zero arguments
if isa(varargin_copy{j},'sdpvar')
varargin_copy{j} = zeros(size(varargin_copy{j},1),size(varargin_copy{j},2));
end
end
output = feval(varargin_copy{end},varargin_copy{1:end-1});
if prod(size(output)) == 1
% MANY -> 1
% Append derivative (might be empty)
varargin{end+1} = derivative;
varargout{1} = yalmip('define',mfilename,varargin{:});
else
% MANY -> MANY
y = [];
[n,m] = size(varargin{1});
varargin{1} = varargin{1}(:);
for i = 1:length(varargin{1})
varargin_copy = varargin;
varargin_copy{1} = varargin_copy{1}(i);
varargin_copy{end+1} = derivative;
y = [y;yalmip('define',mfilename,varargin_copy{:})];
end
varargout{1} = reshape(y,n,m);
end
return
end
end
end
switch class(varargin{1})
case {'struct','double'} % What is the numerical value of this argument (needed for displays etc)
varargout{1} = feval(varargin{end-1},varargin{1:end-2});
case 'sdpvar'
% Should not happen
error('Report bug. Call to SDPFUN with SDPVAR object');
case 'char' % YALMIP sends 'model' when it wants the epigraph or hypograph
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.bounds = @bounds;
operator.convexhull = @convexhull;
if ~isempty(varargin{end})
operator.derivative = varargin{end};
end
varargout{1} = [];
varargout{2} = operator;
% Figure out which argument actually is the SDPVAR object (not
% necessarily the first argument
for i = 3:length(varargin)
if isa(varargin{i},'sdpvar')
varargout{3} = varargin{i};
return
end
end
error('SDPFUN arguments seem weird. Could not find any SDPVAR object');
otherwise
error('SDPVAR/SDPFUN called with CHAR argument?');
end
function [Ax,Ay,b] = convexhull(xL,xU,varargin)
if ~(isinf(xL) | isinf(xU))
z = linspace(xL,xU,100);
fz = feval(varargin{end-1},z,varargin{1:end-2});
% create 4 bounding planes
% f(z) < k1*(x-XL) + f(xL)
% f(z) > k2*(x-XL) + f(xL)
% f(z) < k3*(x-XU) + f(xU)
% f(z) > k4*(x-XU) + f(xU)
% f(z) < k5*(x-XM) + f(xM)
% f(z) > k6*(x-XM) + f(xM)
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))];
else
Ax = [];
Ay = [];
b = [];
end
function [L,U] = bounds(xL,xU,varargin)
if ~isinf(xL) & ~isinf(xU)
xtest = linspace(xL,xU,100);
values = feval(varargin{end-1},xtest,varargin{1:end-2});
[minval,minpos] = min(values);
[maxval,maxpos] = max(values);
% Concetrate search around the extreme regions
xtestmin = linspace(xtest(max([1 minpos-5])),xtest(min([100 minpos+5])),100);
xtestmax = linspace(xtest(max([1 maxpos-5])),xtest(min([100 maxpos+5])),100);
values1 = feval(varargin{end-1},xtestmin,varargin{1:end-2});
values2 = feval(varargin{end-1},xtestmax,varargin{1:end-2});
L = min([values1 values2]);
U = max([values1 values2]);
else
L = -inf;
U = inf;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
absexp.m
|
.m
|
LMI-Matlab-master/yalmip/operators/absexp.m
| 972 |
utf_8
|
1c9eb8d6258431984094357b18a76a4a
|
function varargout = absexp(varargin)
switch class(varargin{1})
case 'double'
varargout{1} = abs(exp(varargin{1}) - 1);
case 'sdpvar'
varargout{1} = InstantiateBuiltInScalar(mfilename,varargin{:});
case 'char'
t = varargin{2};
X = varargin{3};
F = SetupEvaluationVariable(varargin{:});
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.bounds = @bounds;
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 & xU>=0
% The variable is not bounded enough yet
L = 0;
U = max([abs(exp(xL)-1) abs(exp(xU)-1)]);
else
U = max([abs(exp(xL)-1) abs(exp(xU)-1)]);
L = min([abs(exp(xL)-1) abs(exp(xU)-1)]);
end
function [Ax, Ay, b] = convexhull(xL,xU)
Ax = [];
Ay = [];
b = [];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
entropy.m
|
.m
|
LMI-Matlab-master/yalmip/operators/entropy.m
| 2,257 |
utf_8
|
311340b986854921e33a7272e402651d
|
function varargout = entropy(varargin)
%ENTROPY
%
% y = ENTROPY(x)
%
% Computes/declares concave entropy -sum(x.*log(x))
%
% Implemented as evalutation based nonlinear operator. Hence, the concavity
% of this function is exploited to perform convexity analysis and rigorous
% modelling.
%
% See also CROSSENTROPY, KULLBACKLEIBLER.
switch class(varargin{1})
case 'double'
x = varargin{1};
% Safe version with defined negative values (helps fmincon when
% outside feasible region)
if any(x<=0)
z = abs(x);z(z==0)=1;
y = z.*log(z);
y(x==0) = 0;
y(x<0) = 3*(x(x<0)-1).^2-3;
varargout{1} = -sum(y);
else
varargout{1} = -sum(x.*log(x));
end
case {'sdpvar','ndsdpvar'}
varargin{1} = reshape(varargin{1},[],1);
varargout{1} = yalmip('define',mfilename,varargin{1});
case 'char'
X = varargin{3};
F = (X >= 0);
operator = struct('convexity','concave','monotonicity','none','definiteness','none','model','callback');
operator.range = [-inf exp(-1)*length(X)];
operator.domain = [0 inf];
operator.bounds = @bounds;
operator.convexhull = @convexhull;
operator.derivative = @derivative;
varargout{1} = F;
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/LOG called with CHAR argument?');
end
function df = derivative(x)
x(x<=0)=eps;
df = (-1-log(x));
function [L, U] = bounds(xL,xU)
t = find(xL==0);
u = find(xL<0);
xL(t)=1;
LU = [-xL.*log(xL) -xU.*log(xU)];
LU(t,1)=0;
xL(t) = 0;
L = min(LU,[],2);
U = max(LU,[],2);
U((xL < exp(-1)) & (xU > exp(-1))) = exp(-1);
L = sum(L);
U = sum(U);
function [Ax, Ay, b] = convexhull(xL,xU)
Ax = [];
Ay = [];
b = [];
% % Loop thorough all variables, and compute a convex hull each term xlogx
% Hmm, how do I merge without expensive projection
% for i = 1:length(xL)
% if xL(i) <= 0
% fL = inf;
% dfL = -inf;
% else
% fL = -xL(i).*log(xL(i));
% dfL = -log(xL(i)) - 1;
% end
% fU = -xU(i).*log(xU(i));
% dfU = -log(xU(i)) - 1;
% [Ax,Ay,b] = convexhullConcave(xL(i),xU(i),fL,fU,dfL,dfU);
% end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
xexpintinv.m
|
.m
|
LMI-Matlab-master/yalmip/operators/xexpintinv.m
| 816 |
utf_8
|
bd8857363df0521d4ca537237872b1f5
|
function varargout = xexpintinv(varargin)
%XEXPINTINV EXPINT(1/Z)/Z
switch class(varargin{1})
case 'double'
z = varargin{1};
varargout{1} = (1./z).*expint(1./z);
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
varargout{1} = [];
varargout{2} = createOperator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/EXPINT called with CHAR argument?');
end
function operator = createOperator
operator = struct('convexity','none','monotonicity','none','definiteness','positive','model','callback');
operator.derivative = @derivative;
operator.range = [0 1];
operator.domain = [1e-8 inf];
function d = derivative(z);
d = (-1./z.^2).*expint(1./z)+(1./z).*(-z.*exp(-1./z)).*(-1./z.^2);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
kullbackleibler.m
|
.m
|
LMI-Matlab-master/yalmip/operators/kullbackleibler.m
| 1,913 |
utf_8
|
b60195db713567cbb6515e32703c04e8
|
function varargout = kullbackleibler(varargin)
% KULLBACKLEIBLER
%
% y = KULLBACKLEIBLER(x,y)
%
% Computes/declares the convex Kullback-Leibler divergence sum(x.*log(x./y))
% Alternatively -sum(x.*log(y/x)), i.e., negated perspectives of log(y)
%
% See also ENTROPY, CROSSENTROPY
switch class(varargin{1})
case 'double'
if nargin == 1
z = varargin{1};
z = reshape(z,[],2);
x = z(:,1);
y = z(:,2);
else
x = varargin{1}(:);
y = varargin{2}(:);
end
l = log(x./y);
l(x<=0) = 0;
l = real(l);
varargout{1} = sum(x.*l);
case {'sdpvar','ndsdpvar'}
varargin{1} = reshape(varargin{1},[],1);
varargin{2} = reshape(varargin{2},[],1);
if length(varargin{1})~=length(varargin{2})
if length(varargin{1})==1
varargin{1} = repmat(varargin{1},length(varargin{2}),1);
elseif length(varargin{2})==1
varargin{2} = repmat(varargin{2},length(varargin{1}),1);
else
error('Dimension mismatch in kullbackleibler')
end
end
varargout{1} = yalmip('define',mfilename,[varargin{1};varargin{2}]);
case 'char'
X = varargin{3};
F = [X >= 0];
operator = struct('convexity','convex','monotonicity','none','definiteness','none','model','callback');
operator.range = [-inf inf];
operator.domain = [0 inf];
operator.derivative = @derivative;
varargout{1} = F;
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/KULLBACKLEIBLER called with CHAR argument?');
end
function df = derivative(x)
z = abs(reshape(x,[],2));
x = z(:,1);
y = z(:,2);
% Use KL = -Entropy + Cross Entropy
df = [1+log(x);0*y] + [-log(y);-x./y];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
plog.m
|
.m
|
LMI-Matlab-master/yalmip/operators/plog.m
| 3,011 |
utf_8
|
c2d6cca279a1861bf8dfe62cf593dc28
|
function varargout = plog(varargin)
%PLOG
%
% y = PLOG(x)
%
% Computes concave perspective log, x(1)*log(x(2)/x(1)) on x>0
%
% Implemented as evalutation based nonlinear operator. Hence, the concavity
% of this function is exploited to perform convexity analysis and rigorous
% modelling.
switch class(varargin{1})
case 'double'
if ~isequal(prod(size(varargin{1})),2)
error('PLOG only defined for 2x1 arguments');
end
x = varargin{1};
% Safe version with defined negative values (helps fmincon when
% outside feasible region)
if isequal(x(1),[0])
varargout{1} = 0;
else
varargout{1} = x(1)*log(x(2)/x(1));
end
case 'sdpvar'
if ~isequal(prod(size(varargin{1})),2)
error('PLOG only defined for 2x1 arguments');
else
varargout{1} = yalmip('define',mfilename,varargin{1});
end
case 'char'
X = varargin{3};
operator = struct('convexity','concave','monotonicity','none','definiteness','none','model','callback');
operator.range = [-inf inf];
operator.domain = [0 inf];
% operator.bounds = @bounds;
% operator.convexhull = @convexhull;
operator.derivative = @derivative;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/PLOG called with CHAR argument?');
end
function dp = derivative(x)
z = x(2)/x(1);
dp = [log(z)-1;1./z];
function [L,U] = 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] = convexhull(L,U);%xL,xU)
%
% Ax = [];
% Ay = [];
% b = [];
% return
% L = [1 2];
% U = [3 6];
p1 = [L(1);L(2)];
p2 = [U(1);L(2)];
p3 = [L(1);U(2)];
p4 = [U(1);U(2)];
pm = [(L(1) + U(1))/2;(L(2) + U(2))/2];
z1 = L(1)*log(L(1)/L(2));
z2 = U(1)*log(U(1)/L(2));
z3 = L(1)*log(L(1)/U(2));
z4 = U(1)*log(U(1)/U(2));
zm = pm(1)*log(pm(1)/pm(2));
g1 = [log(L(1)/L(2)) + 1;-L(1)/L(2)];
g2 = [log(U(1)/L(2)) + 1;-U(1)/L(2)];
g3 = [log(L(1)/U(2)) + 1;-L(1)/U(2)];
g4 = [log(U(1)/U(2)) + 1;-U(1)/U(2)];
gm = [log(pm(1)/pm(2)) + 1;-pm(1)/pm(2)];
%sdpvar x y z
%C = [max([z1 z2 z3 z4]) > z > z1 + g1'*([x;y] - p1),z > z2 + g2'*([x;y] - p2), z > z3 + g3'*([x;y] - p3),z > z4 + g4'*([x;y] - p4),[x y]>U, L < [x y]]
Ax = [0 0;g1';g2';g3';g4';gm'];%;eye(2);-eye(2)];
Ay = [1;-1;-1;-1;-1;-1];%;0;0;0;0];
b = [max([z1 z2 z3 z4]);g1'*p1-z1;g2'*p2-z2;g3'*p3-z3;g4'*p4-z4;gm'*pm-zm];%;U(:);-L(:)];
xL = L(1);
yL = L(2);
xU = U(1);
yU = U(2);
p1 = [xL;yL;z1];
p2 = [xU;yL;z2];
p3 = [xL;yU;z3];
p4 = [xU;yU;z4];
U = max([z1 z2 z3 z4]);
H1 = null([p2-p1 p3-p1]')';
H2 = null([p3-p2 p4-p2]')';
A = [H1;H2];
b = [b;H1*p1;H2*p2];
Ax = [Ax;A(:,1:2)];
Ay = [Ay;A(:,3)];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
crossentropy.m
|
.m
|
LMI-Matlab-master/yalmip/operators/crossentropy.m
| 1,815 |
utf_8
|
dd20a786dd2a42dbd13576cf33b307b0
|
function varargout = crossentropy(varargin)
% CROSSENTROPY
%
% y = CROSSENTROPY(x,y)
%
% Computes/declares cross entropy -sum(x.*log(y))
%
% See also ENTROPY, KULLBACKLEIBLER
switch class(varargin{1})
case 'double'
if nargin == 1
% YALMIP flattens internally to [x(:);y(:)]
z = varargin{1};
z = reshape(z,[],2);
x = z(:,1);
y = z(:,2);
else
x = varargin{1}(:);
y = varargin{2}(:);
end
ce = x(:).*log(y(:));
ce(x==0) = 0;
ce = real(ce);
varargout{1} = -sum(ce);
case {'sdpvar','ndsdpvar'}
varargin{1} = reshape(varargin{1},[],1);
varargin{2} = reshape(varargin{2},[],1);
if length(varargin{1})~=length(varargin{2})
if length(varargin{1})==1
varargin{1} = repmat(varargin{1},length(varargin{2}),1);
elseif length(varargin{2})==1
varargin{2} = repmat(varargin{2},length(varargin{1}),1);
else
error('Dimension mismatch in crossentropy')
end
end
varargout{1} = yalmip('define',mfilename,[varargin{1};varargin{2}]);
case 'char'
X = varargin{3};
F = [X >= 0];
operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
operator.range = [-inf inf];
operator.domain = [0 inf];
operator.derivative = @derivative;
varargout{1} = F;
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/CROSSENTROPY called with CHAR argument?');
end
function df = derivative(x)
z = reshape(x,[],2);
x = z(:,1);
y = z(:,2);
df = [-log(y);-x./y];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
max_internal.m
|
.m
|
LMI-Matlab-master/yalmip/operators/max_internal.m
| 2,193 |
utf_8
|
1e843d6b9fb476c9c4d77aa38e2f6171
|
function varargout = max_internal(varargin)
switch class(varargin{1})
case 'double'
varargout{1} = max(varargin{:});
case 'char'
extstruct.var = varargin{2};
extstruct.arg = {varargin{3:end}};
[F,properties,arguments]=max_model([],varargin{1},[],extstruct);
varargout{1} = F;
varargout{2} = properties;
varargout{3} = arguments;
otherwise
end
function [F,properties,arguments]=max_model(X,method,options,extstruct)
switch method
case 'graph'
t = extstruct.var;
X = extstruct.arg{1};
basis = getbase(X);
inf_row = find(basis(:,1) == -inf);
if length(inf_row)>0
X(inf_row) = [];
end
F = t-X>= 0;
arguments = X(:);
properties = struct('convexity','convex','monotonicity','increasing','definiteness','none');
case 'exact'
arguments = [];
F = ([]);
t = extstruct.var;
X = extstruct.arg{1};
basis = getbase(X);
inf_row = find(basis(:,1) == -inf);
if length(inf_row)>0
X(inf_row) = [];
end
X = reshape(X,length(X),1);
if prod(size(X)) == 1
F = F + (X == t);
elseif (prod(size(X)) == 2) & ((nnz(basis(1,:))==0) | (nnz(basis(2,:))==0))
% Special case to test a particular problem max(0,y), so we
% keep it since it is optimized
if (nnz(basis(2,:))==0)
X = [0 1;1 0]*X;
end
[M,m] = derivebounds(X);
d = binvar(1,1);
F = F + (m(1) <= t <= m(1) + (M(2)-m(1))*d);
F = F + (0 <= t-X(2) <= (m(1)-m(2))*(1-d));
elseif all(ismember(getvariables(X),yalmip('binvariables'))) & (is(X,'lpcone') | is(X,'sdpcone'))
% Special case max(x) where x is simple binary
F = [F, X <= t, sum(X) >= t];
else
F = max_integer_model(X,t);
end
arguments = [arguments;X(:)];
properties = struct('convexity','convex','monotonicity','increasing','definiteness','none','model','integer');
otherwise
F = [];
return
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
expexpintinv.m
|
.m
|
LMI-Matlab-master/yalmip/operators/expexpintinv.m
| 842 |
utf_8
|
2befcb9c4f10aff4f339806f9a4828a5
|
function varargout = expexpintinv(varargin)
%EXPINT (overloaded)
switch class(varargin{1})
case 'double'
z = varargin{1};
varargout{1} = exp(1./z).*expint(1./z);
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
varargout{1} = [];
varargout{2} = createOperator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/EXPINTINV called with CHAR argument?');
end
function operator = createOperator
operator = struct('convexity','concave','monotonicity','increasing','definiteness','positive','model','callback');
operator.derivative = @derivative;
operator.range = [0 inf];
operator.domain = [1e-8 inf];
function d = derivative(z);
d = (-1./z.^2).*exp(1./z).*expint(1./z)+exp(1./z).*(-z.*exp(-1./z)).*(-1./z.^2);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
logistic.m
|
.m
|
LMI-Matlab-master/yalmip/operators/logistic.m
| 1,787 |
utf_8
|
7db6dafadc94775db52ca52054d9f148
|
function varargout = logistic(varargin)
% LOGISTIC Returns logistic function 1./(1+exp(-x))
%
% y = LOGISTIC(x)
%
% For a real vector x, LOGISTIC returns (1+exp(-x)).^-1
switch class(varargin{1})
case 'double'
x = varargin{1};
varargout{1} = 1./(1+exp(-x));
case 'sdpvar'
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
case 'char'
[M,m] = derivebounds(varargin{3});
if m >= 0
operator = struct('convexity','concave','monotonicity','increasing','definiteness','positive','model','callback');
elseif M <= 0
operator = struct('convexity','convex','monotonicity','increasing','definiteness','positive','model','callback');
else
operator = struct('convexity','none','monotonicity','increasing','definiteness','positive','model','callback');
end
operator.convexhull = @convexhull;
operator.bounds = @bounds;
operator.derivative = @(x)logistic(x).*(1-logistic(x));
operator.range = [0 1];
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/EXP called with CHAR argument?');
end
% Bounding functions for the branch&bound solver
function [L,U] = bounds(xL,xU)
L = 1./(1+exp(-xL));
U = 1./(1+exp(-xU));
function [Ax, Ay, b, K] = convexhull(xL,xU)
if xU <=0
fL = logistic(xL);
fU = logistic(xU);
dfL = fL*(1-fL);
dfU = fU*(1-fU);
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
plot(polytope([Ax Ay],b));
elseif xL>=0
fL = logistic(xL);
fU = logistic(xU);
dfL = fL*(1-fL);
dfU = fU*(1-fU);
[Ax,Ay,b] = convexhullConcave(xL,xU,fL,fU,dfL,dfU);
else
Ax = [];
Ay = [];
b = [];
end
K = [];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
slog.m
|
.m
|
LMI-Matlab-master/yalmip/operators/slog.m
| 2,540 |
utf_8
|
337f77232e578d581ec03cc60aaec8a1
|
function varargout = slog(varargin)
%ENTROPY
%
% y = SLOG(x)
%
% Computes/declares concave shifted logarithm log(1+x)
%
% Implemented as evalutation based nonlinear operator. Hence, the concavity
% of this function is exploited to perform convexity analysis and rigorous
% modelling. Implemented in order to avoid singularities in logarithm
% evaluation.
switch class(varargin{1})
case 'double'
x = varargin{1};
varargout{1} = log(abs(1+x)+sqrt(eps));
case 'sdpvar'
varargout{1} = check_for_special_cases(varargin{:});
if isempty(varargout{1})
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
end
case 'char'
X = varargin{3};
F = (X >= -1+eps);
operator = struct('convexity','concave','monotonicity','increasing','definiteness','none','model','callback');
operator.convexhull = @convexhull;
operator.range = [-inf inf];
operator.domain = [-1 inf];
operator.derivative = @(x) (1./(abs(1+x)+sqrt(eps)));
varargout{1} = F;
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/SLOG called with CHAR argument?');
end
function f = check_for_special_cases(g);
f = [];
% Check for slog(1+a(x)/y)
vars = getvariables(g);
[mt,variabletype] = yalmip('monomtable');
% All signomials
if all(variabletype(vars)==4)
% All xi/yi
local_mt = mt(vars,:);
for i = 1:size(local_mt,1)
if nnz(local_mt(i,:) < 0) ~= 1
return
end
if nnz(local_mt(i,:)) >2
return
end
if ~all(ismember(local_mt(i,:),[-1 0 1]))
return
end
end
% OK, everything is xi/yi
for i = 1:length(g)
gi = extsubsref(g,i);
[~,common] = find(mt(getvariables(gi),:) < 0);
y = recover(common(1));
x = gi*y;
if length(g)==1
% Testing some display issues
f =slogfrac([x;y]);
else
f = [f;slogfrac([x;y])];
end
end
else
return
end
function [Ax, Ay, b, K] = convexhull(xL,xU)
K = [];
if 1+xL <= 0
fL = inf;
else
fL = log(1+xL);
end
fU = log(1+xU);
dfL = 1/(1+xL);
dfU = 1/(1+xU);
xM = (xU + xL)/2;
fM = log(1+xM);
dfM = 1/(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
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
pexp.m
|
.m
|
LMI-Matlab-master/yalmip/operators/pexp.m
| 1,269 |
utf_8
|
f334c5023924d04359e729add5b1df1d
|
function varargout = pexp(varargin)
%PEXP
%
% y = PEXP(x)
%
% Computes perspective exp, x(1)*exp(x(2)/x(1)) on x>0
%
% Implemented as evalutation based nonlinear operator. Hence, the convexity
% of this function is exploited to perform convexity analysis and rigorous
% modelling.
switch class(varargin{1})
case 'double'
if ~isequal(prod(size(varargin{1})),2)
error('PEXP only defined for 2x1 arguments');
end
x = varargin{1};
varargout{1} = x(1)*exp(x(2)/x(1));
case 'sdpvar'
if ~isequal(prod(size(varargin{1})),2)
error('PLOG only defined for 2x1 arguments');
else
varargout{1} = yalmip('define',mfilename,varargin{1});
end
case 'char'
X = varargin{3};
operator = struct('convexity','convex','monotonicity','none','definiteness','positive','model','callback');
operator.range = [0 inf];
operator.domain = [0 inf];
operator.derivative = @derivative;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/PEXP called with CHAR argument?');
end
function dp = derivative(x)
z = x(2)/x(1);
dp = [exp(z)-z*exp(z);exp(z)];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
acos_internal.m
|
.m
|
LMI-Matlab-master/yalmip/operators/acos_internal.m
| 879 |
utf_8
|
1e3261fde0507f4701cb739fbb4be919
|
function varargout = acos_internal(varargin)
%ACOS (overloaded)
switch class(varargin{1})
case 'double'
x = varargin{1};
y = acos(x);
y(x<-1) = pi;
y(x>1) = 0;
varargout{1} = y;
case 'char'
operator = struct('convexity','none','monotonicity','decreasing','definiteness','none','model','callback');
operator.convexhull = [];
operator.bounds = @bounds;
operator.derivative = @derivative;
operator.range = [-pi/2 pi/2];
operator.domain = [-1 1];
varargout{1} = [];
varargout{2} = operator;
varargout{3} = varargin{3};
otherwise
error('SDPVAR/ACOS called with CHAR argument?');
end
function [L,U] = bounds(xL,xU)
L = real(acos(xU));
U = real(acos(xL));
function df = derivative(x)
df = (-(1 - x.^2).^-0.5);
df(x>1) = 0;
df(x<1) = 0;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
implies_internal.m
|
.m
|
LMI-Matlab-master/yalmip/operators/implies_internal.m
| 5,075 |
utf_8
|
e53fb93c351693a8fa46d1e56ec7162a
|
function varargout = implies_internal(varargin)
X = varargin{1};
Y = varargin{2};
if nargin == 2
zero_tolerance = 1e-5;
else
zero_tolerance = varargin{3};
end
% Normalize
if isa(X,'constraint')
X = lmi(X,[],[],1);
end
if isa(Y,'constraint')
Y = lmi(Y,[],[],1);
end
% % Special case something implies binary == 1
% if isa(Y,'lmi') && length(Y)==1 & isa(Y,'equality')
% y = sdpvar(Y);
% if isa(y,'binary') && getbase(y)==[1 -1] | getbase(y)==[-1 1]
%
% end
% end
if isa(X,'sdpvar') & isa(Y,'sdpvar')
varargout{1} = (Y >= X);
elseif isa(X,'sdpvar') & isa(Y,'lmi')
varargout{1} = binary_implies_constraint(X,Y);
elseif isa(X,'lmi') & isa(Y,'sdpvar')
varargout{1} = constraint_implies_binary(X,Y,zero_tolerance);
elseif isa(X,'lmi') & isa(Y,'lmi')
% Glue them using a binary
binvar d
varargout{1} = [constraint_implies_binary(X,d,zero_tolerance), binary_implies_constraint(d,Y)];
end
function F = binary_implies_constraint(X,Y)
if isempty(Y) | length(Y)==0
F = [];
return
end
switch settype(Y)
case 'multiple'
% recursive call if we have a mixture
Y1 = Y(find(is(Y,'equality')));
Y2 = Y(find(is(Y,'elementwise')));
Y3 = Y(find(is(Y,'socp')));
Y4 = Y(find(is(Y,'sdp')));
F = [binary_implies_constraint(X,Y1),
binary_implies_constraint(X,Y2),
binary_implies_constraint(X,Y3),
binary_implies_constraint(X,Y4)];
case 'elementwise' % X --> (Y(:)>=0)
Y = sdpvar(Y);
Y = Y(:);
F = binary_implies_linearnegativeconstraint(-Y,X);
case 'equality' % X --> (Y(:)==0)
Y = sdpvar(Y);
Y = Y(:);
[M,m,infbound]=derivebounds(Y);
if infbound
warning('You have unbounded variables in IMPLIES leading to a lousy big-M relaxation.');
end
F = binary_implies_linearnegativeconstraint(Y,X(:),M,m);
F = [F, binary_implies_linearnegativeconstraint(-Y,X(:),-m,-M)];
case 'sdp' % X --> (Y>=0)
if length(X)>1
error('IMPLIES not implemented for vector x implies lmi.');
end
Y = sdpvar(Y);
% Elements in matrix
y = Y(find(triu(ones(length(Y)))));
% Derive bounds on all elements
[M,m,infbound]=derivebounds(y);
if infbound
warning('You have unbounded variables in IMPLIES leading to a lousy big-M relaxation.');
end
% Crude lower bound eig(Y) > -max(abs(Y(:))*n*I
m=-max(abs([M;m]))*length(Y);
% Big-M relaxation...
F = [Y >= (1-X)*m*eye(length(Y))];
otherwise
error('IMPLIES only implemented for linear (in)equalities and semidefinite constraints');
end
function F = constraint_implies_binary(X,Y,zero_tolerance)
switch settype(X)
case 'multiple'
X1 = X(find(is(X,'equality')));
X2 = X(find(is(X,'elementwise')));
if length(X1)+length(X2) < length(X)
disp('Binary variables can only be activated by linear (in)equalities in IMPLIES');
end
d1 = binvar(length(Y),1);
d2 = binvar(length(Y),1);
F1 = constraint_implies_binary(X1,d1,zero_tolerance);
F2 = constraint_implies_binary(X2,d2,zero_tolerance);
F = [F1, F2, Y >= d1+d2-1];
case 'elementwise'
X = -sdpvar(X);
if length(Y)==length(X)
% Elementwise implies, either by user or internally
F = linearnegativeconstraint_implies_binary(X,Y,[],[],zero_tolerance);
elseif length(Y)== 1
% Many rows should imply one. Create intermediate and use AND
d = binvar(length(X),1);
F = [linearnegativeconstraint_implies_binary(X,d,[],[],zero_tolerance), Y >= sum(d)+1-length(X)];
else
error('Inconsistent sizes in implies_internal')
end
case 'equality'
X = sdpvar(X);
n = length(X);
if isequal(getbase(X),[-ones(n,1) eye(n)]) | isequal(getbase(X),[ones(n,1) -eye(n)]) & all(ismember(depends(X),yalmip('binvariables')));
% Smart code for X == 1 implies Y
F = [Y(:) >= recover(getvariables(X))];
else
d = binvar(length(X),2,'full');
%F = linearnegativeconstraint_implies_binary([-zero_tolerance-X;X-zero_tolerance],[d(:,1);d(:,2)],[],[],zero_tolerance);
F = linearnegativeconstraint_implies_binary([-zero_tolerance-X;X-zero_tolerance],[d(:,1);d(:,2)],[],[],zero_tolerance/100);
if length(X)==length(Y)
% elementwise version
F = [F, Y >= d(:,1)+d(:,2)-1];
elseif length(Y)==1
% All elements must be zero
F = [F, Y >= sum(sum(d))-2*length(X)+1];
else
error('Inconsistent sizes in implies_internal')
end
end
otherwise
disp('IMPLIES not implemented for this case');
error('IMPLIES not implemented for this case');
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
cpower.m
|
.m
|
LMI-Matlab-master/yalmip/operators/cpower.m
| 2,821 |
utf_8
|
7da9a3176a88314e9825801fed666649
|
function varargout = cpower(varargin)
%CPOWER Power of SDPVAR variable with convexity knowledge
%
% CPOWER is recommended if your goal is to obtain
% a convex model, since the function CPOWER is implemented
% as a so called nonlinear operator. (For p/q ==2 you can
% however just as well use the overloaded power)
%
% t = cpower(x,p/q)
%
% For negative p/q, the operator is convex.
% For positive p/q with p>q, the operator is convex.
% For positive p/q with p<q, the operator is concave.
%
% A domain constraint x>0 is automatically added if
% p/q not is an even integer.
%
% Note, the complexity of generating the conic representation
% of these variables are O(2^L) where L typically is the
% smallest integer such that 2^L >= min(p,q)
switch class(varargin{1})
case 'double'
varargout{1} = power(varargin{1},varargin{2});
case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.
X = varargin{1};
if isreal(X)
dim = size(X);
X = reshape(X,prod(dim),1);
y = [];
for i = 1:prod(dim)
y = [y;yalmip('define',mfilename,extsubsref(X,i),varargin{2})];
end
y = reshape(y,dim);
varargout{1} = y;
else
error('CPOWER can only be applied to real vectors.');
end
case 'char' % YALMIP send 'model' when it wants the epigraph or hypograph
if isequal(varargin{1},'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.
p = varargin{4};
if p>0
[p,q] = rat(abs(p));
F = pospower(X,t,p,q);
if p>q
convexity = 'convex';
monotonicity = 'increasing';
else
convexity = 'concave';
monotonicity = 'decreasing';
end
else
[p,q] = rat(abs(p));
F = negpower(X,t,p,q);
convexity = 'convex';
monotonicity = 'decreasing';
end
varargout{1} = F;
varargout{2} = struct('convexity',convexity,'monotonicity',monotonicity,'definiteness','positive','model','graph');
varargout{3} = X;
end
otherwise
end
function F = pospower(x,t,p,q)
if p>q
l = ceil(log2(abs(p)));
r = 2^l-p;
y = [ones(r,1)*x;ones(q,1)*t;ones(2^l-r-q,1)];
F = detset(x,y);
else
l = ceil(log2(abs(q)));
y = [ones(p,1)*x;ones(2^l-q,1)*t;ones(q-p,1)];
F = detset(t,y);
end
function F = negpower(x,t,p,q)
l = ceil(log2(abs(p+q)));
p = abs(p);
q = abs(q);
y = [ones(2^l-p-q,1);ones(p,1)*x;ones(q,1)*t];
F = detset(1,y);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
min_internal.m
|
.m
|
LMI-Matlab-master/yalmip/operators/min_internal.m
| 1,846 |
utf_8
|
000eee732402247d0ba89563345fdef3
|
function varargout = min_internal(varargin)
switch class(varargin{1})
case 'double'
varargout{1} = min(varargin{:});
case 'char'
extstruct.var = varargin{2};
extstruct.arg = {varargin{3:end}};
[F,properties,arguments]=min_model([],varargin{1},[],extstruct);
varargout{1} = F;
varargout{2} = properties;
varargout{3} = arguments;
otherwise
end
function [F,properties,arguments] = min_model(X,method,options,extstruct)
switch method
case 'graph'
arguments=[];
F = ([]);
basis = getbase(extstruct.arg{1});
inf_row = find(basis(:,1) == inf);
if length(inf_row)>0
extstruct.arg{1}(inf_row) = [];
end
F = F + (extstruct.arg{1} - extstruct.var >= 0);
arguments= [arguments;extstruct.arg{1}(:)];
properties = struct('convexity','concave','monotonicity','increasing','definiteness','none');
case 'exact'
arguments = [];
t = extstruct.var;
X = extstruct.arg{1};
basis = getbase(X);
inf_row = find(basis(:,1) == inf);
if length(inf_row)>0
X(inf_row) = [];
end
X = reshape(X,length(X),1);
if prod(size(X)) == 1
F = [X == t];
elseif all(ismember(getvariables(X),yalmip('binvariables'))) & (is(X,'lpcone') | is(X,'sdpcone'))
% Special case min(x) where x is simple binary
F = [X >= t, sum(X) <= t+length(X)-1];
else
F = max_integer_model(-X,-t);
end
arguments = [arguments;X(:)];
properties = struct('convexity','concave','monotonicity','increasing','definiteness','none','model','integer');
otherwise
F = [];
return
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
power_internal1.m
|
.m
|
LMI-Matlab-master/yalmip/operators/power_internal1.m
| 2,439 |
utf_8
|
8fdb9032081e36221ef83491e13f0ea4
|
function varargout = power_internal1(varargin)
%power_internal1
% Used for cases such as 2^x, and is treated as evaluation-based operators
switch class(varargin{1})
case 'double'
varargout{1} = varargin{2}.^varargin{1};
case 'sdpvar'
if isa(varargin{2},'sdpvar')
x = varargin{2};
y = varargin{1};
varargout{1} = exp(y*log(x)); %x^y = exp(log(x^y))
else
if length(varargin{1}) > 1 || size(varargin{2},1) ~= size(varargin{2},2)
error('Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead.');
end
x = varargin{2};
y = varargin{1};
if isa(x,'double') && x==1 && length(y)==1
varargout{1} = 1;
else
varargout{1} = InstantiateElementWise(mfilename,varargin{:});
end
end
case 'char'
X = varargin{3};
Y = varargin{4};
F=[];
if Y>=1
operator = struct('convexity','none','monotonicity','increasing','definiteness','positve','model','callback');
elseif Y>=0
operator = struct('convexity','none','monotonicity','decreasing','definiteness','positive','model','callback');
else
% Base is negative, so the power has to be an integer
F = (integer(X));
operator = struct('convexity','none','monotonicity','decreasing','definiteness','none','model','callback');
end
operator.bounds = @bounds_power;
operator.convexhull = @convexhull_power;
operator.derivative = @(x)derivative(x,Y);
varargout{1} = F;
varargout{2} = operator;
varargout{3} = [X(:);Y(:)];
otherwise
error('SDPVAR/power_internal1 called with CHAR argument?');
end
% This should not be hidden here....
function [L,U] = bounds_power(xL,xU,base)
if base >= 1
L = base^xL;
U = base^xU;
elseif base>= 0
L = base^xU;
U = base^xL;
else
disp('Not implemented yet. Report bug if you need this')
error
end
function df = derivative(x,base)
if length(base)~=length(x)
base = base*ones(size(x));
end
f = base.^x;
df = log(base)*f;
function [Ax, Ay, b] = convexhull_power(xL,xU,base)
fL = base^xL;
fU = base^xU;
dfL = log(base)*fL;
dfU = log(base)*fU;
[Ax,Ay,b] = convexhullConvex(xL,xU,fL,fU,dfL,dfU);
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
pnorm.m
|
.m
|
LMI-Matlab-master/yalmip/operators/pnorm.m
| 3,905 |
utf_8
|
6ea7721daa042f84ee690bffafed5bdf
|
function varargout = pnorm(varargin)
%PNORM P-Norm of SDPVAR variable with convexity knowledge
%
% PNORM is recommended if your goal is to obtain
% a convex model, since the function PNORM is implemented
% as a so called nonlinear operator. (For p/q ==1,2,inf you should use the
% overloaded norm)
%
% t = pnorm(x,p/q), p/q >= 1
%
% Note, the pnorm is implemented using cpower, which adds
% a large number of variables and constraints
switch class(varargin{1})
case 'double'
varargout{1} = sum(varargin{1}.^varargin{2}).^(1/varargin{2});
case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them.
X = varargin{1};
[n,m] = size(X);
if isreal(X) & min(n,m)==1
if varargin{2}>=1
varargout{1} = yalmip('define',mfilename,varargin{:});
else
error('PNORM only applicable for p>=1');
end
else
error('PNORM can only be applied to real vectors.');
end
case 'char' % YALMIP send 'model' when it wants the epigraph or hypograph
if isequal(varargin{1},'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.
p = varargin{4};
% sum(|xi|^(l/m))^(l/m) < t
% si>0
% -t^({l-m}/m)si^(m/l) < -xi
% -t^({l-m}/m)si^(m/l) < xi
%sum(si) < t
% t>0
if 0
[p,q] = rat(p);
absX = sdpvar(length(X),1);
y = sdpvar(length(X),1);
F = [-absX < X < absX];
for i = 1:length(y)
F = [F,pospower(absX(i),y(i),p,q)];
end
F = [F,pospower(t,sum(y),q,p)];
else
[l,m] = rat(p);
% l=4
% m = 1
% x<(t^(l-m)*s^m)^1/l
% -x<(t^(l-m)*s^m)^1/l
% x < t t t s
if 2^fix(log2(l))==l & m == 1
s=sdpvar(length(X),1);
absX = sdpvar(length(X),1);
F = [-absX <= X <= absX];
F = [F,sum(s)<= t,s>=0];
for i = 1:length(X)
F = [F,detset(absX(i),[repmat(t,1,l-m) s(i)])];
F = [F,detset(-absX(i),[repmat(t,1,l-m) s(i)])];
end
else
% l = 7
% m = 2
% x < (t t t t t s s)^(1/7)
% x^7 < (t t t t t s s)
% x^8 < (t t t t t s s x)
% x < (t t t t t s s x)^(1/8
s=sdpvar(length(X),1);
w = 2^(ceil(log2(l)));
absX = sdpvar(length(X),1);
F = [-absX <= X <= absX];
F = [F,sum(s)<= t,s>=0];
for i = 1:length(X)
F = [F,detset(absX(i),[repmat(t,1,l-m) repmat(s(i),1,m) repmat(absX(i),1,w-l)])];
F = [F,detset(-absX(i),[repmat(t,1,l-m) repmat(s(i),1,m) repmat(absX(i),1,w-l)])];
end
end
end
varargout{1} = F;
varargout{2} = struct('convexity','convex','monotonicity','none','definiteness','positive','model','graph');
varargout{3} = X;
end
otherwise
end
function F = pospower(x,t,p,q)
if p>q
l = ceil(log2(abs(p)));
r = 2^l-p;
y = [ones(r,1)*x;ones(q,1)*t;ones(2^l-r-q,1)];
F = detset(x,y);
else
l = ceil(log2(abs(q)));
y = [ones(p,1)*x;ones(2^l-q,1)*t;ones(q-p,1)];
F = detset(t,y);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
logsumexp.m
|
.m
|
LMI-Matlab-master/yalmip/operators/logsumexp.m
| 1,345 |
utf_8
|
6b83cc0ac3e1ba57ad80dba22db81d41
|
function varargout = logsumexp(varargin)
%LOGSUMEXP
%
% y = LOGSUMEXP(x)
%
% Computes/declares log of sum of exponentials log(sum(exp(x)))
%
% Implemented as evalutation based nonlinear operator. Hence, the convexity
% of this function is exploited to perform convexity analysis and rigorous
% modelling.
switch class(varargin{1})
case 'double'
x = varargin{1};
varargout{1} = log(sum(exp(x)));
case 'sdpvar'
if min(size(varargin{1}))>1
error('LOGSUMEXP only defined for vector arguments');
elseif max(size(varargin{1}))==1
varargout{1} = varargin{1};
else
varargout{1} = yalmip('define',mfilename,varargin{1});
end
case 'char'
X = varargin{3};
operator = struct('convexity','convex','monotonicity','none','definiteness','none','model','callback');
operator.bounds = @bounds;
operator.derivative = @(x) exp(x)./(sum(exp(x)));
operator.convexhull = @convexhull;
varargout{1} = [];
varargout{2} = operator;
varargout{3} = X;
otherwise
error('SDPVAR/LOG called with CHAR argument?');
end
function [L, U] = bounds(xL,xU)
L = log(sum(exp(xL)));
U = log(sum(exp(xU)));
function [Ax, Ay, b] = convexhull(xL,xU)
Ax = [];
Ay = [];
b = [];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
iff_internal.m
|
.m
|
LMI-Matlab-master/yalmip/operators/iff_internal.m
| 3,921 |
utf_8
|
ae2278fd236008b34aa5db44cc6c4c72
|
function varargout = iff_internal(varargin)
X = varargin{1};
Y = varargin{2};
if nargin == 2
zero_tolerance = 1e-5;
else
zero_tolerance = abs(varargin{3});
end
% Normalize data
if isa(Y,'constraint')
Y=lmi(Y,[],[],1);
end
if isa(X,'constraint')
X=lmi(X,[],[],1);
end
if isa(X,'lmi') & isa(Y,'sdpvar')
temp = X;
X = Y;
Y = temp;
end
if isa(X,'sdpvar') & isa(Y,'sdpvar')
% user presumably works with binary variables
varargout{1} = [Y == X];
elseif (isa(X,'sdpvar') & isa(Y,'lmi'))
% Binary variable iff a constraint holds
switch settype(Y)
case 'elementwise' % binary X <--> Y(:)>=0
varargout{1} = binary_iff_lp(X,-sdpvar(Y),zero_tolerance);
case 'equality'
varargout{1} = binary_iff_equality(X,sdpvar(Y),zero_tolerance);
case 'multiple'
Y1 = Y(find(is(Y,'equality')));
Y2 = Y(find(is(Y,'elementwise')));
% Glue using intermediate variables holding truth of each set
% of constraints. X is true iff both di are true and v.v.
% Hence, we make a recursive call with two new models
binvar d1 d2
C1 = iff_internal(d1,Y1,zero_tolerance);
C2 = iff_internal(d2,Y2,zero_tolerance);
C3 = [X <= d1,X <= d2,X >= d1+d2-1];
varargout{1} = [C1, C2, C3];
% varargout{1} = [iff_internal(X,Y1),iff_internal(X,Y2)];
otherwise
error('IFF not implemented for this case');
end
elseif isa(X,'lmi') & isa(Y,'lmi')
% Constraint holds iff constraint holds.
% Glue using an intermediate variable
binvar d
C1 = iff_internal(d,X,zero_tolerance);
C2 = iff_internal(d,Y,zero_tolerance);
varargout{1} = [C1,C2];
end
function F = binary_iff_lp(X,f,zero_tolerance)
% X == 1 <=> f<=0
[M,m,infbound] = derivebounds(f);
if infbound
warning('You have unbounded variables in IFF leading to a lousy big-M relaxation.');
end
[nf,mf]=size(f);
if nf*mf==1
F = linearnegativeconstraint_iff_binary(f,X,M,m,zero_tolerance);
else
f = reshape(f,nf*mf,1);
di = binvar(nf*mf,1);
F = linearnegativeconstraint_iff_binary(f,di,M,m,zero_tolerance);
if length(X)==1
% X is true if any di
F = [F, X>=sum(di)-length(di)+1, X <= di];
else
% This must be a vectorized X(i) iff f(i)
F = [F, di == X];
end
% di=0 means the ith hypeplane is violated
% X=1 means we are in the polytope
% F = [f <= M*(1-X), f>=eps+(m-eps).*di, X>=sum(di)-length(di)+1, X <= di];
% Add some cuts for c < a'x+b < d
[bA] = getbase(f);
b = bA(:,1);
A = bA(:,2:end);
S = zeros(0,length(di));
for i = 1:length(b)
j = findrows(abs(A),abs(A(i,:)));
j = j(j > i);
if length(j)==1
S(end+1,[i j]) = 1;
end
end
if size(S,1) > 0
% Add cut cannot be outside both constraints
F = F + (S*di >= 1);
end
end
function F = binary_iff_equality(X,Y,zero_tolerance)
Y = Y(:);
d = binvar(length(Y),3);
% We have to model every single line of equality.
% di1 : Yi < -eps
% di2 : -eps < Yi < eps
% di3 : eps < Yi
C = sum(d,2)==1;
[M,m,infbounds] = derivebounds(Y);
for i = 1:length(Y)
if all(ismember(depends(Y(i)),yalmip('binvariables'))) & all(getbase(Y(i))==fix(getbase(Y(i))))
eps = 0.5;
else
eps = 0;
end
C1 = binary_iff_lp(d(i,1),Y(i)+eps,abs(zero_tolerance)); % Y <-eps
C2 = binary_iff_lp(d(i,2),[Y(i)-eps;-eps-Y(i)],abs(zero_tolerance)); % -eps < Y < eps
C3 = binary_iff_lp(d(i,3),eps-Y(i),abs(zero_tolerance)); % eps < Y
C = [C, C1,C2,C3];
% Cut off some trivial cases
if m(i)>=0
C = [C,d(i,1)==0];
elseif M(i)<=0
C = [C,d(i,3)==0];
end
end
% X is true if all di2 are true and v.v
F = [C,X <= d(:,2), X >= sum(d(:,2))-length(Y)+1];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
veccomplex.m
|
.m
|
LMI-Matlab-master/sedumi/veccomplex.m
| 2,989 |
utf_8
|
591fbdddd59de32e4e5fd57b33ebc1d7
|
function z = veccomplex(x,cpx,K)
% z = veccomplex(x,cpx,K)
%
% ********** INTERNAL FUNCTION OF SEDUMI **********
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
z = zeros(length(x) - cpx.dim,1);
dimflqr = K.f+K.l+sum(K.q)+sum(K.r);
rsel = 1:dimflqr;
nfx = length(cpx.f)+length(cpx.x);
imsel = 1:nfx;
imsel = imsel' + [zeros(length(cpx.f),1); vec(cpx.x)];
rsel(imsel) = 0;
z(1:dimflqr-nfx) = x(rsel~=0);
z(cpx.f) = z(cpx.f) + sqrt(-1) * x(imsel(1:length(cpx.f)));
z(cpx.x) = z(cpx.x) + sqrt(-1) * x(imsel(length(cpx.f)+1:end));
% ----------------------------------------
% PSD:
% ----------------------------------------
hfirstk = 1+dimflqr + sum(K.s(1:K.rsdpN).^2); % start of Hermitian blocks
zfirstk = 1+dimflqr - nfx; % start of psd blocks in z
firstk = 1+dimflqr; % start if psd blocks in x
k = 1; sk = 1;
for knz = 1:length(cpx.s)
newk = cpx.s(knz);
if newk > k
len = sum(K.s(sk:sk+newk-k-1).^2);
z(zfirstk:zfirstk+len-1) = x(firstk:firstk+len-1); % copy real PSD blocks
zfirstk = zfirstk + len;
firstk = firstk + len;
sk = sk + newk - k; % handled newk-k real blocks
end
nksqr = K.s(K.rsdpN + knz)^2; % insert a Hermitian block
z(zfirstk:zfirstk+nksqr-1) = x(hfirstk:hfirstk+nksqr-1) ...
+ 1i * x(hfirstk+nksqr: hfirstk+2*nksqr-1);
zfirstk = zfirstk + nksqr;
hfirstk = hfirstk + 2*nksqr;
k = newk + 1; % handled up to block newk.
end
if sk <= K.rsdpN % copy remaining real blocks
len = sum(K.s(sk:K.rsdpN).^2);
z(zfirstk:zfirstk+len-1) = x(firstk:firstk+len-1);
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
prelp.m
|
.m
|
LMI-Matlab-master/sedumi/conversion/prelp.m
| 3,887 |
utf_8
|
4d1e23d094e3f1b35ec666df11a34003
|
% PRELP Loads and preprocesses LP from an MPS file.
%
% > [A,b,c,lenx,lbounds] = PRELP('problemname')
% The above command results in an LP in standard form,
% - Instead of specifying the problemname, you can also use PRELP([]), to
% get the problem from the file /tmp/default.mat.
% - Also, you may type PRELP without any input arguments, and get prompted
% for a name.
%
% MINIMIZE c'*x SUCH THAT A*x = b AND x>= 0.
%
% So, you can solve it with SeDuMi:
% > [x,y,info] = SEDUMI(A,b,c);
%
% After solving, post-process it with
% > [x,objp] = POSTPROCESS(x(1:lenx),lbounds).
%
% REMARK x(lenx+1:length(x)) will contain upper-bound slacks.
%
% IMPORTANT works only if LIPSOL is installed on your system.
%
% See also sedumi, getproblem, postprocess (LIPSOL), frompack, lipsol.
function [A,b,c,lenx,lbounds,times] = prelp(pname)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
global OUTFID
global Ubounds_exist
if ~exist('loadata','file') || ~exist('preprocess','file')
if ~exist('loadata','file') | ~exist('preprocess','file')
error('To use PRELP, you need to have LIPSOL installed.')
end
%--------------------------------------------------
% LOAD LP PROBLEM INTO MEMORY
%--------------------------------------------------
if (nargin == 0)
pname = input('Enter problem name: ','s');
end
[A,b,c,lbounds,ubounds,BIG] = loadata(pname);
t0 = cputime;
[A,b,c,lbounds,ubounds,BIG,NAME] = loadata(pname);
times(1) = cputime - t0;
%--------------------------------------------------
% PREPROCESS LP PROBLEM
% NB: Y.Zhang's preprocess returns lbounds for post-
% processing; the pre-processed problem has x>=0.
%--------------------------------------------------
t0 = cputime;
[A,b,c,lbounds,ubounds,FEASIBLE] = ...
preprocess(A,b,c,lbounds,ubounds,BIG);
if ~FEASIBLE
fprintf('\n');
if isempty(OUTFID)
return;
end;
msginf = 'Infeasibility detected in preprocessing';
fprintf(OUTFID, [pname ' 0 ' msginf '\n']);
return;
end;
%[A,b,c,ubounds] = scaling(A,b,c,ubounds);
%--------------------------------------------------
% INSERT UBOUND- CONSTRAINTS IN THE A-MATRIX
%--------------------------------------------------
b = full(b); c = full(c);
[m,lenx] = size(A);
if Ubounds_exist
nub = nnz(ubounds);
A= [ A sparse(m,nub); sparse(1:nub,find(ubounds),1,nub,lenx) speye(nub) ];
b = [b; nonzeros(ubounds)];
c = [c; zeros(nub,1)];
else
ubounds = [];
end
%--------------------------------------------------
% LOCATE DENSE COLUMNS
%--------------------------------------------------
%checkdense(A);
times(2) = cputime - t0;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
feasreal.m
|
.m
|
LMI-Matlab-master/sedumi/conversion/feasreal.m
| 4,144 |
utf_8
|
454dcb6c42c0642ed5c5a524e84bec58
|
% FEASREAL Generates a random sparse optimization problem with
% linear, quadratic and semi-definite constraints. Output
% can be used by SEDUMI. All data will be real-valued.
%
% The following two lines are typical:
% > [AT,B,C,K] = FEASREAL;
% > [X,Y,INFO] = SEDUMI(AT,B,C,K);
%
% An extended version is:
% > [AT,B,C,K] = FEASREAL(m,lpN,lorL,rconeL,sdpL,denfac)
%
% SEE ALSO sedumi AND feascpx.
function [At,b,c,K] = feasreal(m,nLP,qL,rL,nL,denfac)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
if nargin < 6
denfac = 0.1;
if nargin < 5
nL = 1+ round(7*rand(1,5));
fprintf('Choosing random SDP-product cone K.s.\n')
if nargin < 4
rL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ R-product cone K.r.\n')
if nargin < 3
qL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ-product cone K.q.\n')
if(nargin < 2)
nLP = 10;
fprintf('Choosing default K.l=%3.0f.\n',nLP)
if nargin < 1
m=10;
fprintf('Choosing default m=%3.0f.\n',m)
end
end
end
end
end
end
if isempty(nLP)
nLP = 0;
end
nblk = length(nL) + length(rL) + length(qL) + nLP;
denfac = min(1, max(denfac,2/nblk));
fprintf('Choosing block density denfac=%6.4f per row\n',denfac)
Apattern=sparse(m,nblk);
for j=1:m
pati = sprandn(1,nblk,denfac);
Apattern(j,:) = (pati~= 0);
end
sumnLsqr = sum(nL.^2);
x = zeros(nLP+sum(qL)+sum(rL)+sumnLsqr,1);
x(1:nLP) = rand(nLP,1);
At = sparse(length(x),m);
At(1:nLP,:) = sprandn(Apattern(:,1:nLP)');
firstk = nLP+1;
%[nA, mA] = size(At);
% LORENTZ:
for k=1:length(qL)
nk = qL(k); lastk = firstk + nk - 1;
x(firstk) = rand;
for j=1:m
if Apattern(j,nLP+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk));
end
end
firstk = lastk + 1;
end
% RCONE (Rotated Lorentz):
for k=1:length(rL)
nk = rL(k); lastk = firstk + nk - 1;
x(firstk) = rand; x(firstk+1) = rand;
for j=1:m
if Apattern(j,nLP+length(qL)+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk));
end
end
firstk = lastk + 1;
end
% SDP:
for k=1:length(nL)
nk = nL(k); lastk = firstk + nk*nk - 1;
Xk = diag(rand(nk,1)); % diagonal, to keep sparsity structure
x(firstk:lastk) = Xk; %although symmetric, store nk^2 elts.
for j=1:m
if Apattern(j,nLP+length(qL)+length(rL)+k)==1
Aik = sprandsym(nk,1/nk); %on average 1 nonzero per row
At(firstk:lastk,j) = vec( (Aik+Aik') );
end
end
firstk = lastk + 1;
end
b = full(At'*x);
y = rand(m,1)-0.5;
c = sparse(At*y)+x;
K.l = nLP; K.q = qL; K.r = rL; K.s = nL;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
sdpa2vec.m
|
.m
|
LMI-Matlab-master/sedumi/conversion/sdpa2vec.m
| 2,352 |
utf_8
|
f055b4df357f6cf3b426ce27869bc738
|
% x = sdpavec(E,K)
% Takes an SDPA type sparse data description E, i.e.
% E(1,:) = block, E(2,:) = row, E(3,:) = column, E(4,:) = entry,
% and transforms it into a "long" vector, with vectorized matrices for
% each block stacked under each other. The size of each matrix block
% is given in the field K.s.
% ********** INTERNAL FUNCTION OF SEDUMI **********
function x = sdpa2vec(E,K,invperm)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA %
% ------------------------------------------------------------
% Split E into blocks E[1], E[2], ..., E[length(K.s)]
% ------------------------------------------------------------
[xir,xjc] = sdpasplit(E(1,:),length(K.s));
x = sparse([],[],[],0,0,2*size(E,2));
for knz = 1:length(xir)
permk = xir(knz);
k = invperm(permk);
if k > K.l
k = k - K.l; % matrix
nk = K.s(k);
Ek = E(2:4,xjc(knz):xjc(knz+1)-1);
Xk = sparse(Ek(1,:),Ek(2,:),Ek(3,:),nk,nk);
Xk = Xk + triu(Xk,1)';
x=[x;Xk(:)];
else
x=[x;E(4,xjc(knz))];
end
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
blk2vec.m
|
.m
|
LMI-Matlab-master/sedumi/conversion/blk2vec.m
| 1,653 |
utf_8
|
0d48b96f66e746fce480e7a3e9c271a5
|
% x = blk2vec(X,nL)
%
% Converts a block diagonal matrix into a vector.
%
% ********** INTERNAL FUNCTION OF FROMPACK **********
function x = blk2vec(X,nL)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA %
nblk = length(nL);
sumnk = 0;
x = [];
for k = 1:nblk
nk = nL(k);
x = [x; vec(X(sumnk+1:sumnk + nk,sumnk+1:sumnk + nk))] ;
sumnk = sumnk + nk;
end
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
writesdp.m
|
.m
|
LMI-Matlab-master/sedumi/conversion/writesdp.m
| 4,708 |
utf_8
|
31f196bca4c11b9610c98de8e4d7b107
|
% This function takes a problem in SeDuMi MATLAB format and writes it out
% in SDPpack format.
%
% Usage:
%
% writesdp(fname,A,b,c,K)
%
% fname Name of SDPpack file, in quotes
% A,b,c,K Problem in SeDuMi form
%
% Notes:
%
% Problems with complex data are not allowed.
%
% Rotated cone constraints are not supported.
%
% Nonsymmetric A.s and C.s matrices are symmetrized with A=(A+A')/2
% a warning is given when this happens.
%
% Floating point numbers are written out with 18 decimal digits for
% accuracy.
%
% Please contact the author (Brian Borchers, [email protected]) with any
% questions or bug reports.
%
function writesdp(fname,A,b,c,K)
%From: Brian Borchers[SMTP:[email protected]]
%Sent: Wednesday, December 08, 1999 12:33 PM
%To: [email protected]
%
%Here's a MATLAB routine that will take a problem in SeDuMi's MATLAB format
%and write it out in SDPpack format.
%
% First, check for complex numbers in A, b, or c.
%
if (isreal(A) ~= 1),
disp('A is not real!');
return;
end;
if (isreal(b) ~= 1),
disp('b is not real!');
return;
end;
if (isreal(c) ~= 1),
disp('c is not real!');
return;
end;
%
% Check for any rotated cone constraints.
%
if (isfield(K,'r') && (~isempty(K.r)) && (K.r ~= 0)),
disp('rotated cone constraints are not yet supported.');
return;
end;
%
% Get the size data.
%
if (isfield(K,'l')),
nlin=K.l;
sizelin=nlin;
if (isempty(sizelin)),
sizelin=0;
nlin=0;
end;
else
nlin=0;
sizelin=0;
end;
if (isfield(K,'s')),
nsdpblocks=length(K.s);
%sizesdp=sum((K.s).^2);
%if (isempty(sizesdp)),
%sizesdp=0;
%nsdpblocks=0;
%end;
else
%sizesdp=0;
nsdpblocks=0;
end;
if (isfield(K,'q')),
nqblocks=length(K.q);
sizeq=sum(K.q);
if (isempty(sizeq)),
sizeq=0;
nqblocks=0;
end;
else
nqblocks=0;
sizeq=0;
end;
m=length(b);
%
% Open up the file for writing.
%
fid=fopen(fname,'w');
%
% Print out m, the number of constraints.
%
fprintf(fid,'%d \n',m);
%
% Next, b, with one entry per line.
%
fprintf(fid,'%.18e\n',full(b));
%
% Next, the semidefinite part.
%
if (nsdpblocks == 0),
fprintf(fid,'0\n');
else
%
% Print out the number of semidefinite blocks.
%
fprintf(fid,'%d\n',nsdpblocks);
%
% For each block, print out its size.
%
fprintf(fid,'%d\n',full(K.s));
%
% Next, the cost matrix C.s.
%
%
% First, calculate where in c things start.
%
base=sizelin+sizeq+1;
%
% Next, work through the blocks.
%
for i=1:nsdpblocks,
fprintf(fid,'1\n');
work=c(base:base+K.s(i)^2-1);
if nnz(work ~= work'),
if (work ~= work'),
disp('Non symmetric C.s matrix!');
work=(work+work')/2;
end;
work=triu(work);
[II,JJ,V]=find(work);
cnt=length(II);
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
%
% Next, update to the next base.
%
base=base+K.s(i)^2;
end;
%
% Now, loop through the constraints, one at a time.
%
for cn=1:m,
%
% Print out the SDP part of constraint cn.
%
base=sizelin+sizeq+1;
for i=1:nsdpblocks,
fprintf(fid,'1\n');
if nnz(work ~= work'),
work=reshape(work,K.s(i),K.s(i));
if (work ~= work'),
disp('Non symmetric A.s matrix!');
work=(work+work')/2;
end;
work=triu(work);
[II,JJ,V]=find(work);
cnt=length(II);
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
%
% Next, update to the next base.
%
base=base+K.s(i)^2;
end;
%
% Done with constraint cn
%
end;
%
% Done with SDP part.
%
end;
%
% Next, handle the Quadratic part.
%
%
% Describe the Q blocks.
%
if (nqblocks == 0),
fprintf(fid,'0\n');
else
fprintf(fid,'%d\n',nqblocks);
fprintf(fid,'%d\n',full(K.q));
%
% Find C.q.
%
base=sizelin+1;
cq=c(base:base+sizeq-1);
%
% Print out the C.q coefficients.
%
fprintf(fid,'%.18e\n',full(cq));
%
% Next, the constraint matrix A.q.
%
Aq=A(:,base:base+sizeq-1);
%
% Print out the count of nonzeros.
%
[II,JJ,V]=find(Aq);
cnt=length(II);
fprintf(fid,'1\n');
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
%
% End of handling quadratic part.
%
end;
%
%
% Finally, handle the linear part.
%
if (nlin == 0),
fprintf(fid,'0\n');
else
%
% Print out the number of linear variables.
%
fprintf(fid,'%d\n',nlin);
%
% Print out C.l
%
fprintf(fid,'%.18e\n',full(c(1:nlin)));
%
% Print out the A matrix.
%
Al=A(:,1:nlin);
[II,JJ,V]=find(Al);
cnt=length(II);
fprintf(fid,'1\n');
fprintf(fid,'%d\n',cnt);
if (cnt ~= 0),
fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]');
end;
end;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
frompack.m
|
.m
|
LMI-Matlab-master/sedumi/conversion/frompack.m
| 2,509 |
utf_8
|
a4730dcb4ec069944953dce753da973d
|
% FROMPACK Converts a cone problem in SDPPACK format to SEDUMI format.
%
% [At,c] = frompack(A,b,C,blk) Given a problem (A,b,C,blk) in the
% SDPPACK-0.9-beta format, this produces At and c for use with
% SeDuMi. This lets you execute
%
% [x,y,info] = SEDUMI(At,b,c,blk);
%
% IMPORTANT: this function assumes that the SDPPACK function `smat'
% exists in your search path.
%
% SEE ALSO sedumi.
function [At,c] = frompack(A,b,C,blk)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
m = length(b);
% ----------------------------------------
% In SDPPACK, 0s are sometimes used as emptyset and vice versa.
% ----------------------------------------
if blk.l == 0
A.l = []; C.l = [];
end
if isempty(blk.q)
A.q = []; C.q = [];
end
if isempty(blk.s)
A.s = []; C.s = [];
end
% ----------------------------------------
% SDP:
% ----------------------------------------
Asdp = [];
if sum(blk.s) == 0
csdp = [];
else
for i=1:m
Asdp = [Asdp blk2vec( smat(sparse(A.s(i,:)),blk.s), blk.s ) ];
end
csdp = blk2vec(C.s,blk.s);
end
% ----------------------------------------
% Assemble LP, LORENTZ and SDP.
%----------------------------------------
At = [A.l'; A.q'; Asdp];
c = [C.l; C.q; csdp];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
feascpx.m
|
.m
|
LMI-Matlab-master/sedumi/conversion/feascpx.m
| 4,385 |
utf_8
|
c48c6cf336cdb94ad12b04e1efd2417b
|
% FEASCPX Generates a random sparse optimization problem with
% linear, quadratic and semi-definite constraints. Output
% can be used by SEDUMI. Includes complex-valued data.
%
% The following two lines are typical:
% > [AT,B,C,K] = FEASCPX;
% > [X,Y,INFO] = SEDUMI(AT,B,C,K);
%
% An extended version is:
% > [AT,B,C,K] = FEASCPX(m,lpN,lorL,rconeL,sdpL,denfac)
%
% SEE ALSO sedumi AND feasreal.
function [At,b,c,K] = feascpx(m,nLP,qL,rL,nL,denfac)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%
if nargin < 6
denfac = 0.1;
if nargin < 5
nL = 1+ round(7*rand(1,5));
fprintf('Choosing random SDP-product cone K.s.\n')
if nargin < 4
rL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ R-product cone K.r.\n')
if nargin < 3
qL = 3 + round(4*rand(1,5));
fprintf('Choosing random LORENTZ-product cone K.q.\n')
if(nargin < 2)
nLP = 10;
fprintf('Choosing default K.l=%3.0f.\n',nLP)
if nargin < 1
m=10;
fprintf('Choosing default m=%3.0f.\n',m)
end
end
end
end
end
end
if isempty(nLP)
nLP = 0;
end
nblk = length(nL) + length(rL) + length(qL) + nLP;
denfac = min(1, max(denfac,2/nblk));
fprintf('Choosing block density denfac=%6.4f per row\n',denfac)
Apattern=sparse(m,nblk);
for j=1:m
pati = sprandn(1,nblk,denfac);
Apattern(j,:) = (pati~= 0);
end
sumnLsqr = sum(nL.^2);
x = zeros(nLP+sum(qL)+sum(rL)+sumnLsqr,1);
x(1:nLP) = rand(nLP,1);
At = sparse(length(x),m);
At(1:nLP,:) = sprandn(Apattern(:,1:nLP)');
firstk = nLP+1;
%[nA, mA] = size(At);
% LORENTZ:
for k=1:length(qL)
nk = qL(k); lastk = firstk + nk - 1;
x(firstk) = rand;
for j=1:m
if Apattern(j,nLP+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)) + sqrt(-1) * ...
sparse([0;sprand(nk-1,1,1/sqrt(nk))]);
end
end
firstk = lastk + 1;
end
% RCONE (Rotated Lorentz):
for k=1:length(rL)
nk = rL(k); lastk = firstk + nk - 1;
x(firstk) = rand; x(firstk+1) = rand;
for j=1:m
if Apattern(j,nLP+length(qL)+k)==1
At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)) + sqrt(-1) * ...
sparse([0;0;sprand(nk-2,1,1/sqrt(nk-1))]);
end
end
firstk = lastk + 1;
end
% SDP:
for k=1:length(nL)
nk = nL(k); lastk = firstk + nk*nk - 1;
Xk = diag(rand(nk,1)); % diagonal, to keep sparsity structure
x(firstk:lastk) = Xk; %although symmetric, store nk^2 elts.
for j=1:m
if Apattern(j,nLP+length(qL)+length(rL)+k)==1
rAik = sprandsym(nk,1/nk); %on average 1 nonzero per row
iAik = sprand(nk,nk,1/nk); %on average 1 nonzero per row
At(firstk:lastk,j) = vec(rAik + sqrt(-1)*(iAik-iAik'));
end
end
firstk = lastk + 1;
end
b = real(full(At'*x));
y = rand(m,1)-0.5;
c = sparse(At*y)+x;
K.l = nLP; K.q = qL; K.r = rL; K.s = nL;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
check_A.m
|
.m
|
LMI-Matlab-master/old/kypd/check_A.m
| 2,103 |
utf_8
|
5cc8ebd00480a27a665e76443dc0b1eb
|
function [check,matrix_info,T,c]=check_A(matrix_info,i)
% [check,matrix_info,T,c]=check_A(matrix_info,i)
%
% Checks if the system is controllable or stabilizable. If check=0
% the system is not stabilizable, if check=1 the system is stabilizable
% and if check=2 the system is controllable. If the system is only
% stabilizable the system is transformed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
K=matrix_info.K;
n=matrix_info.n(i);
nm=matrix_info.nm(i);
m=nm-n;
A=matrix_info.A{i};
B=matrix_info.B{i};
[A,B,T,c] = vandooren1(A,B,10);
A=fliplr(flipud(A));
B=flipud(B);
T=fliplr(T);
if c<n&min(real(eig(A(c+1:n,c+1:n))))>0
check=0;
elseif c<n
check=1;
matrix_info.A{i}=A;
matrix_info.B{i}=B;
Tbar=blkdiag(T,eye(m));
matrix_info.M0{i}=Tbar'*matrix_info.M0{i}*Tbar;
for j=1:K
matrix_info.M{i,j}=Tbar'*matrix_info.M{i,j}*Tbar;
end;
matrix_info.C{i} = T*matrix_info.C{i}*T';
else
check=2;
T=eye(n);
end;
function [Ac,Bc,T,c] = vandooren1(A,B,tol)
%
% [Ac,Bc,T,c] = vandooren1(A,B,tol)
%
% Computes a state transformation T such that
%
% A*T = T*Ac; B = T*Bc, where
%
% Ac = [Ac1 0 ]; Bc = [0 ]
% [Ac21 Ac2] [Bc2]
%
% with (Ac2,Bc2) controllable and where the dimension of Ac2 is c
%
% The routine implemented is described in van Dooren, Paul M.: The Generalized
% Eigenstructure Problem in Linear System Theory, IEEE Transaction on Automatic
% Control, Vol. AC-26, No. 1, February 1981
%
% Copyright (c) by Anders Hansson 1996
[n,m] = size(B);
[n,dummy] = size(A);
c = 0;
tau = n;
rho = m;
T = eye(n);
P = [A B];
ready = 0;
while ~ready,
[barB,U,newrho] = rowcompressr(P(:,tau+1:tau+rho),tol);
newtau = tau-newrho;
if newrho == 0,
c = n-tau;
ready = 1;
elseif newtau == 0,
c = n;
ready =1;
else
P = U'*P(:,1:tau)*U;
P = P(1:newtau,:);
T = T*[U zeros(tau,c); zeros(c,tau) eye(c)];
tau = newtau;
rho = newrho;
c = c+rho;
end
end
Ac = T'*A*T;
Bc = T'*B;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
derankcross_sort.m
|
.m
|
LMI-Matlab-master/old/kypd/derankcross_sort.m
| 2,700 |
utf_8
|
01855791da5b13f65d47985a4168c416
|
function schurpar = derankcross_sort(Basis_matrices,len,block_end,n,nm)
rcum = ones(len+1,1);
alphas = [];
V = [];
%Make 'derankcross' for double-crosses
for i = 1:(nm-n)*block_end %number of dubble-crosses
Fi = Basis_matrices{i};
block_number = ceil(i/(2*(nm-n)));
non_zero = [2*block_number-1 2*block_number];
Cross1 = zeros(size(Fi));
Cross2 = Cross1;
Cross1(non_zero(1),:) = Fi(non_zero(1),:);
Cross1(:,non_zero(1)) = Fi(:,non_zero(1));
Cross2(non_zero(2),:) = Fi(non_zero(2),:);
Cross2(:,non_zero(2)) = Fi(:,non_zero(2));
Cross1(non_zero(1),non_zero(2)) = Cross1(non_zero(1),non_zero(2))*.5;
Cross1(non_zero(2),non_zero(1)) = Cross1(non_zero(2),non_zero(1))*.5;
Cross2(non_zero(1),non_zero(2)) = Cross2(non_zero(1),non_zero(2))*.5;
Cross2(non_zero(2),non_zero(1)) = Cross2(non_zero(2),non_zero(1))*.5;
[alpha_temp V_temp] = derankcross_single(sparse(Cross1),non_zero(1));
alphas = [alphas, alpha_temp];
V = [V, V_temp];
[alpha_temp V_temp] = derankcross_single(sparse(Cross2),non_zero(2));
alphas = [alphas, alpha_temp];
V = [V, V_temp];
rcum(i+1) = rcum(i)+4;
end
%Single-crosses
for i = 1:(nm-n)*(n-block_end)%number of single-crosses
position = (nm-n)*block_end+i;
Fi = Basis_matrices{position};
Cross = zeros(size(Fi));
non_zero = block_end+ceil(i/(nm-n));
Cross(:,non_zero) = Fi(:,non_zero);
Cross(non_zero,:) = Fi(non_zero,:);
[alpha_temp V_temp] = derankcross_single(sparse(Cross),non_zero);
rcum(position+1) = rcum(position) + 2;
alphas = [alphas, alpha_temp];
V = [V, V_temp];
end
%The 'extra block'
i = (nm-n)*n+1;
for l=1:nm-n
for k=l:nm-n
if k==l
rcum(i+1) = rcum(i) + 1;
alphas = [alphas, 1];
v = zeros(nm,1);
v(n+k) = 1;
V = [V,v];
i=i+1;
else
Fi = Basis_matrices{i};
[alpha_temp V_temp] = derankcross_single(sparse(Fi),n+k);
rcum(i+1) = rcum(i) + 2;
alphas = [alphas, alpha_temp];
V = [V, V_temp];
i=i+1;
end;
end;
end;
schurpar = {{rcum alphas V}};
function [alpha V] = derankcross_single(Cross, diag)
%function [alpha V] = derankcross_single(Cross, diag)
%
% Rewrite a cross-matrix with rank 1 as alpha*V*V.'
%
% Cross is a matrix with non-zero element in position located on row/column
% 'diag'.
%
v = zeros(size(Cross,1),1);
v(:,1) = Cross(:,diag);
v(diag) = .5*v(diag);
normv = norm(v);
v1 = 1/normv*v;
v2 = v1;
v1(diag) = v1(diag)+1;
v2(diag) = v2(diag)-1;
alpha = [.5*normv -.5*normv];
V = [v1,v2];
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
check_M.m
|
.m
|
LMI-Matlab-master/old/kypd/check_M.m
| 5,029 |
utf_8
|
ec13945d05cc7097b4b9d8847b95e3d8
|
function [check,matrix_info,Pbar,V]=check_M(matrix_info,solver,lowrank,tol)
% [check,matrix_info,Pbar,V]=check_M(matrix_info,tol)
%
% Eliminates the (1,1)-block of the M-matrices and checks if they
% are linearly independent with tolerance tol. If not the number of
% M-matrices are reduced if possible. The values of check can be 0
% which means that the matrices are linearly dependent but the
% system can not be reduced, 1 which means that the matrices are
% linearly dependent and the system is reduced or 2 which means
% that the matrices are linearly independent.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
N=matrix_info.N;
K=matrix_info.K;
nm=matrix_info.nm;
n=matrix_info.n;
m=nm-n;
if solver == 'schur' & ~lowrank
matrix_info.schur.ua = cell(N,1);
matrix_info.schur.ta = cell(N,1);
matrix_info.schur.ub = cell(N,1);
matrix_info.schur.tb = cell(N,1);
elseif solver == 'diago' & ~lowrank
matrix_info.diago.ua = cell(N,1);
matrix_info.diago.ta = cell(N,1);
matrix_info.diago.uainv = cell(N,1);
elseif lowrank
matrix_info.block_info = zeros(N,1);
matrix_info.diago.ta = cell(N,1);
end
matrix_info.T_diag = cell(N,1);
matrix_info.T_diaginv = cell(N,1);
matrix_info.D_diag = cell(N,1);
check=2;
% Eliminate the (1,1)-block of the M-matrices.
Pbar=[];
vec_M=[];
D_diag = cell(N,1);
c = matrix_info.c; %JANNE
for i=1:N
temp=[];
M0=matrix_info.M0{i};
if n(i)~=0
A=matrix_info.A{i};
B=matrix_info.B{i};
[ma,na] = size(A);
[mb,nb] = size(A);
if solver=='schur'
[ua,ta] = schur(A','complex');
j = ma:-1:1;
ub = ua(:,j);
tb = ta(j,j)';
Pbar{i,1}=lyapunov(ua,ta,ub,tb,-M0(1:n(i),1:n(i)));
if lowrank
[T,D] = eig(A');
end
end;
if solver=='diago'
[ua,ta] = eig(A');
uainv = inv(ua);
Pbar{i,1}=diaglyapunov(ua,uainv,ta,-M0(1:n(i),1:n(i)));
if lowrank
T = ua;
D = ta;
end
end;
if lowrank
[matrix_info.T_diag{i},matrix_info.T_diaginv{i}, ...
matrix_info.D_diag{i},matrix_info.block_info(i)] = create_blockdiag_sort(T,D);
end
M0(1:n(i),1:n(i))=zeros(n(i));
M0(1:n(i),n(i)+1:nm(i))=M0(1:n(i),n(i)+1:nm(i))-Pbar{i,1}*B;
M0(n(i)+1:nm(i),1:n(i))=M0(1:n(i),n(i)+1:nm(i))';
matrix_info.M0{i}=M0;
end;
for j=1:K
M=matrix_info.M{i,j};
if n(i)~=0
if solver=='schur'
Pbar{i,j+1}=lyapunov(ua,ta,ub,tb,-M(1:n(i),1:n(i)));
end;
if solver=='diago'
Pbar{i,j+1}=diaglyapunov(ua,uainv,ta,-M(1:n(i),1:n(i)));
end;
M(1:n(i),1:n(i))=zeros(n(i));
M(1:n(i),n(i)+1:nm(i))=M(1:n(i),n(i)+1:nm(i))-Pbar{i,j+1}*B;
M(n(i)+1:nm(i),1:nm(i))=M(1:nm(i),n(i)+1:nm(i))';
matrix_info.M{i,j}=M;
end;
temp=[temp [vec(M(n(i)+1:nm(i),1:n(i)));...
hvec(M(n(i)+1:nm(i),n(i)+1:nm(i)))]];
try
C = matrix_info.C{i}; %JANNE
c(j) = c(j) - trace(C*Pbar{i,j+1}); %JANNE
catch
%No C! c(j) needs not to be changed.
end
end;
vec_M=[vec_M;temp];
end;
matrix_info.c = c;
[n1,m1]=size(vec_M);
% Make a singular value decomposition.
[u,s,v]=svd(full(vec_M));
V=v';
if nargin<4
tol = max(size(vec_M)')*max(max(s))*eps;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check if the matrices are linearly independent.
r = sum(sum(s)>tol);
if r<m1
disp('The M matrices are linearly dependent')
% Check if the number of matrices can be reduced.
if any(abs(V(r+1:m1,:)*matrix_info.c)>tol)
check=0;
error('The system cannot be reduced')
else
% Reduce the number of matrices.
check=1;
matrix_info.c=V(1:r,:)*matrix_info.c;
matrix_info.K=r;
E=u*s;
E=E(:,1:r);
% Create the new M matrices.
for i=1:N
for j=1:r
matrix_info.M{i,j}=zeros(nm(i));
matrix_info.M{i,j}(n(i)+1:nm(i),1:n(i))=reshape(E(1: ...
n(i)*m(i),j),m(i),n(i));
matrix_info.M{i,j}=matrix_info.M{i,j}+matrix_info.M{i,j}';
matrix_info.M{i,j}(n(i)+1:nm(i),n(i)+1:nm(i))=...
inv_hvec(E(n(i)*m(i)+1:n(i)*m(i)+m(i)*(m(i)+1)/2,j));
end;
E=E(n(i)*m(i)+m(i)*(m(i)+1)/2+1:end,:);
end;
end;
end;
V=V(1:r,:);
function v=hvec(M)
[n,m]=size(M);
if n~=m
error('The matrix is not square')
end;
if issymmetric(M)
x=find(triu(ones(m)));
v=M(x);
else
error('The matrix is not symmetric')
end;
function M=inv_hvec(v)
m=(-1+sqrt(1+8*length(v)))/2;
if abs(round(m)-m)>1e-5
error('The size of the vector is not compatible with a symmetric matrix')
else
x=find(triu(ones(m)));
M=zeros(m);
M(x)=v;
M=M+M'-diag(diag(M));
end;
|
github
|
EnricoGiordano1992/LMI-Matlab-master
|
kypd.m
|
.m
|
LMI-Matlab-master/old/kypd/kypd.m
| 1,440 |
utf_8
|
a3f4c76e79be3a54e3ac79de6ebc7e9b
|
function [u,P,x,Z,soltime,errorflag]=kypd(matrix_info,options)
if nargin<2
options = sdpsettings;
end
for i=1:matrix_info.N
matrix_info.M0{i}=matrix_info.M0{i}-options.kypd.tol*...
eye(size(matrix_info.M0{i}));
end;
[F,n_basis,ntot_basis,F0]=basis_matrices(matrix_info,...
options.kypd.lyapunovsolver,options.kypd.lowrank);
G=computeG(matrix_info,F,n_basis);
G0=computeG0(matrix_info,F0,ones(matrix_info.N,1));
t=0;
for i=1:matrix_info.N
for j=1:n_basis(i)
d(t+j,1)=ip(F{t+j},matrix_info.M0{i});
end;
t=t+n_basis(i);
end;
[X,Z,soltime,errorflag]=dual(d,F,G,n_basis,ntot_basis,matrix_info,options,F0,G0);
if ~errorflag
[u,P,x]=get_Px(X,F,G,matrix_info,n_basis);
else
u = [];
P = [];
x = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function G=computeG(matrix_info,F,n_basis);
N=matrix_info.N;
K=matrix_info.K;
G=[];
Gtemp=[];
t=0;
for i=1:N
for k=1:n_basis(i)
for l=1:K
Gtemp(k,l)=ip(F{t+k},matrix_info.M{i,l});
end;
end;
t=t+k;
G=[G;Gtemp];
Gtemp=[];
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function G=computeG0(matrix_info,F0,n_basis);
N=matrix_info.N;
K=matrix_info.K;
G=zeros(1,K);
Gtemp=[];
for i=1:N
for l=1:K
Gtemp(1,l)=ip(F0{i,1},matrix_info.M{i,l});
end;
G= G + Gtemp;
Gtemp=[];
end;
|
github
|
M-MohammadPour/EEGClassification-master
|
gradient_boosting_predict.m
|
.m
|
EEGClassification-master/Ensemble Learning/Boosting/gradient_boosting_predict.m
| 1,914 |
utf_8
|
b9930d13df8f681614d35fdf971acae0
|
% Practicum, Task #3, 'Compositions of algorithms'.
%
% FUNCTION:
% [prediction, err] = gradient_boosting_predict (model, X, y)
%
% DESCRIPTION:
% This function use the composition of algorithms, trained with gradient
% boosting method, for prediction.
%
% INPUT:
% X --- matrix of objects, N x K double matrix, N --- number of objects,
% K --- number of features.
% y --- vector of answers, N x 1 double vector, N --- number of objects. y
% can have only two values --- +1 and -1.
% model --- trained composition.
%
% OUTPUT:
% prediction --- vector of predicted answers, N x 1 double vector.
% error --- the ratio of number of correct answers to number of objects on
% each iteration, num_iterations x 1 vector
%
% AUTHOR:
% Murat Apishev ([email protected])
%
function [prediction, err] = gradient_boosting_predict (model, X, y)
num_iterations = length(model.weights);
no_objects = length(y);
pred_prediction = zeros([no_objects num_iterations]);
for alg = 1 : num_iterations
value = zeros([no_objects 1]) + model.b_0;
for i = 1 : alg
if strcmp(model.algorithm, 'epsilon_svr')
value = value + svmpredict(y, X, model.models{i}) * model.weights(i);
elseif strcmp(model.algorithm, 'regression_tree')
value = value + predict(model.models{i}, X) * model.weights(i);
end
end
pred_prediction(:,alg) = value;
end
prediction = pred_prediction(:,end);
err = zeros([num_iterations 1]);
if strcmp(model.loss, 'absolute')
temp = (bsxfun(@minus, pred_prediction, y));
err = abs(sum(temp)) / no_objects;
elseif strcmp(model.loss, 'logistic')
prediction = sign(prediction);
temp = (bsxfun(@eq, sign(pred_prediction), y));
err = sum(temp == 0) / no_objects;
end
if size(err, 1) == 1
err = err';
end
end
|
github
|
M-MohammadPour/EEGClassification-master
|
gradient_boosting_train.m
|
.m
|
EEGClassification-master/Ensemble Learning/Boosting/gradient_boosting_train.m
| 4,308 |
utf_8
|
dfa172848dafd66a5e29d53c7f5ee8b2
|
% Practicum, Task #3, 'Compositions of algorithms'.
%
% FUNCTION:
% [model] = gradient_boosting_train (X, y, num_iterations, base_algorithm, loss, ...
% param_name1, param_value1, param_name2, param_value2, ...
% param_name3, param_value3, param_name3, param_value3)
%
% DESCRIPTION:
% This function train the composition of algorithms using gradient boosting method.
%
% INPUT:
% X --- matrix of objects, N x K double matrix, N --- number of objects,
% K --- number of features.
% y --- vector of answers, N x 1 double vector, N --- number of objects. y
% can have only two values --- +1 and -1 in case of classification
% and all possible double values in case of regression.
% num_iterations --- the number ob algorithms in composition, scalar.
% base_algorithm --- the base algorithm, string. Can have one of two
% values: 'regression_tree' or 'epsilon_svr'.
% loss --- the loss function, string. Can have one of two values:
% 'logistic' (for classification) or 'absolute' (for regression).
% param_name1 --- learning rate, scalar.
% param_name2 --- parameter of base_algorithm. For 'regression_tree' it
% is a 'min_parent' --- min number of objects in the leaf of
% regression tree. For 'epsilon_svr' it is 'epsilon' parameter.
% param_name3 --- parameter, that exists only for 'epsilon_svr', it is a
% 'gamma' parameter.
% param_name4 --- parameter, that exists only for 'epsilon_svr', it is a
% 'C' parameter.
% param_value1, param_value2, param_value3, param_value4 --- values of
% corresponding parametres, scalar.
% OUTPUT:
% model --- trained composition, structure with three fields
% - b_0 --- the base of composition, scalar
% - weights --- double array of weights, 1 x num_iterations
% - models --- cell array with trained models, 1 x num_iterations
% - algorithm --- string, 'epsilon_svr' or 'regression_tree'
% - loss --- loss parameter (from INPUT).
%
% AUTHOR:
% Murat Apishev ([email protected])
%
function [model] = gradient_boosting_train (X, y, num_iterations, base_algorithm, loss, ...
param_name1, param_value1, param_name2, param_value2, ...
param_name3, param_value3, param_name4, param_value4)
no_objects = size(X, 1);
if ~strcmp(base_algorithm, 'epsilon_svr') && ~strcmp(base_algorithm, 'regression_tree')
error('Incorrect type of algorithm!')
end
if strcmp(loss, 'logistic')
loss_function = @(a, b) log(1 + exp(-a .* b));
grad_a_loss_function = @(a, b) -b .* exp(-a .* b) ./ ((1 + exp(-a .* b)));
elseif strcmp(loss, 'absolute')
loss_function = @(a, b) abs(a - b);
grad_a_loss_function = @(a, b) -sign(b - a);
else
error('Incorrect type of loss function!');
end
func = @(c) sum(loss_function(y, c));
b_0 = fminsearch(func, 0);
model.b_0 = b_0;
model.algorithm = base_algorithm;
model.models = cell([1 num_iterations]);
model.loss = loss;
% the length of model is number of finite weights, not number of models!
model.weights = repmat(+Inf, 1, num_iterations);
z = zeros([no_objects 1]) + b_0;
delta = zeros([no_objects 1]);
for iter = 1 : num_iterations
for obj = 1 : no_objects
delta(obj) = -grad_a_loss_function(z(obj), y(obj));
end
if strcmp(base_algorithm, 'epsilon_svr')
model.models{iter} = svmtrain(delta, X, [' -s 3 -g ', num2str(param_value3), ...
' -c ', num2str(param_value4), ' -e ', num2str(param_value2)]);
value = svmpredict(y, X, model.models{iter});
elseif strcmp(base_algorithm, 'regression_tree')
model.models{iter} = RegressionTree.fit(X, delta, 'minparent', param_value2);
value = predict(model.models{iter}, X);
end
func = @(g) sum(loss_function(z + g * value, y));
model.weights(iter) = fminsearch(func, 0);
z = z + model.weights(iter) * value * param_value1;
end
end
|
github
|
M-MohammadPour/EEGClassification-master
|
bagging_train.m
|
.m
|
EEGClassification-master/Ensemble Learning/Bagging/bagging_train.m
| 2,754 |
utf_8
|
7c6dc91c1019d451c23e46502a63ca75
|
% Practicum, Task #3, 'Compositions of algorithms'.
%
% FUNCTION:
% [model] = bagging_train (X, y, num_iterations, base_algorithm, ...
% param_name1, param_value1, param_name2, param_value2)
%
% DESCRIPTION:
% This function train the composition of algorithms using bagging method.
%
% INPUT:
% X --- matrix of objects, N x K double matrix, N --- number of objects,
% K --- number of features.
% y --- vector of answers, N x 1 double vector, N --- number of objects. y
% can have only two values --- +1 and -1.
% num_iterations --- the number ob algorithms in composition, scalar.
% base_algorithm --- the base algorithm, string. Can have one of two
% values: 'classification_tree' or 'svm'.
% param_name1 --- parameter of base_algorithm. For 'classification_tree' it
% is a 'min_parent' --- min number of objects in the leaf of
% classification tree. For 'svm' it is 'gamma' parameter.
% param_name2 --- parameter, that exists only for 'svm', it is a 'C'
% parameter.
% param_value1, param_value2 --- values of corresponding parametres,
% scalar.
% OUTPUT:
% model --- trained composition, structure with two fields
% - models --- cell array with trained models
% - algorithm --- string, 'svm' or 'classification_tree'
%
% AUTHOR:
% Murat Apishev ([email protected])
%
function [model] = bagging_train (X, y, num_iterations, base_algorithm, ...
param_name1, param_value1, param_name2, param_value2)
no_objects = size(X, 1);
models = cell([1 num_iterations]);
if strcmp(base_algorithm, 'svm')
if ~strcmp(param_name1, 'gamma')
temp = param_value1;
param_value1 = param_value2;
param_value2 = temp;
end
for iter = 1 : num_iterations
indices = randi(no_objects, 1, no_objects);
indices = unique(indices);
models{iter} = svmtrain(y(indices), X(indices,:), ...
[' -g ', num2str(param_value1), ' -c ', num2str(param_value2)]);
end
elseif strcmp(base_algorithm, 'classification_tree')
for iter = 1 : num_iterations
indices = randi(no_objects, 1, no_objects);
indices = unique(indices);
if (param_value1 > length(indices))
value = length(indices);
else
value = param_value1;
end
models{iter} = ClassificationTree.fit(X(indices,:), y(indices), 'MinParent', value);
end
else
error('Incorrect type of algorithm!');
end
model.models = models;
model.algorithm = base_algorithm;
end
|
github
|
M-MohammadPour/EEGClassification-master
|
bagging_predict.m
|
.m
|
EEGClassification-master/Ensemble Learning/Bagging/bagging_predict.m
| 1,913 |
utf_8
|
3e79de35c9fe4d67be86750ef18c1aeb
|
% Practicum, Task #3, 'Compositions of algorithms'.
%
% FUNCTION:
% [prediction, err] = bagging_predict (model, X, y)
%
% DESCRIPTION:
% This function use the composition of algorithms, trained with bagging
% method, for prediction.
%
% INPUT:
% X --- matrix of objects, N x K double matrix, N --- number of objects,
% K --- number of features.
% y --- vector of answers, N x 1 double vector, N --- number of objects. y
% can have only two values --- +1 and -1.
% model --- trained composition.
%
% OUTPUT:
% prediction --- vector of predicted answers, N x 1 double vector.
% error --- the ratio of number of correct answers to number of objects on
% each iteration, num_iterations x 1 vector
%
% AUTHOR:
% Murat Apishev ([email protected])
%
function [prediction, err] = bagging_predict (model, X, y)
num_iterations = length(model.models);
no_objects = length(y);
pred_prediction = zeros([no_objects num_iterations]);
err = zeros([num_iterations 1]);
if strcmp(model.algorithm, 'svm')
for alg = 1 : num_iterations
pred_prediction(:,alg) = svmpredict(y, X, model.models{alg});
func = @(i) find_max(pred_prediction(i,:));
prediction = arrayfun(func, 1 : no_objects)';
err(alg) = sum(prediction ~= y) / no_objects;
end
elseif strcmp(model.algorithm, 'classification_tree')
for alg = 1 : num_iterations
pred_prediction(:,alg) = predict(model.models{alg}, X);
func = @(i) find_max(pred_prediction(i,:));
prediction = arrayfun(func, 1 : no_objects)';
err(alg) = sum(prediction ~= y) / no_objects;
end
else
error('Incorrect type of algorithm!');
end
end
function [result] = find_max (vector)
if sum(vector == -1) > sum(vector == +1)
result = -1;
else
result = +1;
end
end
|
github
|
M-MohammadPour/EEGClassification-master
|
predStump.m
|
.m
|
EEGClassification-master/Ensemble Learning/AdaBoost/predStump.m
| 240 |
utf_8
|
33aef76407d65dfa83f957307334842c
|
% Make prediction based on a decision stump
function label = predStump(X, stump)
N = size(X, 1);
x = X(:, stump.dim);
idx = logical(x >= stump.threshold); % N x 1
label = zeros(N, 1);
label(idx) = stump.more;
label(~idx) = stump.less;
end
|
github
|
M-MohammadPour/EEGClassification-master
|
buildOneDStump.m
|
.m
|
EEGClassification-master/Ensemble Learning/AdaBoost/buildOneDStump.m
| 959 |
utf_8
|
1b1d03178b568de1fb78b4f663a935fb
|
function stump = buildOneDStump(x, y, d, w)
[err_1, t_1] = searchThreshold(x, y, w, '>'); % > t_1 -> +1
[err_2, t_2] = searchThreshold(x, y, w, '<'); % < t_2 -> +1
stump = initStump(d);
if err_1 <= err_2
stump.threshold = t_1;
stump.error = err_1;
stump.less = -1;
stump.more = 1;
else
stump.threshold = t_2;
stump.error = err_2;
stump.less = 1;
stump.more = -1;
end
end
function [error, thresh] = searchThreshold(x, y, w, sign)
N = length(x);
err_n = zeros(N, 1);
y_predict = zeros(N, 1);
for n=1:N
switch sign
case '>'
idx = logical(x >= x(n));
y_predict(idx) = 1;
y_predict(~idx) = -1;
case '<'
idx = logical(x < x(n));
y_predict(idx) = 1;
y_predict(~idx) = -1;
end
err_label = logical(y ~= y_predict);
%sum(err_label)
err_n(n) = sum(err_label.*w)/sum(w);
end
[v, idx] = min(err_n);
error = v;
thresh = x(idx);
end
|
github
|
claudia-lat/MAPest-master
|
save2pdf.m
|
.m
|
MAPest-master/external/save2pdf.m
| 2,184 |
utf_8
|
28056d1c6584d93469211eb0e05bdd6a
|
%SAVE2PDF Saves a figure as a properly cropped pdf
%
% save2pdf(pdfFileName,handle,dpi)
%
% - pdfFileName: Destination to write the pdf to.
% - handle: (optional) Handle of the figure to write to a pdf. If
% omitted, the current figure is used. Note that handles
% are typically the figure number.
% - dpi: (optional) Integer value of dots per inch (DPI). Sets
% resolution of output pdf. Note that 150 dpi is the Matlab
% default and this function's default, but 600 dpi is typical for
% production-quality.
%
% Saves figure as a pdf with margins cropped to match the figure size.
% (c) Gabe Hoffmann, [email protected]
% Written 8/30/2007
% Revised 9/22/2007
% Revised 1/14/2007
function save2pdf(pdfFileName,handle,dpi)
% Verify correct number of arguments
narginchk(0,3);
% If no handle is provided, use the current figure as default
if nargin<1
[fileName,pathName] = uiputfile('*.pdf','Save to PDF file:');
if fileName == 0; return; end
pdfFileName = [pathName,fileName];
end
if nargin<2
handle = gcf;
end
if nargin<3
dpi = 150;
end
% Backup previous settings
prePaperType = get(handle,'PaperType');
prePaperUnits = get(handle,'PaperUnits');
preUnits = get(handle,'Units');
prePaperPosition = get(handle,'PaperPosition');
prePaperSize = get(handle,'PaperSize');
% Make changing paper type possible
set(handle,'PaperType','<custom>');
% Set units to all be the same
set(handle,'PaperUnits','inches');
set(handle,'Units','inches');
% Set the page size and position to match the figure's dimensions
paperPosition = get(handle,'PaperPosition');
position = get(handle,'Position');
set(handle,'PaperPosition',[0,0,position(3:4)]);
set(handle,'PaperSize',position(3:4));
% Save the pdf (this is the same method used by "saveas")
print(handle,'-dpdf',pdfFileName,sprintf('-r%d',dpi))
% Restore the previous settings
set(handle,'PaperType',prePaperType);
set(handle,'PaperUnits',prePaperUnits);
set(handle,'Units',preUnits);
set(handle,'PaperPosition',prePaperPosition);
set(handle,'PaperSize',prePaperSize);
|
github
|
claudia-lat/MAPest-master
|
tightfig.m
|
.m
|
MAPest-master/external/tightfig.m
| 5,419 |
utf_8
|
1f6f3f5059ca866348b7edf7add7db02
|
% Copyright (c) 2011, Richard Crozier
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function hfig = tightfig(hfig)
% tightfig: Alters a figure so that it has the minimum size necessary to
% enclose all axes in the figure without excess space around them.
%
% Note that tightfig will expand the figure to completely encompass all
% axes if necessary. If any 3D axes are present which have been zoomed,
% tightfig will produce an error, as these cannot easily be dealt with.
%
% hfig - handle to figure, if not supplied, the current figure will be used
% instead.
if nargin == 0
hfig = gcf;
end
% There can be an issue with tightfig when the user has been modifying
% the contnts manually, the code below is an attempt to resolve this,
% but it has not yet been satisfactorily fixed
% origwindowstyle = get(hfig, 'WindowStyle');
set(hfig, 'WindowStyle', 'normal');
% 1 point is 0.3528 mm for future use
% get all the axes handles note this will also fetch legends and
% colorbars as well
hax = findall(hfig, 'type', 'axes');
% get the original axes units, so we can change and reset these again
% later
origaxunits = get(hax, 'Units');
% change the axes units to cm
set(hax, 'Units', 'centimeters');
% get various position parameters of the axes
if numel(hax) > 1
% fsize = cell2mat(get(hax, 'FontSize'));
ti = cell2mat(get(hax,'TightInset'));
pos = cell2mat(get(hax, 'Position'));
else
% fsize = get(hax, 'FontSize');
ti = get(hax,'TightInset');
pos = get(hax, 'Position');
end
% ensure very tiny border so outer box always appears
ti(ti < 0.1) = 0.15;
% we will check if any 3d axes are zoomed, to do this we will check if
% they are not being viewed in any of the 2d directions
views2d = [0,90; 0,0; 90,0];
for i = 1:numel(hax)
set(hax(i), 'LooseInset', ti(i,:));
% set(hax(i), 'LooseInset', [0,0,0,0]);
% get the current viewing angle of the axes
[az,el] = view(hax(i));
% determine if the axes are zoomed
iszoomed = strcmp(get(hax(i), 'CameraViewAngleMode'), 'manual');
% test if we are viewing in 2d mode or a 3d view
is2d = all(bsxfun(@eq, [az,el], views2d), 2);
if iszoomed && ~any(is2d)
error('TIGHTFIG:haszoomed3d', 'Cannot make figures containing zoomed 3D axes tight.')
end
end
% we will move all the axes down and to the left by the amount
% necessary to just show the bottom and leftmost axes and labels etc.
moveleft = min(pos(:,1) - ti(:,1));
movedown = min(pos(:,2) - ti(:,2));
% we will also alter the height and width of the figure to just
% encompass the topmost and rightmost axes and lables
figwidth = max(pos(:,1) + pos(:,3) + ti(:,3) - moveleft);
figheight = max(pos(:,2) + pos(:,4) + ti(:,4) - movedown);
% move all the axes
for i = 1:numel(hax)
set(hax(i), 'Position', [pos(i,1:2) - [moveleft,movedown], pos(i,3:4)]);
end
origfigunits = get(hfig, 'Units');
set(hfig, 'Units', 'centimeters');
% change the size of the figure
figpos = get(hfig, 'Position');
set(hfig, 'Position', [figpos(1), figpos(2), figwidth, figheight]);
% change the size of the paper
set(hfig, 'PaperUnits','centimeters');
set(hfig, 'PaperSize', [figwidth, figheight]);
set(hfig, 'PaperPositionMode', 'manual');
set(hfig, 'PaperPosition',[0 0 figwidth figheight]);
% reset to original units for axes and figure
if ~iscell(origaxunits)
origaxunits = {origaxunits};
end
for i = 1:numel(hax)
set(hax(i), 'Units', origaxunits{i});
end
set(hfig, 'Units', origfigunits);
% set(hfig, 'WindowStyle', origwindowstyle);
end
|
github
|
claudia-lat/MAPest-master
|
xml_write.m
|
.m
|
MAPest-master/external/xml_io_tools/xml_write.m
| 18,772 |
utf_8
|
4f952d9ca0351040dbffeb946e877bb0
|
function DOMnode = xml_write(filename, tree, RootName, Pref)
%XML_WRITE Writes Matlab data structures to XML file
%
% DESCRIPTION
% xml_write( filename, tree) Converts Matlab data structure 'tree' containing
% cells, structs, numbers and strings to Document Object Model (DOM) node
% tree, then saves it to XML file 'filename' using Matlab's xmlwrite
% function. Optionally one can also use alternative version of xmlwrite
% function which directly calls JAVA functions for XML writing without
% MATLAB middleware. This function is provided as a patch to existing
% bugs in xmlwrite (in R2006b).
%
% xml_write(filename, tree, RootName, Pref) allows you to specify
% additional preferences about file format
%
% DOMnode = xml_write([], tree) same as above except that DOM node is
% not saved to the file but returned.
%
% INPUT
% filename file name
% tree Matlab structure tree to store in xml file.
% RootName String with XML tag name used for root (top level) node
% Optionally it can be a string cell array storing: Name of
% root node, document "Processing Instructions" data and
% document "comment" string
% Pref Other preferences:
% Pref.ItemName - default 'item' - name of a special tag used to
% itemize cell or struct arrays
% Pref.XmlEngine - let you choose the XML engine. Currently default is
% 'Xerces', which is using directly the apache xerces java file.
% Other option is 'Matlab' which uses MATLAB's xmlwrite and its
% XMLUtils java file. Both options create identical results except in
% case of CDATA sections where xmlwrite fails.
% Pref.CellItem - default 'true' - allow cell arrays to use 'item'
% notation. See below.
% Pref.RootOnly - default true - output variable 'tree' corresponds to
% xml file root element, otherwise it correspond to the whole file.
% Pref.StructItem - default 'true' - allow arrays of structs to use
% 'item' notation. For example "Pref.StructItem = true" gives:
% <a>
% <b>
% <item> ... <\item>
% <item> ... <\item>
% <\b>
% <\a>
% while "Pref.StructItem = false" gives:
% <a>
% <b> ... <\b>
% <b> ... <\b>
% <\a>
%
%
% Several special xml node types can be created if special tags are used
% for field names of 'tree' nodes:
% - node.CONTENT - stores data section of the node if other fields
% (usually ATTRIBUTE are present. Usually data section is stored
% directly in 'node'.
% - node.ATTRIBUTE.name - stores node's attribute called 'name'.
% - node.COMMENT - create comment child node from the string. For global
% comments see "RootName" input variable.
% - node.PROCESSING_INSTRUCTIONS - create "processing instruction" child
% node from the string. For global "processing instructions" see
% "RootName" input variable.
% - node.CDATA_SECTION - stores node's CDATA section (string). Only works
% if Pref.XmlEngine='Xerces'. For more info, see comments of F_xmlwrite.
% - other special node types like: document fragment nodes, document type
% nodes, entity nodes and notation nodes are not being handled by
% 'xml_write' at the moment.
%
% OUTPUT
% DOMnode Document Object Model (DOM) node tree in the format
% required as input to xmlwrite. (optional)
%
% EXAMPLES:
% MyTree=[];
% MyTree.MyNumber = 13;
% MyTree.MyString = 'Hello World';
% xml_write('test.xml', MyTree);
% type('test.xml')
% %See also xml_tutorial.m
%
% See also
% xml_read, xmlread, xmlwrite
%
% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com
%% Check Matlab Version
v = ver('MATLAB');
v = str2double(regexp(v.Version, '\d.\d','match','once'));
if (v<7)
error('Your MATLAB version is too old. You need version 7.0 or newer.');
end
%% default preferences
DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays
DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays
DPref.StructItem = true; % allow arrays of structs to use 'item' notation
DPref.CellItem = true; % allow cell arrays to use 'item' notation
DPref.StructTable= 'Html';
DPref.CellTable = 'Html';
DPref.XmlEngine = 'Matlab'; % use matlab provided XMLUtils
%DPref.XmlEngine = 'Xerces'; % use Xerces xml generator directly
DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings?
RootOnly = true; % Input is root node only
GlobalProcInst = [];
GlobalComment = [];
GlobalDocType = [];
%% read user preferences
if (nargin>3)
if (isfield(Pref, 'TableName' )), DPref.TableName = Pref.TableName; end
if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end
if (isfield(Pref, 'StructItem')), DPref.StructItem = Pref.StructItem; end
if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end
if (isfield(Pref, 'CellTable')), DPref.CellTable = Pref.CellTable; end
if (isfield(Pref, 'StructTable')), DPref.StructTable= Pref.StructTable; end
if (isfield(Pref, 'XmlEngine' )), DPref.XmlEngine = Pref.XmlEngine; end
if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end
if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end
end
if (nargin<3 || isempty(RootName)), RootName=inputname(2); end
if (isempty(RootName)), RootName='ROOT'; end
if (iscell(RootName)) % RootName also stores global text node data
rName = RootName;
RootName = char(rName{1});
if (length(rName)>1), GlobalProcInst = char(rName{2}); end
if (length(rName)>2), GlobalComment = char(rName{3}); end
if (length(rName)>3), GlobalDocType = char(rName{4}); end
end
if(~RootOnly && isstruct(tree)) % if struct than deal with each field separatly
fields = fieldnames(tree);
for i=1:length(fields)
field = fields{i};
x = tree(1).(field);
if (strcmp(field, 'COMMENT'))
GlobalComment = x;
elseif (strcmp(field, 'PROCESSING_INSTRUCTION'))
GlobalProcInst = x;
elseif (strcmp(field, 'DOCUMENT_TYPE'))
GlobalDocType = x;
else
RootName = field;
t = x;
end
end
tree = t;
end
%% Initialize jave object that will store xml data structure
RootName = varName2str(RootName);
if (~isempty(GlobalDocType))
% n = strfind(GlobalDocType, ' ');
% if (~isempty(n))
% dtype = com.mathworks.xml.XMLUtils.createDocumentType(GlobalDocType);
% end
% DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName, dtype);
warning('xml_io_tools:write:docType', ...
'DOCUMENT_TYPE node was encountered which is not supported yet. Ignoring.');
end
DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName);
%% Use recursive function to convert matlab data structure to XML
root = DOMnode.getDocumentElement;
struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref);
%% Remove the only child of the root node
root = DOMnode.getDocumentElement;
Child = root.getChildNodes; % create array of children nodes
nChild = Child.getLength; % number of children
if (nChild==1)
node = root.removeChild(root.getFirstChild);
while(node.hasChildNodes)
root.appendChild(node.removeChild(node.getFirstChild));
end
while(node.hasAttributes) % copy all attributes
root.setAttributeNode(node.removeAttributeNode(node.getAttributes.item(0)));
end
end
%% Save exotic Global nodes
if (~isempty(GlobalComment))
DOMnode.insertBefore(DOMnode.createComment(GlobalComment), DOMnode.getFirstChild());
end
if (~isempty(GlobalProcInst))
n = strfind(GlobalProcInst, ' ');
if (~isempty(n))
proc = DOMnode.createProcessingInstruction(GlobalProcInst(1:(n(1)-1)),...
GlobalProcInst((n(1)+1):end));
DOMnode.insertBefore(proc, DOMnode.getFirstChild());
end
end
% Not supported yet as the code below does not work
% if (~isempty(GlobalDocType))
% n = strfind(GlobalDocType, ' ');
% if (~isempty(n))
% dtype = DOMnode.createDocumentType(GlobalDocType);
% DOMnode.insertBefore(dtype, DOMnode.getFirstChild());
% end
% end
%% save java DOM tree to XML file
if (~isempty(filename))
if (strcmpi(DPref.XmlEngine, 'Xerces'))
xmlwrite_xerces(filename, DOMnode);
else
xmlwrite(filename, DOMnode);
end
end
%% =======================================================================
% === struct2DOMnode Function ===========================================
% =======================================================================
function [] = struct2DOMnode(xml, parent, s, TagName, Pref)
% struct2DOMnode is a recursive function that converts matlab's structs to
% DOM nodes.
% INPUTS:
% xml - jave object that will store xml data structure
% parent - parent DOM Element
% s - Matlab data structure to save
% TagName - name to be used in xml tags describing 's'
% Pref - preferenced
% OUTPUT:
% parent - modified 'parent'
% perform some conversions
if (ischar(s) && min(size(s))>1) % if 2D array of characters
s=cellstr(s); % than convert to cell array
end
% if (strcmp(TagName, 'CONTENT'))
% while (iscell(s) && length(s)==1), s = s{1}; end % unwrap cell arrays of length 1
% end
TagName = varName2str(TagName);
%% == node is a 2D cell array ==
% convert to some other format prior to further processing
nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc?
if (iscell(s) && nDim==2 && strcmpi(Pref.CellTable, 'Matlab'))
s = var2str(s, Pref.PreserveSpace);
end
if (nDim==2 && (iscell (s) && strcmpi(Pref.CellTable, 'Vector')) || ...
(isstruct(s) && strcmpi(Pref.StructTable, 'Vector')))
s = s(:);
end
if (nDim>2), s = s(:); end % can not handle this case well
nItem = numel(s);
nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc?
%% == node is a cell ==
if (iscell(s)) % if this is a cell or cell array
if ((nDim==2 && strcmpi(Pref.CellTable,'Html')) || (nDim< 2 && Pref.CellItem))
% if 2D array of cells than can use HTML-like notation or if 1D array
% than can use item notation
if (strcmp(TagName, 'CONTENT')) % CONTENT nodes already have <TagName> ... </TagName>
array2DOMnode(xml, parent, s, Pref.ItemName, Pref ); % recursive call
else
node = xml.createElement(TagName); % <TagName> ... </TagName>
array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call
parent.appendChild(node);
end
else % use <TagName>...<\TagName> <TagName>...<\TagName> notation
array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call
end
%% == node is a struct ==
elseif (isstruct(s)) % if struct than deal with each field separatly
if ((nDim==2 && strcmpi(Pref.StructTable,'Html')) || (nItem>1 && Pref.StructItem))
% if 2D array of structs than can use HTML-like notation or
% if 1D array of structs than can use 'items' notation
node = xml.createElement(TagName);
array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call
parent.appendChild(node);
elseif (nItem>1) % use <TagName>...<\TagName> <TagName>...<\TagName> notation
array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call
else % otherwise save each struct separatelly
fields = fieldnames(s);
node = xml.createElement(TagName);
for i=1:length(fields) % add field by field to the node
field = fields{i};
x = s.(field);
switch field
case {'COMMENT', 'CDATA_SECTION', 'PROCESSING_INSTRUCTION'}
if iscellstr(x) % cell array of strings -> add them one by one
array2DOMnode(xml, node, x(:), field, Pref ); % recursive call will modify 'node'
elseif ischar(x) % single string -> add it
struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node'
else % not a string - Ignore
warning('xml_io_tools:write:badSpecialNode', ...
['Struct field named ',field,' encountered which was not a string. Ignoring.']);
end
case 'ATTRIBUTE' % set attributes of the node
if (isempty(x)), continue; end
if (isstruct(x))
attName = fieldnames(x); % get names of all the attributes
for k=1:length(attName) % attach them to the node
att = xml.createAttribute(varName2str(attName(k)));
att.setValue(var2str(x.(attName{k}),Pref.PreserveSpace));
node.setAttributeNode(att);
end
else
warning('xml_io_tools:write:badAttribute', ...
'Struct field named ATTRIBUTE encountered which was not a struct. Ignoring.');
end
otherwise % set children of the node
struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node'
end
end % end for i=1:nFields
parent.appendChild(node);
end
%% == node is a leaf node ==
else % if not a struct and not a cell than it is a leaf node
switch TagName % different processing depending on desired type of the node
case 'COMMENT' % create comment node
com = xml.createComment(s);
parent.appendChild(com);
case 'CDATA_SECTION' % create CDATA Section
cdt = xml.createCDATASection(s);
parent.appendChild(cdt);
case 'PROCESSING_INSTRUCTION' % set attributes of the node
OK = false;
if (ischar(s))
n = strfind(s, ' ');
if (~isempty(n))
proc = xml.createProcessingInstruction(s(1:(n(1)-1)),s((n(1)+1):end));
parent.insertBefore(proc, parent.getFirstChild());
OK = true;
end
end
if (~OK)
warning('xml_io_tools:write:badProcInst', ...
['Struct field named PROCESSING_INSTRUCTION need to be',...
' a string, for example: xml-stylesheet type="text/css" ', ...
'href="myStyleSheet.css". Ignoring.']);
end
case 'CONTENT' % this is text part of already existing node
txt = xml.createTextNode(var2str(s, Pref.PreserveSpace)); % convert to text
parent.appendChild(txt);
otherwise % I guess it is a regular text leaf node
txt = xml.createTextNode(var2str(s, Pref.PreserveSpace));
node = xml.createElement(TagName);
node.appendChild(txt);
parent.appendChild(node);
end
end % of struct2DOMnode function
%% =======================================================================
% === array2DOMnode Function ============================================
% =======================================================================
function [] = array2DOMnode(xml, parent, s, TagName, Pref)
% Deal with 1D and 2D arrays of cell or struct. Will modify 'parent'.
nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc?
switch nDim
case 2 % 2D array
for r=1:size(s,1)
subnode = xml.createElement(Pref.TableName{1});
for c=1:size(s,2)
v = s(r,c);
if iscell(v), v = v{1}; end
struct2DOMnode(xml, subnode, v, Pref.TableName{2}, Pref ); % recursive call
end
parent.appendChild(subnode);
end
case 1 %1D array
for iItem=1:numel(s)
v = s(iItem);
if iscell(v), v = v{1}; end
struct2DOMnode(xml, parent, v, TagName, Pref ); % recursive call
end
case 0 % scalar -> this case should never be called
if ~isempty(s)
if iscell(s), s = s{1}; end
struct2DOMnode(xml, parent, s, TagName, Pref );
end
end
%% =======================================================================
% === var2str Function ==================================================
% =======================================================================
function str = var2str(object, PreserveSpace)
% convert matlab variables to a string
switch (1)
case isempty(object)
str = '';
case (isnumeric(object) || islogical(object))
if ndims(object)>2, object=object(:); end % can't handle arrays with dimention > 2
str=mat2str(object); % convert matrix to a string
% mark logical scalars with [] (logical arrays already have them) so the xml_read
% recognizes them as MATLAB objects instead of strings. Same with sparse
% matrices
if ((islogical(object) && isscalar(object)) || issparse(object)),
str = ['[' str ']'];
end
if (isinteger(object)),
str = ['[', class(object), '(', str ')]'];
end
case iscell(object)
if ndims(object)>2, object=object(:); end % can't handle cell arrays with dimention > 2
[nr nc] = size(object);
obj2 = object;
for i=1:length(object(:))
str = var2str(object{i}, PreserveSpace);
if (ischar(object{i})), object{i} = ['''' object{i} '''']; else object{i}=str; end
obj2{i} = [object{i} ','];
end
for r = 1:nr, obj2{r,nc} = [object{r,nc} ';']; end
obj2 = obj2.';
str = ['{' obj2{:} '}'];
case isstruct(object)
str='';
warning('xml_io_tools:write:var2str', ...
'Struct was encountered where string was expected. Ignoring.');
case isa(object, 'function_handle')
str = ['[@' char(object) ']'];
case ischar(object)
str = object;
otherwise
str = char(object);
end
%% string clean-up
str=str(:); str=str.'; % make sure this is a row vector of char's
if (~isempty(str))
str(str<32|str==127)=' '; % convert no-printable characters to spaces
if (~PreserveSpace)
str = strtrim(str); % remove spaces from begining and the end
str = regexprep(str,'\s+',' '); % remove multiple spaces
end
end
%% =======================================================================
% === var2Namestr Function ==============================================
% =======================================================================
function str = varName2str(str)
% convert matlab variable names to a sting
str = char(str);
p = strfind(str,'0x');
if (~isempty(p))
for i=1:length(p)
before = str( p(i)+(0:3) ); % string to replace
after = char(hex2dec(before(3:4))); % string to replace with
str = regexprep(str,before,after, 'once', 'ignorecase');
p=p-3; % since 4 characters were replaced with one - compensate
end
end
str = regexprep(str,'_COLON_',':', 'once', 'ignorecase');
str = regexprep(str,'_DASH_' ,'-', 'once', 'ignorecase');
|
github
|
claudia-lat/MAPest-master
|
xml_read.m
|
.m
|
MAPest-master/external/xml_io_tools/xml_read.m
| 24,408 |
utf_8
|
4931c3d512db336d744ec43f7fa0b368
|
function [tree, RootName, DOMnode] = xml_read(xmlfile, Pref)
%XML_READ reads xml files and converts them into Matlab's struct tree.
%
% DESCRIPTION
% tree = xml_read(xmlfile) reads 'xmlfile' into data structure 'tree'
%
% tree = xml_read(xmlfile, Pref) reads 'xmlfile' into data structure 'tree'
% according to your preferences
%
% [tree, RootName, DOMnode] = xml_read(xmlfile) get additional information
% about XML file
%
% INPUT:
% xmlfile URL or filename of xml file to read
% Pref Preferences:
% Pref.ItemName - default 'item' - name of a special tag used to itemize
% cell arrays
% Pref.ReadAttr - default true - allow reading attributes
% Pref.ReadSpec - default true - allow reading special nodes
% Pref.Str2Num - default 'smart' - convert strings that look like numbers
% to numbers. Options: "always", "never", and "smart"
% Pref.KeepNS - default true - keep or strip namespace info
% Pref.NoCells - default true - force output to have no cell arrays
% Pref.Debug - default false - show mode specific error messages
% Pref.NumLevels- default infinity - how many recursive levels are
% allowed. Can be used to speed up the function by prunning the tree.
% Pref.RootOnly - default true - output variable 'tree' corresponds to
% xml file root element, otherwise it correspond to the whole file.
% Pref.CellItem - default 'true' - leave 'item' nodes in cell notation.
% OUTPUT:
% tree tree of structs and/or cell arrays corresponding to xml file
% RootName XML tag name used for root (top level) node.
% Optionally it can be a string cell array storing: Name of
% root node, document "Processing Instructions" data and
% document "comment" string
% DOMnode output of xmlread
%
% DETAILS:
% Function xml_read first calls MATLAB's xmlread function and than
% converts its output ('Document Object Model' tree of Java objects)
% to tree of MATLAB struct's. The output is in format of nested structs
% and cells. In the output data structure field names are based on
% XML tags, except in cases when tags produce illegal variable names.
%
% Several special xml node types result in special tags for fields of
% 'tree' nodes:
% - node.CONTENT - stores data section of the node if other fields are
% present. Usually data section is stored directly in 'node'.
% - node.ATTRIBUTE.name - stores node's attribute called 'name'.
% - node.COMMENT - stores node's comment section (string). For global
% comments see "RootName" output variable.
% - node.CDATA_SECTION - stores node's CDATA section (string).
% - node.PROCESSING_INSTRUCTIONS - stores "processing instruction" child
% node. For global "processing instructions" see "RootName" output variable.
% - other special node types like: document fragment nodes, document type
% nodes, entity nodes, notation nodes and processing instruction nodes
% will be treated like regular nodes
%
% EXAMPLES:
% MyTree=[];
% MyTree.MyNumber = 13;
% MyTree.MyString = 'Hello World';
% xml_write('test.xml', MyTree);
% [tree treeName] = xml_read ('test.xml');
% disp(treeName)
% gen_object_display()
% % See also xml_examples.m
%
% See also:
% xml_write, xmlread, xmlwrite
%
% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com
% References:
% - Function inspired by Example 3 found in xmlread function.
% - Output data structures inspired by xml_toolbox structures.
%% default preferences
DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays
DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays
DPref.CellItem = false; % leave 'item' nodes in cell notation
DPref.ReadAttr = true; % allow reading attributes
DPref.ReadSpec = true; % allow reading special nodes: comments, CData, etc.
DPref.KeepNS = true; % Keep or strip namespace info
DPref.Str2Num = 'smart';% convert strings that look like numbers to numbers
DPref.NoCells = true; % force output to have no cell arrays
DPref.NumLevels = 1e10; % number of recurence levels
DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings?
RootOnly = true; % return root node with no top level special nodes
Debug = false; % show specific errors (true) or general (false)?
tree = [];
RootName = [];
%% Check Matlab Version
v = ver('MATLAB');
version = str2double(regexp(v.Version, '\d.\d','match','once'));
if (version<7.1)
error('Your MATLAB version is too old. You need version 7.1 or newer.');
end
%% read user preferences
if (nargin>1)
if (isfield(Pref, 'TableName')), DPref.TableName = Pref.TableName; end
if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end
if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end
if (isfield(Pref, 'Str2Num' )), DPref.Str2Num = Pref.Str2Num ; end
if (isfield(Pref, 'NoCells' )), DPref.NoCells = Pref.NoCells ; end
if (isfield(Pref, 'NumLevels')), DPref.NumLevels = Pref.NumLevels; end
if (isfield(Pref, 'ReadAttr' )), DPref.ReadAttr = Pref.ReadAttr; end
if (isfield(Pref, 'ReadSpec' )), DPref.ReadSpec = Pref.ReadSpec; end
if (isfield(Pref, 'KeepNS' )), DPref.KeepNS = Pref.KeepNS; end
if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end
if (isfield(Pref, 'Debug' )), Debug = Pref.Debug ; end
if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end
end
if ischar(DPref.Str2Num), % convert from character description to numbers
DPref.Str2Num = find(strcmpi(DPref.Str2Num, {'never', 'smart', 'always'}))-1;
if isempty(DPref.Str2Num), DPref.Str2Num=1; end % 1-smart by default
end
%% read xml file using Matlab function
if isa(xmlfile, 'org.apache.xerces.dom.DeferredDocumentImpl');
% if xmlfile is a DOMnode than skip the call to xmlread
try
try
DOMnode = xmlfile;
catch ME
error('Invalid DOM node: \n%s.', getReport(ME));
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
error('Invalid DOM node. \n');
end
else % we assume xmlfile is a filename
if (Debug) % in debuging mode crashes are allowed
DOMnode = xmlread(xmlfile);
else % in normal mode crashes are not allowed
try
try
DOMnode = xmlread(xmlfile);
catch ME
error('Failed to read XML file %s: \n%s',xmlfile, getReport(ME));
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
error('Failed to read XML file %s\n',xmlfile);
end
end
end
Node = DOMnode.getFirstChild;
%% Find the Root node. Also store data from Global Comment and Processing
% Instruction nodes, if any.
GlobalTextNodes = cell(1,3);
GlobalProcInst = [];
GlobalComment = [];
GlobalDocType = [];
while (~isempty(Node))
if (Node.getNodeType==Node.ELEMENT_NODE)
RootNode=Node;
elseif (Node.getNodeType==Node.PROCESSING_INSTRUCTION_NODE)
data = strtrim(char(Node.getData));
target = strtrim(char(Node.getTarget));
GlobalProcInst = [target, ' ', data];
GlobalTextNodes{2} = GlobalProcInst;
elseif (Node.getNodeType==Node.COMMENT_NODE)
GlobalComment = strtrim(char(Node.getData));
GlobalTextNodes{3} = GlobalComment;
% elseif (Node.getNodeType==Node.DOCUMENT_TYPE_NODE)
% GlobalTextNodes{4} = GlobalDocType;
end
Node = Node.getNextSibling;
end
%% parse xml file through calls to recursive DOMnode2struct function
if (Debug) % in debuging mode crashes are allowed
[tree RootName] = DOMnode2struct(RootNode, DPref, 1);
else % in normal mode crashes are not allowed
try
try
[tree RootName] = DOMnode2struct(RootNode, DPref, 1);
catch ME
error('Unable to parse XML file %s: \n %s.',xmlfile, getReport(ME));
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
error('Unable to parse XML file %s.',xmlfile);
end
end
%% If there were any Global Text nodes than return them
if (~RootOnly)
if (~isempty(GlobalProcInst) && DPref.ReadSpec)
t.PROCESSING_INSTRUCTION = GlobalProcInst;
end
if (~isempty(GlobalComment) && DPref.ReadSpec)
t.COMMENT = GlobalComment;
end
if (~isempty(GlobalDocType) && DPref.ReadSpec)
t.DOCUMENT_TYPE = GlobalDocType;
end
t.(RootName) = tree;
tree=t;
end
if (~isempty(GlobalTextNodes))
GlobalTextNodes{1} = RootName;
RootName = GlobalTextNodes;
end
%% =======================================================================
% === DOMnode2struct Function ===========================================
% =======================================================================
function [s TagName LeafNode] = DOMnode2struct(node, Pref, level)
%% === Step 1: Get node name and check if it is a leaf node ==============
[TagName LeafNode] = NodeName(node, Pref.KeepNS);
s = []; % initialize output structure
%% === Step 2: Process Leaf Nodes (nodes with no children) ===============
if (LeafNode)
if (LeafNode>1 && ~Pref.ReadSpec), LeafNode=-1; end % tags only so ignore special nodes
if (LeafNode>0) % supported leaf node types
try
try % use try-catch: errors here are often due to VERY large fields (like images) that overflow java memory
s = char(node.getData);
if (isempty(s)), s = ' '; end % make it a string
% for some reason current xmlread 'creates' a lot of empty text
% fields with first chatacter=10 - those will be deleted.
if (~Pref.PreserveSpace || s(1)==10)
if (isspace(s(1)) || isspace(s(end))), s = strtrim(s); end % trim speces is any
end
if (LeafNode==1), s=str2var(s, Pref.Str2Num, 0); end % convert to number(s) if needed
catch ME % catch for mablab versions 7.5 and higher
warning('xml_io_tools:read:LeafRead', ...
'This leaf node could not be read and was ignored. ');
getReport(ME)
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
warning('xml_io_tools:read:LeafRead', ...
'This leaf node could not be read and was ignored. ');
end
end
if (LeafNode==3) % ProcessingInstructions need special treatment
target = strtrim(char(node.getTarget));
s = [target, ' ', s];
end
return % We are done the rest of the function deals with nodes with children
end
if (level>Pref.NumLevels+1), return; end % if Pref.NumLevels is reached than we are done
%% === Step 3: Process nodes with children ===============================
if (node.hasChildNodes) % children present
Child = node.getChildNodes; % create array of children nodes
nChild = Child.getLength; % number of children
% --- pass 1: how many children with each name -----------------------
f = [];
for iChild = 1:nChild % read in each child
[cname cLeaf] = NodeName(Child.item(iChild-1), Pref.KeepNS);
if (cLeaf<0), continue; end % unsupported leaf node types
if (~isfield(f,cname)),
f.(cname)=0; % initialize first time I see this name
end
f.(cname) = f.(cname)+1; % add to the counter
end % end for iChild
% text_nodes become CONTENT & for some reason current xmlread 'creates' a
% lot of empty text fields so f.CONTENT value should not be trusted
if (isfield(f,'CONTENT') && f.CONTENT>2), f.CONTENT=2; end
% --- pass 2: store all the children as struct of cell arrays ----------
for iChild = 1:nChild % read in each child
[c cname cLeaf] = DOMnode2struct(Child.item(iChild-1), Pref, level+1);
if (cLeaf && isempty(c)) % if empty leaf node than skip
continue; % usually empty text node or one of unhandled node types
elseif (nChild==1 && cLeaf==1)
s=c; % shortcut for a common case
else % if normal node
if (level>Pref.NumLevels), continue; end
n = f.(cname); % how many of them in the array so far?
if (~isfield(s,cname)) % encountered this name for the first time
if (n==1) % if there will be only one of them ...
s.(cname) = c; % than save it in format it came in
else % if there will be many of them ...
s.(cname) = cell(1,n);
s.(cname){1} = c; % than save as cell array
end
f.(cname) = 1; % initialize the counter
else % already have seen this name
s.(cname){n+1} = c; % add to the array
f.(cname) = n+1; % add to the array counter
end
end
end % for iChild
end % end if (node.hasChildNodes)
%% === Step 4: Post-process struct's created for nodes with children =====
if (isstruct(s))
fields = fieldnames(s);
nField = length(fields);
% Detect structure that looks like Html table and store it in cell Matrix
if (nField==1 && strcmpi(fields{1},Pref.TableName{1}))
tr = s.(Pref.TableName{1});
fields2 = fieldnames(tr{1});
if (length(fields2)==1 && strcmpi(fields2{1},Pref.TableName{2}))
% This seems to be a special structure such that for
% Pref.TableName = {'tr','td'} 's' corresponds to
% <tr> <td>M11</td> <td>M12</td> </tr>
% <tr> <td>M12</td> <td>M22</td> </tr>
% Recognize it as encoding for 2D struct
nr = length(tr);
for r = 1:nr
row = tr{r}.(Pref.TableName{2});
Table(r,1:length(row)) = row; %#ok<AGROW>
end
s = Table;
end
end
% --- Post-processing: convert 'struct of cell-arrays' to 'array of structs'
% Example: let say s has 3 fields s.a, s.b & s.c and each field is an
% cell-array with more than one cell-element and all 3 have the same length.
% Then change it to array of structs, each with single cell.
% This way element s.a{1} will be now accessed through s(1).a
vec = zeros(size(fields));
for i=1:nField, vec(i) = f.(fields{i}); end
if (numel(vec)>1 && vec(1)>1 && var(vec)==0) % convert from struct of
s = cell2struct(struct2cell(s), fields, 1); % arrays to array of struct
end % if anyone knows better way to do above conversion please let me know.
end
%% === Step 5: Process nodes with attributes =============================
if (node.hasAttributes && Pref.ReadAttr)
if (~isstruct(s)), % make into struct if is not already
ss.CONTENT=s;
s=ss;
end
Attr = node.getAttributes; % list of all attributes
for iAttr = 1:Attr.getLength % for each attribute
name = char(Attr.item(iAttr-1).getName); % attribute name
name = str2varName(name, Pref.KeepNS); % fix name if needed
value = char(Attr.item(iAttr-1).getValue); % attribute value
value = str2var(value, Pref.Str2Num, 1); % convert to number if possible
s.ATTRIBUTE.(name) = value; % save again
end % end iAttr loop
end % done with attributes
if (~isstruct(s)), return; end %The rest of the code deals with struct's
%% === Post-processing: fields of "s"
% convert 'cell-array of structs' to 'arrays of structs'
fields = fieldnames(s); % get field names
nField = length(fields);
for iItem=1:length(s) % for each struct in the array - usually one
for iField=1:length(fields)
field = fields{iField}; % get field name
% if this is an 'item' field and user want to leave those as cells
% than skip this one
if (strcmpi(field, Pref.ItemName) && Pref.CellItem), continue; end
x = s(iItem).(field);
if (iscell(x) && all(cellfun(@isstruct,x(:))) && numel(x)>1) % it's cell-array of structs
% numel(x)>1 check is to keep 1 cell-arrays created when Pref.CellItem=1
try % this operation fails sometimes
% example: change s(1).a{1}.b='jack'; s(1).a{2}.b='john'; to
% more convinient s(1).a(1).b='jack'; s(1).a(2).b='john';
s(iItem).(field) = [x{:}]'; %#ok<AGROW> % converted to arrays of structs
catch %#ok<CTCH>
% above operation will fail if s(1).a{1} and s(1).a{2} have
% different fields. If desired, function forceCell2Struct can force
% them to the same field structure by adding empty fields.
if (Pref.NoCells)
s(iItem).(field) = forceCell2Struct(x); %#ok<AGROW>
end
end % end catch
end
end
end
%% === Step 4: Post-process struct's created for nodes with children =====
% --- Post-processing: remove special 'item' tags ---------------------
% many xml writes (including xml_write) use a special keyword to mark
% arrays of nodes (see xml_write for examples). The code below converts
% s.item to s.CONTENT
ItemContent = false;
if (isfield(s,Pref.ItemName))
s.CONTENT = s.(Pref.ItemName);
s = rmfield(s,Pref.ItemName);
ItemContent = Pref.CellItem; % if CellItem than keep s.CONTENT as cells
end
% --- Post-processing: clean up CONTENT tags ---------------------
% if s.CONTENT is a cell-array with empty elements at the end than trim
% the length of this cell-array. Also if s.CONTENT is the only field than
% remove .CONTENT part and store it as s.
if (isfield(s,'CONTENT'))
if (iscell(s.CONTENT) && isvector(s.CONTENT))
x = s.CONTENT;
for i=numel(x):-1:1, if ~isempty(x{i}), break; end; end
if (i==1 && ~ItemContent)
s.CONTENT = x{1}; % delete cell structure
else
s.CONTENT = x(1:i); % delete empty cells
end
end
if (nField==1)
if (ItemContent)
ss = s.CONTENT; % only child: remove a level but ensure output is a cell-array
s=[]; s{1}=ss;
else
s = s.CONTENT; % only child: remove a level
end
end
end
%% =======================================================================
% === forceCell2Struct Function =========================================
% =======================================================================
function s = forceCell2Struct(x)
% Convert cell-array of structs, where not all of structs have the same
% fields, to a single array of structs
%% Convert 1D cell array of structs to 2D cell array, where each row
% represents item in original array and each column corresponds to a unique
% field name. Array "AllFields" store fieldnames for each column
AllFields = fieldnames(x{1}); % get field names of the first struct
CellMat = cell(length(x), length(AllFields));
for iItem=1:length(x)
fields = fieldnames(x{iItem}); % get field names of the next struct
for iField=1:length(fields) % inspect all fieldnames and find those
field = fields{iField}; % get field name
col = find(strcmp(field,AllFields),1);
if isempty(col) % no column for such fieldname yet
AllFields = [AllFields; field]; %#ok<AGROW>
col = length(AllFields); % create a new column for it
end
CellMat{iItem,col} = x{iItem}.(field); % store rearanged data
end
end
%% Convert 2D cell array to array of structs
s = cell2struct(CellMat, AllFields, 2);
%% =======================================================================
% === str2var Function ==================================================
% =======================================================================
function val=str2var(str, option, attribute)
% Can this string 'str' be converted to a number? if so than do it.
val = str;
len = numel(str);
if (len==0 || option==0), return; end % Str2Num="never" of empty string -> do not do enything
if (len>10000 && option==1), return; end % Str2Num="smart" and string is very long -> probably base64 encoded binary
digits = '(Inf)|(NaN)|(pi)|[\t\n\d\+\-\*\.ei EI\[\]\;\,]';
s = regexprep(str, digits, ''); % remove all the digits and other allowed characters
if (~all(~isempty(s))) % if nothing left than this is probably a number
if (~isempty(strfind(str, ' '))), option=2; end %if str has white-spaces assume by default that it is not a date string
if (~isempty(strfind(str, '['))), option=2; end % same with brackets
str(strfind(str, '\n')) = ';';% parse data tables into 2D arrays, if any
if (option==1) % the 'smart' option
try % try to convert to a date, like 2007-12-05
datenum(str); % if successful than leave it as string
catch %#ok<CTCH> % if this is not a date than ...
option=2; % ... try converting to a number
end
end
if (option==2)
if (attribute)
num = str2double(str); % try converting to a single number using sscanf function
if isnan(num), return; end % So, it wasn't really a number after all
else
num = str2num(str); %#ok<ST2NM> % try converting to a single number or array using eval function
end
if(isnumeric(num) && numel(num)>0), val=num; end % if convertion to a single was succesful than save
end
elseif ((str(1)=='[' && str(end)==']') || (str(1)=='{' && str(end)=='}')) % this looks like a (cell) array encoded as a string
try
val = eval(str);
catch %#ok<CTCH>
val = str;
end
elseif (~attribute) % see if it is a boolean array with no [] brackets
str1 = lower(str);
str1 = strrep(str1, 'false', '0');
str1 = strrep(str1, 'true' , '1');
s = regexprep(str1, '[01 \;\,]', ''); % remove all 0/1, spaces, commas and semicolons
if (~all(~isempty(s))) % if nothing left than this is probably a boolean array
num = str2num(str1); %#ok<ST2NM>
if(isnumeric(num) && numel(num)>0), val = (num>0); end % if convertion was succesful than save as logical
end
end
%% =======================================================================
% === str2varName Function ==============================================
% =======================================================================
function str = str2varName(str, KeepNS)
% convert a sting to a valid matlab variable name
if(KeepNS)
str = regexprep(str,':','_COLON_', 'once', 'ignorecase');
else
k = strfind(str,':');
if (~isempty(k))
str = str(k+1:end);
end
end
str = regexprep(str,'-','_DASH_' ,'once', 'ignorecase');
if (~isvarname(str)) && (~iskeyword(str))
str = genvarname(str);
end
%% =======================================================================
% === NodeName Function =================================================
% =======================================================================
function [Name LeafNode] = NodeName(node, KeepNS)
% get node name and make sure it is a valid variable name in Matlab.
% also get node type:
% LeafNode=0 - normal element node,
% LeafNode=1 - text node
% LeafNode=2 - supported non-text leaf node,
% LeafNode=3 - supported processing instructions leaf node,
% LeafNode=-1 - unsupported non-text leaf node
switch (node.getNodeType)
case node.ELEMENT_NODE
Name = char(node.getNodeName);% capture name of the node
Name = str2varName(Name, KeepNS); % if Name is not a good variable name - fix it
LeafNode = 0;
case node.TEXT_NODE
Name = 'CONTENT';
LeafNode = 1;
case node.COMMENT_NODE
Name = 'COMMENT';
LeafNode = 2;
case node.CDATA_SECTION_NODE
Name = 'CDATA_SECTION';
LeafNode = 2;
case node.DOCUMENT_TYPE_NODE
Name = 'DOCUMENT_TYPE';
LeafNode = 2;
case node.PROCESSING_INSTRUCTION_NODE
Name = 'PROCESSING_INSTRUCTION';
LeafNode = 3;
otherwise
NodeType = {'ELEMENT','ATTRIBUTE','TEXT','CDATA_SECTION', ...
'ENTITY_REFERENCE', 'ENTITY', 'PROCESSING_INSTRUCTION', 'COMMENT',...
'DOCUMENT', 'DOCUMENT_TYPE', 'DOCUMENT_FRAGMENT', 'NOTATION'};
Name = char(node.getNodeName);% capture name of the node
warning('xml_io_tools:read:unkNode', ...
'Unknown node type encountered: %s_NODE (%s)', NodeType{node.getNodeType}, Name);
LeafNode = -1;
end
|
github
|
claudia-lat/MAPest-master
|
valueFromName.m
|
.m
|
MAPest-master/src/valueFromName.m
| 178 |
utf_8
|
1a145d50bb61efd5b8dec292d6ed8dbf
|
function [indx] = valueFromName(VectorOfString, stringName)
for i = 1: length(VectorOfString)
if strcmp(VectorOfString(i,:), stringName)
indx = i;
break;
end
end
|
github
|
claudia-lat/MAPest-master
|
MAPcomputation.m
|
.m
|
MAPest-master/src/MAPcomputation.m
| 7,376 |
utf_8
|
6d2ded5dfa4746710cb6be336151d93f
|
function [mu_dgiveny, Sigma_dgiveny] = MAPcomputation(berdy, state, y, priors, varargin)
% MAPCOMPUTATION solves the inverse dynamics problem with a
% maximum-a-posteriori estimation by using the Newton-Euler algorithm and
% redundant sensor measurements as originally described in the paper
% [Whole-Body Human Inverse Dynamics with Distributed Micro-Accelerometers,
% Gyros and Force Sensing,Latella, C.; Kuppuswamy, N.; Romano, F.;
% Traversaro, S.; Nori, F.,Sensors 2016, 16, 727].
%
% Considering a generic multibody model composed by n moving rigid bodies
% (i.e. links) connected by joints and being in the Gaussian framework,
% the output 'mu_dgiveny' coincides with the vector 'd' structured as
% follows:
% d = [d_1, d_2, ..., d_n], i = 1,...,n
%
% where:
% d_i = [a_i, fB_i, f_i, tau_i, fx_i, ddq_i]
%
% and a_i is the link-i spatial acceleration, fB_i is the net spatial
% force on the link-i, f_i is spatial wrench transmitted to link-i from
% its parent, tau_i is torque on joint-i, fx_i is the external force on
% link-i and ddq_i is acceleration of joint-i.
% The relationship between d and the sensor measurements y is given by
%
% Y(q, dq) d + b_Y = y (1)
%
% where the matrix Y(q, dq), is represented as a sparse matrix. Moreover,
% the variables in d should satisfy the Newton-Euler equations
%
% D(q,dq) d + b_D(q, dq) = 0 (2)
%
% again represented as a sparse matrix.
% By stacking together the MEASUREMENTS EQUATIONS (1) and CONSTRAINTS
% EQUATIONS (2)the system that MAP solves is obtained.
% -------------------------------------------------------------------------
% NOTE:
% The function provides an option to remove a specified sensor from the
% analysis. By default, MAP is
% computed by using all the sensors (i.e. the full vector of y
% measurements). If the sensor to remove is specified in the option , MAP
% loads the full y and then remove automatically values related to that
% sensor and the related block variance from the Sigmay.
% -------------------------------------------------------------------------
options = struct( ...
'SENSORS_TO_REMOVE', []...
);
% read the acceptable names
optionNames = fieldnames(options);
% count arguments
nArgs = length(varargin);
if round(nArgs/2)~=nArgs/2
error('createXsensLikeURDFmodel needs propertyName/propertyValue pairs')
end
for pair = reshape(varargin,2,[]) % pair is {propName;propValue}
inpName = upper(pair{1}); % make case insensitive
if any(strcmp(inpName,optionNames))
% overwrite options. If you want you can test for the right class here
% Also, if you find out that there is an option you keep getting wrong,
% you can use "if strcmp(inpName,'problemOption'),testMore,end"-statements
options.(inpName) = pair{2};
else
error('%s is not a recognized parameter name',inpName)
end
end
%%
rangeOfRemovedSensors = [];
for i = 1 : size(options.SENSORS_TO_REMOVE)
ithSensor = options.SENSORS_TO_REMOVE(i);
[index, len] = rangeOfSensorMeasurement( berdy, ithSensor.type, ithSensor.id);
rangeOfRemovedSensors = [rangeOfRemovedSensors, index : index + len - 1];
end
y(rangeOfRemovedSensors,:) = [];
priors.Sigmay(rangeOfRemovedSensors, :) = []; % TO BE CHECKED!
priors.Sigmay(:, rangeOfRemovedSensors) = []; % TO BE CHECKED!
%%
% Set gravity
gravity = [0 0 -9.81];
grav = iDynTree.Vector3();
grav.fromMatlab(gravity);
% Set matrices
berdyMatrices = struct;
berdyMatrices.D = iDynTree.MatrixDynSize();
berdyMatrices.b_D = iDynTree.VectorDynSize();
berdyMatrices.Y = iDynTree.MatrixDynSize();
berdyMatrices.b_Y = iDynTree.VectorDynSize();
berdy.resizeAndZeroBerdyMatrices(berdyMatrices.D,...
berdyMatrices.b_D,...
berdyMatrices.Y,...
berdyMatrices.b_Y);
% Set priors
mud = priors.mud;
Sigmad_inv = sparse(inv(priors.Sigmad));
SigmaD_inv = sparse(inv(priors.SigmaD));
Sigmay_inv = sparse(inv(priors.Sigmay));
% Allocate outputs
samples = size(y, 2);
nrOfDynVariables = berdy.getNrOfDynamicVariables();
mu_dgiveny = zeros(nrOfDynVariables, samples);
% Sigma_dgiveny = sparse(nrOfDynVariables, nrOfDynVariables, samples);
Sigma_dgiveny = cell(samples,1);
% MAP Computation
q = iDynTree.JointPosDoubleArray(berdy.model());
dq = iDynTree.JointDOFsDoubleArray(berdy.model());
for i = 1 : samples
q.fromMatlab(state.q(:,i));
dq.fromMatlab(state.dq(:,i));
berdy.updateKinematicsFromTraversalFixedBase(q,dq,grav);
berdy.getBerdyMatrices(berdyMatrices.D,...
berdyMatrices.b_D,...
berdyMatrices.Y,...
berdyMatrices.b_Y);
D = sparse(berdyMatrices.D.toMatlab());
b_D = berdyMatrices.b_D.toMatlab();
Y_nonsparse = berdyMatrices.Y.toMatlab();
Y_nonsparse(rangeOfRemovedSensors, :) = [];
Y = sparse(Y_nonsparse);
b_Y = berdyMatrices.b_Y.toMatlab();
b_Y(rangeOfRemovedSensors) = [];
% Check on the [Y; D] matrix rank
if (i==1)
bigMatrix = full([Y; D]);
rowsOfbigMatrix = size(bigMatrix,1);
columnsOfbigMatrix = size(bigMatrix,2);
% svd
% [U_bigMatrix,S_bigMatrix,V_bigMatrix] = svd(bigMatrix);
svd_bigMatrix = svd(bigMatrix);
rank_bigMatrix = nnz(svd_bigMatrix);
if (rowsOfbigMatrix > columnsOfbigMatrix)
if rank_bigMatrix == nrOfDynVariables
disp('[Info] [Y; D] is a full rank matrix with rows > columns');
else
disp('[Info] [Y; D] is a matrix with rows > columns');
end
else
error('[Info] [Y; D] is a matrix with rows < columns! Check the matrix!!');
end
end
SigmaBarD_inv = D' * SigmaD_inv * D + Sigmad_inv;
% the permutation matrix for SigmaBarD_inv is computed only for the first
% sample, beacuse this matrix does not change in the experiment
if (i==1)
[~,~,PBarD]= chol(SigmaBarD_inv);
end
rhsBarD = Sigmad_inv * mud - D' * (SigmaD_inv * b_D);
muBarD = CholSolve(SigmaBarD_inv , rhsBarD, PBarD);
Sigma_dgiveny_inv = SigmaBarD_inv + Y' * Sigmay_inv * Y;
% the permutation matrix for Sigma_dgiveny_inv is computed only for the first
% sample, beacuse this matrix does not change in the experiment
if (i==1)
[~,~,P]= chol(Sigma_dgiveny_inv);
end
rhs = Y' * (Sigmay_inv * (y(:,i) - b_Y)) + SigmaBarD_inv * muBarD;
if nargout > 1 % Sigma_dgiveny requested as output
Sigma_dgiveny{i} = inv(Sigma_dgiveny_inv);
mu_dgiveny(:,i) = Sigma_dgiveny{i} * rhs;
else % Sigma_dgiveny does not requested as output
mu_dgiveny(:,i) = CholSolve(Sigma_dgiveny_inv, rhs, P);
end
end
end
function [x] = CholSolve(A, b, P)
if ~issymmetric(A)
A = (A+A')/2;
end
C = P'*A*P; % P is given as input
[R] = chol(C); % R is such that R'*R = P'*C*P
w_forward = P\b;
z_forward = R'\w_forward;
y_forward = R\z_forward;
x = P'\y_forward;
end
|
github
|
claudia-lat/MAPest-master
|
MAPcomputation_floating.m
|
.m
|
MAPest-master/src/MAPcomputation_floating.m
| 7,460 |
utf_8
|
f999fc5c938e82433f426e49b548f996
|
function [mu_dgiveny, Sigma_dgiveny] = MAPcomputation_floating(berdy, traversal, state, y, priors, baseAngVel, varargin)
% MAPCOMPUTATION_FLOATING solves the inverse dynamics problem with a
% maximum-a-posteriori estimation by using the Newton-Euler algorithm and
% redundant sensor measurements as originally described in the paper
% [Whole-Body Human Inverse Dynamics with Distributed Micro-Accelerometers,
% Gyros and Force Sensing,Latella, C.; Kuppuswamy, N.; Romano, F.;
% Traversaro, S.; Nori, F.,Sensors 2016, 16, 727] by considering a
% floating-base formalism.
%
% Considering a generic multibody model composed by n moving rigid bodies
% (i.e. links) connected by joints and being in the Gaussian framework,
% the output 'mu_dgiveny' coincides with the vector 'd' structured as
% follows:
% d = [d_1, d_2, ..., d_n], i = 1,...,n
%
% where:
% d_i = [a_i, fB_i, f_i, tau_i, fx_i, ddq_i]
%
% and a_i is the link-i spatial acceleration, fB_i is the net spatial
% force on the link-i, f_i is spatial wrench transmitted to link-i from
% its parent, tau_i is torque on joint-i, fx_i is the external force on
% link-i and ddq_i is acceleration of joint-i.
% The relationship between d and the sensor measurements y is given by
%
% Y(q, dq) d + b_Y = y (1)
%
% where the matrix Y(q, dq), is represented as a sparse matrix. Moreover,
% the variables in d should satisfy the Newton-Euler equations
%
% D(q,dq) d + b_D(q, dq) = 0 (2)
%
% again represented as a sparse matrix.
% By stacking together the MEASUREMENTS EQUATIONS (1) and CONSTRAINTS
% EQUATIONS (2)the system that MAP solves is obtained.
% -------------------------------------------------------------------------
% NOTE:
% The function provides an option to remove a specified sensor from the
% analysis. By default, MAP is
% computed by using all the sensors (i.e. the full vector of y
% measurements). If the sensor to remove is specified in the option , MAP
% loads the full y and then remove automatically values related to that
% sensor and the related block variance from the Sigmay.
% -------------------------------------------------------------------------
options = struct( ...
'SENSORS_TO_REMOVE', []...
);
% read the acceptable names
optionNames = fieldnames(options);
% count arguments
nArgs = length(varargin);
if round(nArgs/2)~=nArgs/2
error('createXsensLikeURDFmodel needs propertyName/propertyValue pairs')
end
for pair = reshape(varargin,2,[]) % pair is {propName;propValue}
inpName = upper(pair{1}); % make case insensitive
if any(strcmp(inpName,optionNames))
% overwrite options. If you want you can test for the right class here
% Also, if you find out that there is an option you keep getting wrong,
% you can use "if strcmp(inpName,'problemOption'),testMore,end"-statements
options.(inpName) = pair{2};
else
error('%s is not a recognized parameter name',inpName)
end
end
%%
rangeOfRemovedSensors = [];
for i = 1 : size(options.SENSORS_TO_REMOVE)
ithSensor = options.SENSORS_TO_REMOVE(i);
[index, len] = rangeOfSensorMeasurement( berdy, ithSensor.type, ithSensor.id);
rangeOfRemovedSensors = [rangeOfRemovedSensors, index : index + len - 1];
end
y(rangeOfRemovedSensors,:) = [];
priors.Sigmay(rangeOfRemovedSensors, :) = [];
priors.Sigmay(:, rangeOfRemovedSensors) = [];
%%
% % Set angularVector
% angVect = [0 0 0];
% omega = iDynTree.Vector3();
% omega.fromMatlab(angVect);
% Set matrices
berdyMatrices = struct;
berdyMatrices.D = iDynTree.MatrixDynSize();
berdyMatrices.b_D = iDynTree.VectorDynSize();
berdyMatrices.Y = iDynTree.MatrixDynSize();
berdyMatrices.b_Y = iDynTree.VectorDynSize();
berdy.resizeAndZeroBerdyMatrices(berdyMatrices.D,...
berdyMatrices.b_D,...
berdyMatrices.Y,...
berdyMatrices.b_Y);
% Set priors
mud = priors.mud;
Sigmad_inv = sparse(inv(priors.Sigmad));
SigmaD_inv = sparse(inv(priors.SigmaD));
Sigmay_inv = sparse(inv(priors.Sigmay));
% Allocate outputs
samples = size(y, 2);
nrOfDynVariables = berdy.getNrOfDynamicVariables();
mu_dgiveny = zeros(nrOfDynVariables, samples);
% Sigma_dgiveny = sparse(nrOfDynVariables, nrOfDynVariables, samples);
Sigma_dgiveny = cell(samples,1);
% MAP Computation
q = iDynTree.JointPosDoubleArray(berdy.model());
dq = iDynTree.JointDOFsDoubleArray(berdy.model());
currentBase = berdy.model().getLinkName(traversal.getBaseLink().getIndex());
baseIndex = berdy.model().getFrameIndex(currentBase);
base_angVel = iDynTree.Vector3();
for i = 1 : samples
q.fromMatlab(state.q(:,i));
dq.fromMatlab(state.dq(:,i));
base_angVel.fromMatlab(baseAngVel(:,i));
berdy.updateKinematicsFromFloatingBase(q,dq,baseIndex,base_angVel);
berdy.getBerdyMatrices(berdyMatrices.D,...
berdyMatrices.b_D,...
berdyMatrices.Y,...
berdyMatrices.b_Y);
D = sparse(berdyMatrices.D.toMatlab());
b_D = berdyMatrices.b_D.toMatlab();
Y_nonsparse = berdyMatrices.Y.toMatlab();
Y_nonsparse(rangeOfRemovedSensors, :) = [];
Y = sparse(Y_nonsparse);
b_Y = berdyMatrices.b_Y.toMatlab();
b_Y(rangeOfRemovedSensors) = [];
% Check on the [Y; D] matrix rank
if (i==1)
bigMatrix = full([Y; D]);
rowsOfbigMatrix = size(bigMatrix,1);
columnsOfbigMatrix = size(bigMatrix,2);
% svd
% [U_bigMatrix,S_bigMatrix,V_bigMatrix] = svd(bigMatrix);
svd_bigMatrix = svd(bigMatrix);
rank_bigMatrix = nnz(svd_bigMatrix);
if (rowsOfbigMatrix > columnsOfbigMatrix)
if rank_bigMatrix == nrOfDynVariables
disp('[Info] [Y; D] is a full rank matrix with rows > columns');
else
disp('[Info] [Y; D] is a matrix with rows > columns');
end
else
error('[Info] [Y; D] is a matrix with rows < columns! Check the matrix!!');
end
end
SigmaBarD_inv = D' * SigmaD_inv * D + Sigmad_inv;
% the permutation matrix for SigmaBarD_inv is computed only for the first
% sample, beacuse this matrix does not change in the experiment
if (i==1)
[~,~,PBarD]= chol(SigmaBarD_inv);
end
rhsBarD = Sigmad_inv * mud - D' * (SigmaD_inv * b_D);
muBarD = CholSolve(SigmaBarD_inv , rhsBarD, PBarD);
Sigma_dgiveny_inv = SigmaBarD_inv + Y' * Sigmay_inv * Y;
% the permutation matrix for Sigma_dgiveny_inv is computed only for the first
% sample, beacuse this matrix does not change in the experiment
if (i==1)
[~,~,P]= chol(Sigma_dgiveny_inv);
end
rhs = Y' * (Sigmay_inv * (y(:,i) - b_Y)) + SigmaBarD_inv * muBarD;
if nargout > 1 % Sigma_dgiveny requested as output
Sigma_dgiveny{i} = inv(Sigma_dgiveny_inv);
mu_dgiveny(:,i) = Sigma_dgiveny{i} * rhs;
else % Sigma_dgiveny does not requested as output
mu_dgiveny(:,i) = CholSolve(Sigma_dgiveny_inv, rhs, P);
end
end
end
function [x] = CholSolve(A, b, P)
if ~issymmetric(A)
A = (A+A')/2;
end
C = P'*A*P; % P is given as input
[R] = chol(C); % R is such that R'*R = P'*C*P
w_forward = P\b;
z_forward = R'\w_forward;
y_forward = R\z_forward;
x = P'\y_forward;
end
|
github
|
claudia-lat/MAPest-master
|
matchOrderToTraversal.m
|
.m
|
MAPest-master/src/matchOrderToTraversal.m
| 647 |
utf_8
|
404c4d927481166123de53813847d5b3
|
function [ orderedData ] = matchOrderToTraversal( originalOrder, originalData, finalOrder )
%UNTITLED5 Summary of this function goes here
% Detailed explanation goes here
orderedData = zeros(size(originalData));
for i = 1 : length(finalOrder)
index = indexOfString (originalOrder, finalOrder{i});
orderedData(i,:) = originalData(index,:);
end
end
function [ index ] = indexOfString ( cellArray, stringName)
%UNTITLED5 Summary of this function goes here
% Detailed explanation goes here
index = -1;
for i = 1 : length(cellArray)
if strcmp (cellArray{i}, stringName)
index = i;
break;
end
end
end
|
github
|
claudia-lat/MAPest-master
|
computeSuitSensorPosition.m
|
.m
|
MAPest-master/Experiments/23links_human/src/computeSuitSensorPosition.m
| 1,530 |
utf_8
|
2ac3f049adfb5cd57aa88a128a0911a9
|
function [suit] = computeSuitSensorPosition(suit, len)
% COMPUTESUITSENSORPOSITION computes the position of the sensors in the
% suit wrt the link frame. It returns its value in a new field of the same
% suit stucture. Notation: G = global, S = sensor; L = link.
% NOTE: Check/modify manually len value. You can decide to insert a fixed
% number of frames useful to capture all the movements performed during
% your own experiment.
for sIdx = 1: suit.properties.nrOfSensors
sensor = suit.sensors{sIdx};
[link, ~] = linksFromName(suit.links, sensor.attachedLink);
A = zeros(3*len,3);
b = zeros(3*len,1);
for i = 1 : len
S1 = skewMatrix(link.meas.angularAcceleration(:,i));
S2 = skewMatrix(link.meas.angularVelocity(:,i));
G_R_L_mat = quat2Mat(link.meas.orientation(:,i));
A(3*i-2:3*i,:) = (S1 + S2*S2) * G_R_L_mat;
G_acc_S = sensor.meas.sensorFreeAcceleration(:,i);
G_acc_L = link.meas.acceleration(:,i);
b(3*i-2:3*i) = G_acc_S - G_acc_L;
G_R_S_mat = quat2Mat(sensor.meas.sensorOrientation(:,i));
S_R_L = G_R_S_mat' * G_R_L_mat;
L_RPY_S(i,:) = mat2RPY(S_R_L'); %RPY in rad
end
% matrix system
B_pos_SL = A\b;
sensor.origin = B_pos_SL;
suit.sensors{sIdx}.position = sensor.origin;
suit.sensors{sIdx}.RPY = mean(L_RPY_S);
end
end
function [ S ] = skewMatrix(x)
%SKEWMATRIX computes the skew matrix given a vector x 3x1
S = [ 0 -x(3) x(2);
x(3) 0 -x(1);
-x(2) x(1) 0 ];
end
|
github
|
gkaguirrelab/WheresWaldo_EyeTracking-master
|
preprocessEyetracking_general.m
|
.m
|
WheresWaldo_EyeTracking-master/preprocessEyetracking_general.m
| 4,810 |
utf_8
|
2b71cc5847e1848c4fbf6c63bcb7d900
|
function preprocessEyetracking_general(subFolder,saveME)
%%function for preprocessing LiveTrack eye tracking data.
%expects data to be in the form output from HID2struct
%subFolder is a string of the directory name containing t he data to be
%analyzed
%saveME is either 1 or 0, depending if you want to save outputs, including
%calibrated position data, and a logical indicating i blinks occur
% Get Calibration Matrices
calibrationMatrices = dir([subFolder '/*cal*.mat']);
calNames = cat(2,{calibrationMatrices(:).name});
% Get targets
targets = dir([subFolder '/*dat*.mat']);
targetNames = cat(2,{targets(:).name});
% Rip calibration times from name
calTimes = nan(1,length(calNames));
for i = 1:length(calNames)
calTimes(i) = str2num(calNames{i}(find('_' == calNames{i},1,'last')+1:find('.' == calNames{i},1,'last')-1));
end
rawData = dir([subFolder '/*REPORT*.mat']);
for dataName = cat(2,{rawData(:).name})
runNumber = find(ismember(cat(2,{rawData(:).name}),dataName));
% load data
dat = load([subFolder '/' dataName{1}]);
dat = dat.Report;
rawX = cat(1,dat.PupilCameraX_Ch01);
rawY = cat(1,dat.PupilCameraY_Ch01);
glintX = cat(1,dat.Glint1CameraX_Ch01);
glintY = cat(1,dat.Glint1CameraY_Ch01);
isBlink = ~cat(1,dat.PupilTracked_Ch01);
% Linearly interpolate blinks
[linX linY] = linterpBlinkGaps(rawX,rawY,isBlink);
[linGlintX linGlintY] = linterpBlinkGaps(glintX,glintY,isBlink);
% Load the appropriate calibration matrix
datTime = str2num(dataName{1}(find('_' == dataName{1},1,'last')+1:find('.' == dataName{1},1,'last')-1));
calMatInd = find(calTimes<datTime & calTimes==max(calTimes(calTimes<datTime)));
calMat = load([subFolder '/' calNames{calMatInd}]);
Rpc = calMat.Rpc;
calMat = calMat.CalMat;
tar = load([subFolder '/' targetNames{calMatInd}]);
% Transform data with calibration matrix
tmp = calMat*[([linX-linGlintX]./Rpc)'; ([linY-linGlintY]./Rpc)'; ...
(1-sqrt(([linX-linGlintX]./Rpc).^2 + ([linY-linGlintY]./Rpc).^2))'; ones(1,length(linX))];
calibratedXYZ = [bsxfun(@rdivide,tmp(1:3,:),tmp(4,:))]';
[movementAngle b] = cart2pol(diff(calibratedXYZ(:,1)),diff(calibratedXYZ(:,2)));
movementSpeed = (sqrt((diff(calibratedXYZ(:,1)).^2+diff(calibratedXYZ(:,2)).^2)));
%% Make Plots
figure(1)
%set(gcf,'position',[50 50 900 600])
subplot(1,3,1)
plot(rawX,rawY)
axis equal
title('Raw Data')
axis square
subplot(1,3,2)
plot(linX,linY)
axis equal
title('Linearly Interpolated Data')
axis square
subplot(1,3,3)
plot(calibratedXYZ(:,1),calibratedXYZ(:,2))
axis equal
title('Calibrated Data')
axis square
%% Write Output
if saveME
subName = subFolder(find(subFolder=='/',1,'last')+1:end);
save(['CalibratedEyetrackingData/' subName '_CalibratedData_Run_' num2str(runNumber)],'calibratedXYZ','isBlink');
if ~isdir(['Plots/' subName])
mkdir(['Plots/' subName]);
end
outP = ['Plots/' subName '/Eyetracking_Descriptives_Run_' num2str(runNumber)];
drawnow;
print(outP,'-dtiff','-r300')
close all
drawnow;
end
end
end
%% Linearly interpolate tracking gaps caused by blinking
function [linX linY] = linterpBlinkGaps(x,y,isB)
linX = x;
linY = y;
oldIsB = isB;
while any(isB)
% Get first unlinterped blink
startBlink = find(isB,1,'first');
if startBlink == length(isB)
finishBlink = 0;
else
finishBlink = find(~isB(startBlink+1:end),1,'first')-1;
if isempty(finishBlink)
finishBlink = length(isB(startBlink+1:end));
end
end
linInds = startBlink:startBlink+finishBlink;
% Interpolation values (edge cases if blinks are at the beginning
% or end dealt with by just setting all to the neighboring value)
%% Dumb edge case stuff
try
xIn1 = x(linInds(1)-1);
catch
xIn1 = nan;
end
try
xIn2 = x(linInds(end)+1);
catch
xIn2 = nan;
end
try
yIn1 = y(linInds(1)-1);
catch
yIn1 = nan;
end
try
yIn2 = y(linInds(end)+1);
catch
yIn2 = nan;
end
if isnan(xIn1)
xIn1 = xIn2;
end
if isnan(xIn2)
xIn2 = xIn1;
end
if isnan(yIn1)
yIn1 = yIn2;
end
if isnan(yIn2)
yIn2 = yIn1;
end
%% Interpolate
linX(linInds) = linterp([linInds(1)-1 linInds(end)+1],[xIn1 xIn2],linInds);
linY(linInds) = linterp([linInds(1)-1 linInds(end)+1],[yIn1 yIn2],linInds);
% Remove the interpolated blink
isB(linInds) = false;
end
end
|
github
|
gkaguirrelab/WheresWaldo_EyeTracking-master
|
preprocessEyetracking.m
|
.m
|
WheresWaldo_EyeTracking-master/preprocessEyetracking.m
| 5,710 |
utf_8
|
263e05e962fbfa001b851da6499cf84f
|
function preprocessEyetracking(subFolder)
% Get Calibration Matrices
calibrationMatrices = dir([subFolder '/*cal*.mat']);
calNames = cat(2,{calibrationMatrices(:).name});
% Get targets
targets = dir([subFolder '/*dat*.mat']);
targetNames = cat(2,{targets(:).name});
% Rip calibration times from name
calTimes = nan(1,length(calNames));
for i = 1:length(calNames)
calTimes(i) = str2num(calNames{i}(find('_' == calNames{i},1,'last')+1:find('.' == calNames{i},1,'last')-1));
end
rawData = dir([subFolder '/*REPORT*.mat']);
for dataName = cat(2,{rawData(:).name})
runNumber = find(ismember(cat(2,{rawData(:).name}),dataName));
% load data
dat = load([subFolder '/' dataName{1}]);
dat = dat.Report;
rawX = cat(1,dat.PupilCameraX_Ch01);
rawY = cat(1,dat.PupilCameraY_Ch01);
glintX = cat(1,dat.Glint1CameraX_Ch01);
glintY = cat(1,dat.Glint1CameraY_Ch01);
isBlink = ~cat(1,dat.PupilTracked_Ch01);
% Linearly interpolate blinks
[linX linY] = linterpBlinkGaps(rawX,rawY,isBlink);
[linGlintX linGlintY] = linterpBlinkGaps(glintX,glintY,isBlink);
% Load the appropriate calibration matrix
datTime = str2num(dataName{1}(find('_' == dataName{1},1,'last')+1:find('.' == dataName{1},1,'last')-1));
calMatInd = find(calTimes<datTime & calTimes==max(calTimes(calTimes<datTime)));
calMat = load([subFolder '/' calNames{calMatInd}]);
Rpc = calMat.Rpc;
calMat = calMat.CalMat;
tar = load([subFolder '/' targetNames{calMatInd}]);
% Transform data with calibration matrix
tmp = calMat*[([linX-linGlintX]./Rpc)'; ([linY-linGlintY]./Rpc)'; ...
(1-sqrt(([linX-linGlintX]./Rpc).^2 + ([linY-linGlintY]./Rpc).^2))'; ones(1,length(linX))];
calibratedXYZ = [bsxfun(@rdivide,tmp(1:3,:),tmp(4,:))]';
[movementAngle b] = cart2pol(diff(calibratedXYZ(:,1)),diff(calibratedXYZ(:,2)));
movementSpeed = (sqrt((diff(calibratedXYZ(:,1)).^2+diff(calibratedXYZ(:,2)).^2)));
%% Make Plots
figure(1)
set(gcf,'position',[50 50 900 600])
subplot(2,3,1)
plot(rawX,rawY)
axis equal
title('Raw Data')
subplot(2,3,2)
plot(linX,linY)
axis equal
title('Linearly Interpolated Data')
subplot(2,3,3)
plot(calibratedXYZ(:,1),calibratedXYZ(:,2))
axis equal
title('Calibrated Data')
% subplot(2,3,4)
% polarHeatmap(movementAngle,movementSpeed,[0:pi.*2./24:pi*2]-pi,[0 10000]);
% title('Movement Angle');
% colorbar
subplot(2,3,6)
polarHeatmap(movementAngle,movementSpeed,[0:pi.*2./24:pi*2]-pi,0:2:36);
title('Movement Angle x Speed');
colorbar
%% Make Regressors
regressors.movementAngle_sin = sin(movementAngle.*6);
regressors.movementAngle_cos = cos(movementAngle.*6);
regressors.speed = movementSpeed;
%% Write Output
subName = subFolder(find(subFolder=='/',1,'last')+1:end);
save(['CalibratedEyetrackingData/' subName '_CalibratedData_Run_' num2str(runNumber)],'calibratedXYZ','isBlink','regressors');
if ~isdir(['Plots/' subName])
mkdir(['Plots/' subName]);
end
outP = ['Plots/' subName '/Eyetracking_Descriptives_Run_' num2str(runNumber)];
drawnow;
print(outP,'-dtiff','-r300')
close all
drawnow;
end
end
%% Linearly interpolate tracking gaps caused by blinking
function [linX linY] = linterpBlinkGaps(x,y,isB)
linX = x;
linY = y;
oldIsB = isB;
while any(isB)
% Get first unlinterped blink
startBlink = find(isB,1,'first');
if startBlink == length(isB)
finishBlink = 0;
else
finishBlink = find(~isB(startBlink+1:end),1,'first')-1;
if isempty(finishBlink)
finishBlink = length(isB(startBlink+1:end));
end
end
linInds = startBlink:startBlink+finishBlink;
% Interpolation values (edge cases if blinks are at the beginning
% or end dealt with by just setting all to the neighboring value)
%% Dumb edge case stuff
try
xIn1 = x(linInds(1)-1);
catch
xIn1 = nan;
end
try
xIn2 = x(linInds(end)+1);
catch
xIn2 = nan;
end
try
yIn1 = y(linInds(1)-1);
catch
yIn1 = nan;
end
try
yIn2 = y(linInds(end)+1);
catch
yIn2 = nan;
end
if isnan(xIn1)
xIn1 = xIn2;
end
if isnan(xIn2)
xIn2 = xIn1;
end
if isnan(yIn1)
yIn1 = yIn2;
end
if isnan(yIn2)
yIn2 = yIn1;
end
%% Interpolate
linX(linInds) = linterp([linInds(1)-1 linInds(end)+1],[xIn1 xIn2],linInds);
linY(linInds) = linterp([linInds(1)-1 linInds(end)+1],[yIn1 yIn2],linInds);
% Remove the interpolated blink
isB(linInds) = false;
end
end
|
github
|
gkaguirrelab/WheresWaldo_EyeTracking-master
|
help_fit_match.m
|
.m
|
WheresWaldo_EyeTracking-master/for_videos/Functions/help_fit_match.m
| 1,085 |
utf_8
|
c6bde26f487492b8e93ecb3be73dfbe6
|
function [distance path transform matched] = help_fit_match(oldX,oldY,pupil_X,pupil_Y,frameInds,isBlink,shift)
shift = round(shift);
badInds = find(frameInds==1,1,'first')-1;
frameInds = frameInds+shift;
oldX(isBlink) = nan;
oldY(isBlink) = nan;
oldX(1:badInds) = nan;
oldY(1:badInds) = nan;
matched = [[oldX(frameInds<length(pupil_X)&frameInds>0),oldY(frameInds<length(pupil_X)&frameInds>0)],...
[pupil_X(frameInds((frameInds<length(pupil_X)&frameInds>0))),...
pupil_Y(frameInds((frameInds<length(pupil_X)&frameInds>0)))]];
matched(any(isnan(matched),2),:) = [];
[distance path transform] = procrustes(matched(:,[1 2]), matched(:,[3 4]),'reflection',false);
% [distance path transform] = help_crust(matched(:,[1 2]), matched(:,[3 4]));%,'reflection',false);
end
function [d p t] = help_crust(a,b)
[t] = fminsearch(@(v)help_dist(a,b,v),[1 1 0 0]);
[d p] = help_dist(a,b,t);
end
function [d b] = help_dist(a,b,v)
b = [b(:,1).*v(1)+v(3) b(:,2).*v(2)+v(4)];
d = mean(sqrt(sum((a-b).^2,2)),1);
end
|
github
|
zhouli2025/some-gadgets-scripts-master
|
detectMSERFeatures_zx.m
|
.m
|
some-gadgets-scripts-master/matlab_tools/mser/detectMSERFeatures_zx.m
| 11,886 |
utf_8
|
6f3850f8d1f0fd28e22c677002bc4bdc
|
function Regions=detectMSERFeatures_zx(I, varargin)
%detectMSERFeatures Finds MSER features.
% regions = detectMSERFeatures(I) returns an MSERRegions object, regions,
% containing region pixel lists and other information about MSER features
% detected in a 2-D grayscale image I. detectMSERFeatures uses Maximally
% Stable Extremal Regions (MSER) algorithm to find regions.
%
% regions = detectMSERFeatures(I,Name,Value) specifies additional
% name-value pair arguments described below:
%
% 'ThresholdDelta' Scalar value, 0 < ThresholdDelta <= 100, expressed
% as a percentage of the input data type range. This
% value specifies the step size between intensity
% threshold levels used in selecting extremal regions
% while testing for their stability. Decrease this
% value to return more regions. Typical values range
% from 0.8 to 4.
%
% Default: 2
%
% 'RegionAreaRange' Two-element vector, [minArea maxArea], which
% specifies the size of the regions in pixels. This
% value allows the selection of regions containing
% pixels between minArea and maxArea, inclusive.
%
% Default: [30 14000]
%
% 'MaxAreaVariation' Positive scalar. Increase this value to return a
% greater number of regions at the cost of their
% stability. Stable regions are very similar in
% size over varying intensity thresholds. Typical
% values range from 0.1 to 1.0.
%
% Default: 0.25
%
% 'ROI' A vector of the format [X Y WIDTH HEIGHT],
% specifying a rectangular region in which corners
% will be detected. [X Y] is the upper left corner of
% the region.
%
% Default: [1 1 size(I,2) size(I,1)]
%
% Class Support
% -------------
% The input image I can be uint8, int16, uint16, single or double,
% and it must be real and nonsparse.
%
% Example
% -------
% % Find MSER regions
% I = imread('cameraman.tif');
% regions = detectMSERFeatures(I);
%
% % Visualize MSER regions which are described by pixel lists stored
% % inside the returned 'regions' object
% figure; imshow(I); hold on;
% plot(regions, 'showPixelList', true, 'showEllipses', false);
%
% % Display ellipses and centroids fit into the regions
% figure; imshow(I); hold on;
% plot(regions); % by default, plot displays ellipses and centroids
%
% See also MSERRegions, extractFeatures, matchFeatures,
% detectBRISKFeatures, detectFASTFeatures, detectHarrisFeatures,
% detectMinEigenFeatures, detectSURFFeatures, SURFPoints
% Copyright 2011 The MathWorks, Inc.
% References:
% Jiri Matas, Ondrej Chum, Martin Urban, Tomas Pajdla. "Robust
% wide-baseline stereo from maximally stable extremal regions",
% Proc. of British Machine Vision Conference, pages 384-396, 2002.
%
% David Nister and Henrik Stewenius, "Linear Time Maximally Stable
% Extremal Regions", European Conference on Computer Vision,
% pages 183-196, 2008.
%#codegen
%#ok<*EMCA>
[Iu8, params] = parseInputs(I,varargin{:});
if isSimMode()
% regionsCell is pixelLists in a cell array {a x 2; b x 2; c x 2; ...} and
% can only be handled in simulation mode since cell arrays are not supported
% in code genereration
regionsCell = ocvExtractMSER(Iu8, params);
if params.usingROI && ~isempty(params.ROI)
regionsCell = offsetPixelList(regionsCell, params.ROI);
end
Regions = MSERRegions(regionsCell);
else
[pixelList, lengths] = ...
vision.internal.buildable.detectMserBuildable.detectMser_uint8(Iu8, params);
if params.usingROI && ~isempty(params.ROI) % offset location values
pixelList = offsetPixelListCodegen(pixelList, params.ROI);
end
Regions = MSERRegions(pixelList, lengths);
end
%==========================================================================
% Parse and check inputs
%==========================================================================
function [img, params] = parseInputs(I, varargin)
validateattributes(I,{'logical', 'uint8', 'int16', 'uint16', ...
'single', 'double'}, {'2d', 'nonempty', 'nonsparse', 'real'},...
mfilename, 'I', 1); % Logical input is not supported
Iu8 = im2uint8(I);
imageSize = size(I);
if isSimMode()
params = parseInputs_sim(imageSize, varargin{:});
else
params = parseInputs_cg(imageSize, varargin{:});
end
%--------------------------------------------------------------------------
% Other OpenCV parameters which are not exposed in the main interface
%--------------------------------------------------------------------------
params.minDiversity = single(0.2);
params.maxEvolution = int32(200);
params.areaThreshold = 1;
params.minMargin = 0.003;
params.edgeBlurSize = int32(5);
img = vision.internal.detector.cropImageIfRequested(Iu8, params.ROI, params.usingROI);
%==========================================================================
function params = parseInputs_sim(imageSize, varargin)
% Parse the PV pairs
parser = inputParser;
defaults = getDefaultParameters(imageSize);
% parser.addParameter('ThresholdDelta', 2);
% parser.addParameter('RegionAreaRange', defaults.RegionAreaRange);
% parser.addParameter('MaxAreaVariation', defaults.MaxAreaVariation);
% parser.addParameter('ROI', defaults.ROI)
parser.addParameter('ThresholdDelta', 5);
parser.addParameter('RegionAreaRange', [30 20000]);
parser.addParameter('MaxAreaVariation', 0.1);
parser.addParameter('ROI', defaults.ROI)
% display(parser);
% Parse input
parser.parse(varargin{:});
checkThresholdDelta(parser.Results.ThresholdDelta);
params.usingROI = ~ismember('ROI', parser.UsingDefaults);
roi = parser.Results.ROI;
if params.usingROI
vision.internal.detector.checkROI(roi, imageSize);
end
isAreaRangeUserSpecified = ~ismember('RegionAreaRange', parser.UsingDefaults);
if isAreaRangeUserSpecified
checkRegionAreaRange(parser.Results.RegionAreaRange, imageSize, ...
params.usingROI, roi);
end
checkMaxAreaVariation(parser.Results.MaxAreaVariation);
% Populate the parameters to pass into OpenCV's ocvExtractMSER()
params.delta = parser.Results.ThresholdDelta*255/100;
params.minArea = parser.Results.RegionAreaRange(1);
params.maxArea = parser.Results.RegionAreaRange(2);
params.maxVariation = parser.Results.MaxAreaVariation;
params.ROI = parser.Results.ROI;
%==========================================================================
function params = parseInputs_cg(imageSize, varargin)
% Optional Name-Value pair: 3 pairs (see help section)
defaults = getDefaultParameters(imageSize);
defaultsNoVal = getDefaultParametersNoVal();
properties = getEmlParserProperties();
optarg = eml_parse_parameter_inputs(defaultsNoVal, properties, varargin{:});
parser_Results.ThresholdDelta = (eml_get_parameter_value( ...
optarg.ThresholdDelta, defaults.ThresholdDelta, varargin{:}));
parser_Results.RegionAreaRange = (eml_get_parameter_value( ...
optarg.RegionAreaRange, defaults.RegionAreaRange, varargin{:}));
parser_Results.MaxAreaVariation = (eml_get_parameter_value( ...
optarg.MaxAreaVariation, defaults.MaxAreaVariation, varargin{:}));
parser_ROI = eml_get_parameter_value(optarg.ROI, defaults.ROI, varargin{:});
checkThresholdDelta(parser_Results.ThresholdDelta);
% check whether ROI parameter is specified
usingROI = optarg.ROI ~= uint32(0);
if usingROI
vision.internal.detector.checkROI(parser_ROI, imageSize);
end
% check whether area range parameter is specified
isAreaRangeUserSpecified = optarg.RegionAreaRange ~= uint32(0);
if isAreaRangeUserSpecified
checkRegionAreaRange(parser_Results.RegionAreaRange, imageSize,...
usingROI, parser_ROI);
end
checkMaxAreaVariation(parser_Results.MaxAreaVariation);
params.delta = cCast('int32_T', parser_Results.ThresholdDelta*255/100);
params.minArea = cCast('int32_T', parser_Results.RegionAreaRange(1));
params.maxArea = cCast('int32_T', parser_Results.RegionAreaRange(2));
params.maxVariation = cCast('real32_T', parser_Results.MaxAreaVariation);
params.ROI = parser_ROI;
params.usingROI = usingROI;
%==========================================================================
% Offset pixel list locations based on ROI
%==========================================================================
function pixListOut = offsetPixelList(pixListIn, roi)
n = size(pixListIn,1);
pixListOut = cell(n,1);
for i = 1:n
pixListOut{i} = vision.internal.detector.addOffsetForROI(pixListIn{i}, roi, true);
end
%==========================================================================
% Offset pixel list locations based on ROI
%==========================================================================
function pixListOut = offsetPixelListCodegen(pixListIn, roi)
pixListOut = vision.internal.detector.addOffsetForROI(pixListIn, roi, true);
%==========================================================================
function defaults = getDefaultParameters(imgSize)
defaults = struct(...
'ThresholdDelta', 5*100/255, ...
'RegionAreaRange', [30 14000], ...
'MaxAreaVariation', 0.25,...
'ROI', [1 1 imgSize(2) imgSize(1)]);
%==========================================================================
function defaultsNoVal = getDefaultParametersNoVal()
defaultsNoVal = struct(...
'ThresholdDelta', uint32(0), ...
'RegionAreaRange', uint32(0), ...
'MaxAreaVariation', uint32(0), ...
'ROI', uint32(0));
%==========================================================================
function properties = getEmlParserProperties()
properties = struct( ...
'CaseSensitivity', false, ...
'StructExpand', true, ...
'PartialMatching', false);
%==========================================================================
function tf = checkThresholdDelta(thresholdDelta)
validateattributes(thresholdDelta, {'numeric'}, {'scalar',...
'nonsparse', 'real', 'positive', '<=', 100}, mfilename);
tf = true;
%==========================================================================
function checkRegionAreaRange(regionAreaRange, imageSize, usingROI, roi)
if usingROI
% When an ROI is specified, the region area range validation should
% be done with respect to the ROI size.
sz = int32([roi(4) roi(3)]);
else
sz = int32(imageSize);
end
imgArea = sz(1)*sz(2);
validateattributes(regionAreaRange, {'numeric'}, {'integer',...
'nonsparse', 'real', 'positive', 'size', [1,2]}, mfilename);
coder.internal.errorIf(regionAreaRange(2) < regionAreaRange(1), ...
'vision:detectMSERFeatures:invalidRegionSizeRange');
% When the imageSize is less than area range, throw a warning.
if imgArea < int32(regionAreaRange(1))
coder.internal.warning('vision:detectMSERFeatures:imageAreaLessThanAreaRange')
end
%==========================================================================
function tf = checkMaxAreaVariation(maxAreaVariation)
validateattributes(maxAreaVariation, {'numeric'}, {'nonsparse', ...
'real', 'scalar', '>=', 0}, mfilename);
tf = true;
%==========================================================================
function flag = isSimMode()
flag = isempty(coder.target);
%==========================================================================
function outVal = cCast(outClass, inVal)
outVal = coder.nullcopy(zeros(1,1,outClass));
outVal = coder.ceval(['(' outClass ')'], inVal);
|
github
|
clatfd/ThresSeg3d-master
|
sliderimg.m
|
.m
|
ThresSeg3d-master/sliderimg.m
| 3,314 |
utf_8
|
46e46c45854a6912b4e961e205cdc6da
|
function varargout=sliderimg(img)
S.SystemFrameHandle=figure;
clf reset
set(gcf,'name','img','numbertitle','off',...
'unit','normalized','position',[0.2,0.1,0.5,0.5]);
% menu_file=uimenu(gcf,'Label','File(&F)');
% menu_open_image=uimenu(menu_file,'Label','Open Images(&O)');
S.OriImageShowHandle=axes('Units','normalized',...
'position',[0.2 0.5 .3 .4],'Color',[0.2 0.2 0.2],'Visible','off','Parent',S.SystemFrameHandle);
S.NewImageShowHandle=axes('Units','normalized',...
'position',[0.6 0.5 .3 .4],'Color',[0.2 0.2 0.2],'Visible','off','Parent',S.SystemFrameHandle);
imshow(img(:,:,1),'Parent',S.OriImageShowHandle);
thresimg=im2bw(img(:,:,1),0.5);
imshow(thresimg,'Parent',S.NewImageShowHandle);
% slider_h = uicontrol(S.SystemFrameHandle,'Style','slider',...
% 'Tag','Slider_h', ...
% 'Position', [100 100 20 200], ...
% 'Max',1,'Min',0,'Value',0.5,...
% 'SliderStep',[0.05 0.2],...
% 'Callback',{@callback_slider_h,S});
S.h = uicontrol('style','slide',...
'unit','pixel',...
'position',[100 200 20 200],...
'SliderStep',[0.05 0.2],...
'value',0.5,...
'min',0,'max',1);
S.sliceslide = uicontrol('style','slide',...
'unit','pixel',...
'position',[150 100 400 20],...
'value',1,...
'SliderStep',[1 5],...
'min',1,'max',size(img,3));
set(S.h,'callback',{@callback_slider_h,S});
set(S.sliceslide,'callback',{@callback_slider_sliceid,S});
setappdata(gcf, 'imgsrc', img);
setappdata(gcf, 'thres_value', 0.5);
setappdata(gcf, 'sliceId', 1);
setappdata(gcf, 'clicktime', 0);
set(gcf,'WindowButtonDownFcn',@ButttonDownFcn);
end
function callback_slider_h(hObject,eventdata,handles)
slide_value=get(hObject,'Value');
assignin('base','thres',slide_value);
setappdata(gcf, 'thres_value', slide_value);
img=getappdata(gcf,'imgsrc');
sliceId=getappdata(gcf,'sliceId');
thresimg=im2bw(img(:,:,sliceId),slide_value);
axes(handles.NewImageShowHandle);
imshow(thresimg);
% disp(slide_value);
end
function callback_slider_sliceid(hObject,eventdata,handles)
sliceId=round(get(hObject,'Value'));
setappdata(gcf, 'sliceId', sliceId);
img=getappdata(gcf,'imgsrc');
axes(handles.OriImageShowHandle);
imshow(img(:,:,sliceId));
axes(handles.NewImageShowHandle);
slide_value=getappdata(gcf,'thres_value');
thresimg=im2bw(img(:,:,sliceId),slide_value);
imshow(thresimg);
% disp(sliceId);
end
function ButttonDownFcn(src,event)
pt = get(gca,'CurrentPoint');
ptx = round(pt(1,1));
pty = round(pt(1,2));
if ptx>=0 && pty>=0
hold on;plot(ptx,pty,'b+');
clicktime=getappdata(gcf,'clicktime');
if clicktime==0
setappdata(gcf, 'clicktime', 1);
cmd=sprintf('crop(1)=%d;',ptx);
evalin('base',cmd);
cmd=sprintf('crop(2)=%d;',pty);
evalin('base',cmd);
setappdata(gcf, 'crop', [ptx pty]);
else
cmd=sprintf('crop(3)=%d;',ptx);
evalin('base',cmd);
cmd=sprintf('crop(4)=%d;',pty);
evalin('base',cmd);
crop=getappdata(gcf,'crop');
line([crop(1) ptx],[crop(2) crop(2)]);
line([crop(1) ptx],[pty pty]);
line([crop(1) crop(1)],[crop(2) pty]);
line([ptx ptx],[crop(2) pty]);
end
end
end
|
github
|
mitschabaude/nanopores-master
|
CloneFig.m
|
.m
|
nanopores-master/scripts/finfet/collocation_methods/CloneFig.m
| 667 |
utf_8
|
cca00ad847ab499d1396a59a594a07df
|
function CloneFig(inFigNum,OutFigNum)
% this program copies a figure to another figure
% example: CloneFig(1,4) would copy Fig. 1 to Fig. 4
% Matt Fetterman, 2009
% pretty much taken from Matlab Technical solutions:
% http://www.mathworks.com/support/solutions/en/data/1-1UTBOL/?solution=1-1UTBOL
hf1=figure(inFigNum);
hf2=figure(OutFigNum);
clf;
compCopy(hf1,hf2);
function compCopy(op, np)
%COMPCOPY copies a figure object represented by "op" and its % descendants to another figure "np" preserving the same hierarchy.
ch = get(op, 'children');
if ~isempty(ch)
nh = copyobj(ch,np);
for k = 1:length(ch)
compCopy(ch(k),nh(k));
end
end;
return;
|
github
|
matheusmlopess-zz/Fuzzy-Logic-power-transmission-analysis-master
|
ktropf_solver.m
|
.m
|
Fuzzy-Logic-power-transmission-analysis-master/matpower5.1/ktropf_solver.m
| 11,710 |
utf_8
|
5cd97b9ba5b0916c199be22be6a70a8f
|
function [results, success, raw] = ktropf_solver(om, mpopt)
%KTROPF_SOLVER Solves AC optimal power flow using KNITRO.
%
% [RESULTS, SUCCESS, RAW] = KTROPF_SOLVER(OM, MPOPT)
%
% Inputs are an OPF model object and a MATPOWER options struct.
%
% Outputs are a RESULTS struct, SUCCESS flag and RAW output struct.
%
% RESULTS is a MATPOWER case struct (mpc) with the usual baseMVA, bus
% branch, gen, gencost fields, along with the following additional
% fields:
% .order see 'help ext2int' for details of this field
% .x final value of optimization variables (internal order)
% .f final objective function value
% .mu shadow prices on ...
% .var
% .l lower bounds on variables
% .u upper bounds on variables
% .nln
% .l lower bounds on nonlinear constraints
% .u upper bounds on nonlinear constraints
% .lin
% .l lower bounds on linear constraints
% .u upper bounds on linear constraints
%
% SUCCESS 1 if solver converged successfully, 0 otherwise
%
% RAW raw output in form returned by MINOS
% .xr final value of optimization variables
% .pimul constraint multipliers
% .info solver specific termination code
% .output solver specific output information
%
% See also OPF, KTRLINK.
% MATPOWER
% Copyright (c) 2000-2015 by Power System Engineering Research Center (PSERC)
% by Ray Zimmerman, PSERC Cornell
% and Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Autonoma de Manizales
%
% $Id: ktropf_solver.m 2644 2015-03-11 19:34:22Z ray $
%
% This file is part of MATPOWER.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See http://www.pserc.cornell.edu/matpower/ for more info.
%%----- initialization -----
%% define named indices into data matrices
[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;
[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;
%% options
use_ktropts_file = 1; %% use a KNITRO options file to pass options
create_ktropts_file = 0; %% generate a KNITRO options file on the fly
%% unpack data
mpc = get_mpc(om);
[baseMVA, bus, gen, branch, gencost] = ...
deal(mpc.baseMVA, mpc.bus, mpc.gen, mpc.branch, mpc.gencost);
[vv, ll, nn] = get_idx(om);
%% problem dimensions
nb = size(bus, 1); %% number of buses
ng = size(gen, 1); %% number of gens
nl = size(branch, 1); %% number of branches
ny = getN(om, 'var', 'y'); %% number of piece-wise linear costs
%% bounds on optimization vars
[x0, xmin, xmax] = getv(om);
%% linear constraints
[A, l, u] = linear_constraints(om);
%% split l <= A*x <= u into less than, equal to, greater than, and
%% doubly-bounded sets
ieq = find( abs(u-l) <= eps ); %% equality
igt = find( u >= 1e10 & l > -1e10 ); %% greater than, unbounded above
ilt = find( l <= -1e10 & u < 1e10 ); %% less than, unbounded below
ibx = find( (abs(u-l) > eps) & (u < 1e10) & (l > -1e10) );
Af = [ A(ilt, :); -A(igt, :); A(ibx, :); -A(ibx, :) ];
bf = [ u(ilt); -l(igt); u(ibx); -l(ibx)];
Afeq = A(ieq, :);
bfeq = u(ieq);
%% build admittance matrices
[Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch);
%% try to select an interior initial point
if mpopt.opf.init_from_mpc ~= 1
ll = xmin; uu = xmax;
ll(xmin == -Inf) = -1e10; %% replace Inf with numerical proxies
uu(xmax == Inf) = 1e10;
x0 = (ll + uu) / 2; %% set x0 mid-way between bounds
k = find(xmin == -Inf & xmax < Inf); %% if only bounded above
x0(k) = xmax(k) - 1; %% set just below upper bound
k = find(xmin > -Inf & xmax == Inf); %% if only bounded below
x0(k) = xmin(k) + 1; %% set just above lower bound
Varefs = bus(bus(:, BUS_TYPE) == REF, VA) * (pi/180);
x0(vv.i1.Va:vv.iN.Va) = Varefs(1); %% angles set to first reference angle
if ny > 0
ipwl = find(gencost(:, MODEL) == PW_LINEAR);
% PQ = [gen(:, PMAX); gen(:, QMAX)];
% c = totcost(gencost(ipwl, :), PQ(ipwl));
c = gencost(sub2ind(size(gencost), ipwl, NCOST+2*gencost(ipwl, NCOST))); %% largest y-value in CCV data
x0(vv.i1.y:vv.iN.y) = max(c) + 0.1 * abs(max(c));
% x0(vv.i1.y:vv.iN.y) = c + 0.1 * abs(c);
end
end
%% find branches with flow limits
il = find(branch(:, RATE_A) ~= 0 & branch(:, RATE_A) < 1e10);
nl2 = length(il); %% number of constrained lines
%% build Jacobian and Hessian structure
nA = size(A, 1); %% number of original linear constraints
nx = length(x0);
f = branch(:, F_BUS); %% list of "from" buses
t = branch(:, T_BUS); %% list of "to" buses
Cf = sparse(1:nl, f, ones(nl, 1), nl, nb); %% connection matrix for line & from buses
Ct = sparse(1:nl, t, ones(nl, 1), nl, nb); %% connection matrix for line & to buses
Cl = Cf + Ct;
Cb = Cl' * Cl + speye(nb);
Cl2 = Cl(il, :);
Cg = sparse(gen(:, GEN_BUS), (1:ng)', 1, nb, ng);
nz = nx - 2*(nb+ng);
nxtra = nx - 2*nb;
Js = [
Cl2 Cl2 sparse(nl2, 2*ng) sparse(nl2,nz);
Cl2 Cl2 sparse(nl2, 2*ng) sparse(nl2,nz);
Cb Cb Cg sparse(nb,ng) sparse(nb,nz);
Cb Cb sparse(nb,ng) Cg sparse(nb,nz);
];
[f, df, d2f] = opf_costfcn(x0, om);
Hs = d2f + [
Cb Cb sparse(nb,nxtra);
Cb Cb sparse(nb,nxtra);
sparse(nxtra,nx);
];
%% basic optimset options needed for ktrlink
hess_fcn = @(x, lambda)opf_hessfcn(x, lambda, 1, om, Ybus, Yf(il,:), Yt(il,:), mpopt, il);
fmoptions = optimset('GradObj', 'on', 'GradConstr', 'on', ...
'Hessian', 'user-supplied', 'HessFcn', hess_fcn, ...
'JacobPattern', Js, 'HessPattern', Hs );
if use_ktropts_file
if ~isempty(mpopt.knitro.opt_fname)
opt_fname = mpopt.knitro.opt_fname;
elseif mpopt.knitro.opt
opt_fname = sprintf('knitro_user_options_%d.txt', mpopt.knitro.opt);
else
%% create ktropts file
ktropts.algorithm = 1;
ktropts.outlev = mpopt.verbose;
ktropts.feastol = mpopt.opf.violation;
ktropts.xtol = mpopt.knitro.tol_x;
ktropts.opttol = mpopt.knitro.tol_f;
if mpopt.fmincon.max_it ~= 0
ktropts.maxit = mpopt.fmincon.max_it;
end
ktropts.bar_directinterval = 0;
opt_fname = write_ktropts(ktropts);
create_ktropts_file = 1; %% make a note that I created it
end
else
fmoptions = optimset(fmoptions, 'Algorithm', 'interior-point', ...
'TolCon', mpopt.opf.violation, 'TolX', mpopt.knitro.tol_x, ...
'TolFun', mpopt.knitro.tol_f );
if mpopt.fmincon.max_it ~= 0
fmoptions = optimset(fmoptions, 'MaxIter', mpopt.fmincon.max_it, ...
'MaxFunEvals', 4 * mpopt.fmincon.max_it);
end
if mpopt.verbose == 0,
fmoptions.Display = 'off';
elseif mpopt.verbose == 1
fmoptions.Display = 'iter';
else
fmoptions.Display = 'testing';
end
opt_fname = [];
end
%%----- run opf -----
f_fcn = @(x)opf_costfcn(x, om);
gh_fcn = @(x)opf_consfcn(x, om, Ybus, Yf(il,:), Yt(il,:), mpopt, il);
if have_fcn('knitromatlab')
[x, f, info, Output, Lambda] = knitromatlab(f_fcn, x0, Af, bf, Afeq, bfeq, ...
xmin, xmax, gh_fcn, [], fmoptions, opt_fname);
else
[x, f, info, Output, Lambda] = ktrlink(f_fcn, x0, Af, bf, Afeq, bfeq, ...
xmin, xmax, gh_fcn, fmoptions, opt_fname);
end
success = (info == 0);
%% delete ktropts file
if create_ktropts_file %% ... but only if I created it
delete(opt_fname);
end
%% update solution data
Va = x(vv.i1.Va:vv.iN.Va);
Vm = x(vv.i1.Vm:vv.iN.Vm);
Pg = x(vv.i1.Pg:vv.iN.Pg);
Qg = x(vv.i1.Qg:vv.iN.Qg);
V = Vm .* exp(1j*Va);
%%----- calculate return values -----
%% update voltages & generator outputs
bus(:, VA) = Va * 180/pi;
bus(:, VM) = Vm;
gen(:, PG) = Pg * baseMVA;
gen(:, QG) = Qg * baseMVA;
gen(:, VG) = Vm(gen(:, GEN_BUS));
%% compute branch flows
Sf = V(branch(:, F_BUS)) .* conj(Yf * V); %% cplx pwr at "from" bus, p.u.
St = V(branch(:, T_BUS)) .* conj(Yt * V); %% cplx pwr at "to" bus, p.u.
branch(:, PF) = real(Sf) * baseMVA;
branch(:, QF) = imag(Sf) * baseMVA;
branch(:, PT) = real(St) * baseMVA;
branch(:, QT) = imag(St) * baseMVA;
%% line constraint is actually on square of limit
%% so we must fix multipliers
muSf = zeros(nl, 1);
muSt = zeros(nl, 1);
if ~isempty(il)
muSf(il) = 2 * Lambda.ineqnonlin(1:nl2) .* branch(il, RATE_A) / baseMVA;
muSt(il) = 2 * Lambda.ineqnonlin((1:nl2)+nl2) .* branch(il, RATE_A) / baseMVA;
end
%% update Lagrange multipliers
bus(:, MU_VMAX) = Lambda.upper(vv.i1.Vm:vv.iN.Vm);
bus(:, MU_VMIN) = -Lambda.lower(vv.i1.Vm:vv.iN.Vm);
gen(:, MU_PMAX) = Lambda.upper(vv.i1.Pg:vv.iN.Pg) / baseMVA;
gen(:, MU_PMIN) = -Lambda.lower(vv.i1.Pg:vv.iN.Pg) / baseMVA;
gen(:, MU_QMAX) = Lambda.upper(vv.i1.Qg:vv.iN.Qg) / baseMVA;
gen(:, MU_QMIN) = -Lambda.lower(vv.i1.Qg:vv.iN.Qg) / baseMVA;
bus(:, LAM_P) = Lambda.eqnonlin(nn.i1.Pmis:nn.iN.Pmis) / baseMVA;
bus(:, LAM_Q) = Lambda.eqnonlin(nn.i1.Qmis:nn.iN.Qmis) / baseMVA;
branch(:, MU_SF) = muSf / baseMVA;
branch(:, MU_ST) = muSt / baseMVA;
%% package up results
nlnN = getN(om, 'nln');
nlt = length(ilt);
ngt = length(igt);
nbx = length(ibx);
%% extract multipliers for nonlinear constraints
kl = find(Lambda.eqnonlin < 0);
ku = find(Lambda.eqnonlin > 0);
nl_mu_l = zeros(nlnN, 1);
nl_mu_u = [zeros(2*nb, 1); muSf; muSt];
nl_mu_l(kl) = -Lambda.eqnonlin(kl);
nl_mu_u(ku) = Lambda.eqnonlin(ku);
%% extract multipliers for linear constraints
kl = find(Lambda.eqlin < 0);
ku = find(Lambda.eqlin > 0);
mu_l = zeros(size(u));
mu_l(ieq(kl)) = -Lambda.eqlin(kl);
mu_l(igt) = Lambda.ineqlin(nlt+(1:ngt));
mu_l(ibx) = Lambda.ineqlin(nlt+ngt+nbx+(1:nbx));
mu_u = zeros(size(u));
mu_u(ieq(ku)) = Lambda.eqlin(ku);
mu_u(ilt) = Lambda.ineqlin(1:nlt);
mu_u(ibx) = Lambda.ineqlin(nlt+ngt+(1:nbx));
mu = struct( ...
'var', struct('l', -Lambda.lower, 'u', Lambda.upper), ...
'nln', struct('l', nl_mu_l, 'u', nl_mu_u), ...
'lin', struct('l', mu_l, 'u', mu_u) );
results = mpc;
[results.bus, results.branch, results.gen, ...
results.om, results.x, results.mu, results.f] = ...
deal(bus, branch, gen, om, x, mu, f);
pimul = [ ...
results.mu.nln.l - results.mu.nln.u;
results.mu.lin.l - results.mu.lin.u;
-ones(ny>0, 1);
results.mu.var.l - results.mu.var.u;
];
raw = struct('xr', x, 'pimul', pimul, 'info', info, 'output', Output);
%%----- write_ktropts -----
function fname = write_ktropts(ktropts)
%% generate file name
fname = sprintf('ktropts_%06d.txt', fix(1e6*rand));
%% open file
[fd, msg] = fopen(fname, 'wt'); %% write options file
if fd == -1
error('could not create %d : %s', fname, msg);
end
%% write options
fields = fieldnames(ktropts);
for k = 1:length(fields)
fprintf(fd, '%s %g\n', fields{k}, ktropts.(fields{k}));
end
%% close file
if fd ~= 1
fclose(fd);
end
|
github
|
matheusmlopess-zz/Fuzzy-Logic-power-transmission-analysis-master
|
modcost.m
|
.m
|
Fuzzy-Logic-power-transmission-analysis-master/matpower5.1/modcost.m
| 4,148 |
utf_8
|
7ad37d349aef8613d44ca72096179496
|
function gencost = modcost(gencost, alpha, modtype)
%MODCOST Modifies generator costs by shifting or scaling (F or X).
% NEWGENCOST = MODCOST(GENCOST, ALPHA)
% NEWGENCOST = MODCOST(GENCOST, ALPHA, MODTYPE)
%
% For each generator cost F(X) (for real or reactive power) in
% GENCOST, this function modifies the cost by scaling or shifting
% the function by ALPHA, depending on the value of MODTYPE, and
% and returns the modified GENCOST. Rows of GENCOST can be a mix
% of polynomial or piecewise linear costs. ALPHA can be a scalar,
% applied to each row of GENCOST, or an NG x 1 vector, where each
% element is applied to the corresponding row of GENCOST.
%
% MODTYPE takes one of the 4 possible values (let F_alpha(X) denote the
% the modified function):
% 'SCALE_F' (default) : F_alpha(X) == F(X) * ALPHA
% 'SCALE_X' : F_alpha(X * ALPHA) == F(X)
% 'SHIFT_F' : F_alpha(X) == F(X) + ALPHA
% 'SHIFT_X' : F_alpha(X + ALPHA) == F(X)
% MATPOWER
% Copyright (c) 2010-2015 by Power System Engineering Research Center (PSERC)
% by Ray Zimmerman, PSERC Cornell
%
% $Id: modcost.m 2644 2015-03-11 19:34:22Z ray $
%
% This file is part of MATPOWER.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See http://www.pserc.cornell.edu/matpower/ for more info.
%% define named indices into data matrices
[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;
if nargin < 3
modtype = 'SCALE_F';
end
[ng, m] = size(gencost);
if ng ~= 0
if length(alpha) ~= ng
if length(alpha) == 1 && ng > 1 %% scalar, make it a col vector
alpha = alpha * ones(ng, 1);
else
error('modcost: ALPHA must be a scalar or col vector with NG rows');
end
elseif size(alpha, 2) ~= 1
alpha = alpha'; %% convert row vector to col vector
end
ipwl = find(gencost(:, MODEL) == PW_LINEAR);
ipol = find(gencost(:, MODEL) == POLYNOMIAL);
c = gencost(ipol, COST:m);
switch modtype
case 'SCALE_F',
gencost(ipol, COST:m) = diag(alpha(ipol)) * c;
gencost(ipwl, COST+1:2:m) = diag(alpha(ipwl)) * gencost(ipwl, COST+1:2:m);
case 'SCALE_X',
for k = 1:length(ipol)
n = gencost(ipol(k), NCOST);
for i = 1:n
gencost(ipol(k), COST+i-1) = c(k, i) / alpha(ipol(k))^(n-i);
end
end
gencost(ipwl, COST:2:m-1) = diag(alpha(ipwl)) * gencost(ipwl, COST:2:m-1);
case 'SHIFT_F',
for k = 1:length(ipol)
n = gencost(ipol(k), NCOST);
gencost(ipol(k), COST+n-1) = alpha(ipol(k)) + c(k, n);
end
gencost(ipwl, COST+1:2:m) = ...
diag(alpha(ipwl)) * ones(length(ipwl), (m+1-COST)/2) + ...
gencost(ipwl, COST+1:2:m);
case 'SHIFT_X',
for k = 1:length(ipol)
n = gencost(ipol(k), NCOST);
gencost(ipol(k), COST:COST+n-1) = polyshift(c(k, 1:n)', alpha(ipol(k)))';
end
gencost(ipwl, COST:2:m-1) = ...
diag(alpha(ipwl)) * ones(length(ipwl), (m+1-COST)/2) + ...
gencost(ipwl, COST:2:m-1);
otherwise
error('modcost: ''%s'' is not a valid modtype\n', modtype);
end
end
%%----- POLYSHIFT -----
function d = polyshift(c, a)
%POLYSHIFT Returns the coefficients of a horizontally shifted polynomial.
%
% D = POLYSHIFT(C, A) shifts to the right by A, the polynomial whose
% coefficients are given in the column vector C.
%
% Example: For any polynomial with n coefficients in c, and any values
% for x and shift a, the f - f0 should be zero.
% x = rand;
% a = rand;
% c = rand(n, 1);
% f0 = polyval(c, x)
% f = polyval(polyshift(c, a), x+a)
n = length(c);
d = zeros(size(c));
A = (-a * ones(n, 1)) .^ ((0:n-1)');
b = ones(n, 1);
for k = 1:n
d(n-k+1) = b' * ( c(n-k+1:-1:1) .* A(1:n-k+1) );
b = cumsum(b(1:n-k));
end
|
github
|
matheusmlopess-zz/Fuzzy-Logic-power-transmission-analysis-master
|
ipoptopf_solver.m
|
.m
|
Fuzzy-Logic-power-transmission-analysis-master/matpower5.1/ipoptopf_solver.m
| 11,041 |
utf_8
|
591f13b41b7cc6d1cc333c404ad42ffd
|
function [results, success, raw] = ipoptopf_solver(om, mpopt)
%IPOPTOPF_SOLVER Solves AC optimal power flow using MIPS.
%
% [RESULTS, SUCCESS, RAW] = IPOPTOPF_SOLVER(OM, MPOPT)
%
% Inputs are an OPF model object and a MATPOWER options struct.
%
% Outputs are a RESULTS struct, SUCCESS flag and RAW output struct.
%
% RESULTS is a MATPOWER case struct (mpc) with the usual baseMVA, bus
% branch, gen, gencost fields, along with the following additional
% fields:
% .order see 'help ext2int' for details of this field
% .x final value of optimization variables (internal order)
% .f final objective function value
% .mu shadow prices on ...
% .var
% .l lower bounds on variables
% .u upper bounds on variables
% .nln
% .l lower bounds on nonlinear constraints
% .u upper bounds on nonlinear constraints
% .lin
% .l lower bounds on linear constraints
% .u upper bounds on linear constraints
%
% SUCCESS 1 if solver converged successfully, 0 otherwise
%
% RAW raw output in form returned by MINOS
% .xr final value of optimization variables
% .pimul constraint multipliers
% .info solver specific termination code
% .output solver specific output information
%
% See also OPF, IPOPT.
% MATPOWER
% Copyright (c) 2000-2015 by Power System Engineering Research Center (PSERC)
% by Ray Zimmerman, PSERC Cornell
% and Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Autonoma de Manizales
%
% $Id: ipoptopf_solver.m 2644 2015-03-11 19:34:22Z ray $
%
% This file is part of MATPOWER.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See http://www.pserc.cornell.edu/matpower/ for more info.
%%----- initialization -----
%% define named indices into data matrices
[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;
[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;
%% unpack data
mpc = get_mpc(om);
[baseMVA, bus, gen, branch, gencost] = ...
deal(mpc.baseMVA, mpc.bus, mpc.gen, mpc.branch, mpc.gencost);
[vv, ll, nn] = get_idx(om);
%% problem dimensions
nb = size(bus, 1); %% number of buses
ng = size(gen, 1); %% number of gens
nl = size(branch, 1); %% number of branches
ny = getN(om, 'var', 'y'); %% number of piece-wise linear costs
%% linear constraints
[A, l, u] = linear_constraints(om);
%% bounds on optimization vars
[x0, xmin, xmax] = getv(om);
%% build admittance matrices
[Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch);
%% try to select an interior initial point
if mpopt.opf.init_from_mpc ~= 1
ll = xmin; uu = xmax;
ll(xmin == -Inf) = -1e10; %% replace Inf with numerical proxies
uu(xmax == Inf) = 1e10;
x0 = (ll + uu) / 2; %% set x0 mid-way between bounds
k = find(xmin == -Inf & xmax < Inf); %% if only bounded above
x0(k) = xmax(k) - 1; %% set just below upper bound
k = find(xmin > -Inf & xmax == Inf); %% if only bounded below
x0(k) = xmin(k) + 1; %% set just above lower bound
Varefs = bus(bus(:, BUS_TYPE) == REF, VA) * (pi/180);
x0(vv.i1.Va:vv.iN.Va) = Varefs(1); %% angles set to first reference angle
if ny > 0
ipwl = find(gencost(:, MODEL) == PW_LINEAR);
% PQ = [gen(:, PMAX); gen(:, QMAX)];
% c = totcost(gencost(ipwl, :), PQ(ipwl));
c = gencost(sub2ind(size(gencost), ipwl, NCOST+2*gencost(ipwl, NCOST))); %% largest y-value in CCV data
x0(vv.i1.y:vv.iN.y) = max(c) + 0.1 * abs(max(c));
% x0(vv.i1.y:vv.iN.y) = c + 0.1 * abs(c);
end
end
%% find branches with flow limits
il = find(branch(:, RATE_A) ~= 0 & branch(:, RATE_A) < 1e10);
nl2 = length(il); %% number of constrained lines
%%----- run opf -----
%% build Jacobian and Hessian structure
nA = size(A, 1); %% number of original linear constraints
nx = length(x0);
f = branch(:, F_BUS); %% list of "from" buses
t = branch(:, T_BUS); %% list of "to" buses
Cf = sparse(1:nl, f, ones(nl, 1), nl, nb); %% connection matrix for line & from buses
Ct = sparse(1:nl, t, ones(nl, 1), nl, nb); %% connection matrix for line & to buses
Cl = Cf + Ct;
Cb = Cl' * Cl + speye(nb);
Cl2 = Cl(il, :);
Cg = sparse(gen(:, GEN_BUS), (1:ng)', 1, nb, ng);
nz = nx - 2*(nb+ng);
nxtra = nx - 2*nb;
Js = [
Cb Cb Cg sparse(nb,ng) sparse(nb,nz);
Cb Cb sparse(nb,ng) Cg sparse(nb,nz);
Cl2 Cl2 sparse(nl2, 2*ng) sparse(nl2,nz);
Cl2 Cl2 sparse(nl2, 2*ng) sparse(nl2,nz);
A;
];
[f, df, d2f] = opf_costfcn(x0, om);
Hs = tril(d2f + [
Cb Cb sparse(nb,nxtra);
Cb Cb sparse(nb,nxtra);
sparse(nxtra,nx);
]);
%% set options struct for IPOPT
options.ipopt = ipopt_options([], mpopt);
%% extra data to pass to functions
options.auxdata = struct( ...
'om', om, ...
'Ybus', Ybus, ...
'Yf', Yf(il,:), ...
'Yt', Yt(il,:), ...
'mpopt', mpopt, ...
'il', il, ...
'A', A, ...
'nA', nA, ...
'neqnln', 2*nb, ...
'niqnln', 2*nl2, ...
'Js', Js, ...
'Hs', Hs );
% %% check Jacobian and Hessian structure
% xr = rand(size(x0));
% lambda = rand(2*nb+2*nl2, 1);
% options.auxdata.Js = jacobian(xr, options.auxdata);
% options.auxdata.Hs = tril(hessian(xr, 1, lambda, options.auxdata));
% Js1 = options.auxdata.Js;
% options.auxdata.Js = Js;
% Hs1 = options.auxdata.Hs;
% [i1, j1, s] = find(Js);
% [i2, j2, s] = find(Js1);
% if length(i1) ~= length(i2) || norm(i1-i2) ~= 0 || norm(j1-j2) ~= 0
% error('something''s wrong with the Jacobian structure');
% end
% [i1, j1, s] = find(Hs);
% [i2, j2, s] = find(Hs1);
% if length(i1) ~= length(i2) || norm(i1-i2) ~= 0 || norm(j1-j2) ~= 0
% error('something''s wrong with the Hessian structure');
% end
%% define variable and constraint bounds
options.lb = xmin;
options.ub = xmax;
options.cl = [zeros(2*nb, 1); -Inf(2*nl2, 1); l];
options.cu = [zeros(2*nb, 1); zeros(2*nl2, 1); u];
%% assign function handles
funcs.objective = @objective;
funcs.gradient = @gradient;
funcs.constraints = @constraints;
funcs.jacobian = @jacobian;
funcs.hessian = @hessian;
funcs.jacobianstructure = @(d) Js;
funcs.hessianstructure = @(d) Hs;
%funcs.jacobianstructure = @jacobianstructure;
%funcs.hessianstructure = @hessianstructure;
%% run the optimization
if have_fcn('ipopt_auxdata')
[x, info] = ipopt_auxdata(x0,funcs,options);
else
[x, info] = ipopt(x0,funcs,options);
end
if info.status == 0 || info.status == 1
success = 1;
else
success = 0;
end
if isfield(info, 'iter')
output.iterations = info.iter;
else
output.iterations = [];
end
f = opf_costfcn(x, om);
%% update solution data
Va = x(vv.i1.Va:vv.iN.Va);
Vm = x(vv.i1.Vm:vv.iN.Vm);
Pg = x(vv.i1.Pg:vv.iN.Pg);
Qg = x(vv.i1.Qg:vv.iN.Qg);
V = Vm .* exp(1j*Va);
%%----- calculate return values -----
%% update voltages & generator outputs
bus(:, VA) = Va * 180/pi;
bus(:, VM) = Vm;
gen(:, PG) = Pg * baseMVA;
gen(:, QG) = Qg * baseMVA;
gen(:, VG) = Vm(gen(:, GEN_BUS));
%% compute branch flows
Sf = V(branch(:, F_BUS)) .* conj(Yf * V); %% cplx pwr at "from" bus, p.u.
St = V(branch(:, T_BUS)) .* conj(Yt * V); %% cplx pwr at "to" bus, p.u.
branch(:, PF) = real(Sf) * baseMVA;
branch(:, QF) = imag(Sf) * baseMVA;
branch(:, PT) = real(St) * baseMVA;
branch(:, QT) = imag(St) * baseMVA;
%% line constraint is actually on square of limit
%% so we must fix multipliers
muSf = zeros(nl, 1);
muSt = zeros(nl, 1);
if ~isempty(il)
muSf(il) = 2 * info.lambda(2*nb+ (1:nl2)) .* branch(il, RATE_A) / baseMVA;
muSt(il) = 2 * info.lambda(2*nb+nl2+(1:nl2)) .* branch(il, RATE_A) / baseMVA;
end
%% update Lagrange multipliers
bus(:, MU_VMAX) = info.zu(vv.i1.Vm:vv.iN.Vm);
bus(:, MU_VMIN) = info.zl(vv.i1.Vm:vv.iN.Vm);
gen(:, MU_PMAX) = info.zu(vv.i1.Pg:vv.iN.Pg) / baseMVA;
gen(:, MU_PMIN) = info.zl(vv.i1.Pg:vv.iN.Pg) / baseMVA;
gen(:, MU_QMAX) = info.zu(vv.i1.Qg:vv.iN.Qg) / baseMVA;
gen(:, MU_QMIN) = info.zl(vv.i1.Qg:vv.iN.Qg) / baseMVA;
bus(:, LAM_P) = info.lambda(nn.i1.Pmis:nn.iN.Pmis) / baseMVA;
bus(:, LAM_Q) = info.lambda(nn.i1.Qmis:nn.iN.Qmis) / baseMVA;
branch(:, MU_SF) = muSf / baseMVA;
branch(:, MU_ST) = muSt / baseMVA;
%% package up results
nlnN = getN(om, 'nln');
%% extract multipliers for nonlinear constraints
kl = find(info.lambda(1:2*nb) < 0);
ku = find(info.lambda(1:2*nb) > 0);
nl_mu_l = zeros(nlnN, 1);
nl_mu_u = [zeros(2*nb, 1); muSf; muSt];
nl_mu_l(kl) = -info.lambda(kl);
nl_mu_u(ku) = info.lambda(ku);
%% extract multipliers for linear constraints
lam_lin = info.lambda(2*nb+2*nl2+(1:nA)); %% lambda for linear constraints
kl = find(lam_lin < 0); %% lower bound binding
ku = find(lam_lin > 0); %% upper bound binding
mu_l = zeros(nA, 1);
mu_l(kl) = -lam_lin(kl);
mu_u = zeros(nA, 1);
mu_u(ku) = lam_lin(ku);
mu = struct( ...
'var', struct('l', info.zl, 'u', info.zu), ...
'nln', struct('l', nl_mu_l, 'u', nl_mu_u), ...
'lin', struct('l', mu_l, 'u', mu_u) );
results = mpc;
[results.bus, results.branch, results.gen, ...
results.om, results.x, results.mu, results.f] = ...
deal(bus, branch, gen, om, x, mu, f);
pimul = [ ...
results.mu.nln.l - results.mu.nln.u;
results.mu.lin.l - results.mu.lin.u;
-ones(ny>0, 1);
results.mu.var.l - results.mu.var.u;
];
raw = struct('xr', x, 'pimul', pimul, 'info', info.status, 'output', output);
%----- callback functions -----
function f = objective(x, d)
f = opf_costfcn(x, d.om);
function df = gradient(x, d)
[f, df] = opf_costfcn(x, d.om);
function c = constraints(x, d)
[hn, gn] = opf_consfcn(x, d.om, d.Ybus, d.Yf, d.Yt, d.mpopt, d.il);
if isempty(d.A)
c = [gn; hn];
else
c = [gn; hn; d.A*x];
end
function J = jacobian(x, d)
[hn, gn, dhn, dgn] = opf_consfcn(x, d.om, d.Ybus, d.Yf, d.Yt, d.mpopt, d.il);
J = [dgn'; dhn'; d.A];
function H = hessian(x, sigma, lambda, d)
lam.eqnonlin = lambda(1:d.neqnln);
lam.ineqnonlin = lambda(d.neqnln+(1:d.niqnln));
H = tril(opf_hessfcn(x, lam, sigma, d.om, d.Ybus, d.Yf, d.Yt, d.mpopt, d.il));
% function Js = jacobianstructure(d)
% Js = d.Js;
%
% function Hs = hessianstructure(d)
% Hs = d.Hs;
|
github
|
matheusmlopess-zz/Fuzzy-Logic-power-transmission-analysis-master
|
loadcase.m
|
.m
|
Fuzzy-Logic-power-transmission-analysis-master/matpower5.1/loadcase.m
| 9,744 |
utf_8
|
3b9f2a0546e217b2be54a408712e93bc
|
function [baseMVA, bus, gen, branch, areas, gencost, info] = loadcase(casefile)
%LOADCASE Load .m or .mat case files or data struct in MATPOWER format.
%
% [BASEMVA, BUS, GEN, BRANCH, AREAS, GENCOST] = LOADCASE(CASEFILE)
% [BASEMVA, BUS, GEN, BRANCH, GENCOST] = LOADCASE(CASEFILE)
% [BASEMVA, BUS, GEN, BRANCH] = LOADCASE(CASEFILE)
% MPC = LOADCASE(CASEFILE)
%
% Returns the individual data matrices or a struct containing them as fields.
%
% Here CASEFILE is either (1) a struct containing the fields baseMVA,
% bus, gen, branch and, optionally, areas and/or gencost, or (2) a string
% containing the name of the file. If CASEFILE contains the extension
% '.mat' or '.m', then the explicit file is searched. If CASEFILE contains
% no extension, then LOADCASE looks for a MAT-file first, then for an
% M-file. If the file does not exist or doesn't define all required
% matrices, the routine aborts with an appropriate error message.
%
% Alternatively, it can be called with the following syntax, though this
% option is now deprecated and will be removed in a future version:
%
% [BASEMVA, BUS, GEN, BRANCH, AREAS, GENCOST, INFO] = LOADCASE(CASEFILE)
% [MPC, INFO] = LOADCASE(CASEFILE)
%
% In this case, the function will not abort, but INFO will contain an exit
% code as follows:
%
% 0: all variables successfully defined
% 1: input argument is not a string or struct
% 2: specified extension-less file name does not exist in search path
% 3: specified MAT-file does not exist in search path
% 4: specified M-file does not exist in search path
% 5: specified file fails to define all matrices or contains syntax err
%
% If the input data is from an M-file or MAT-file defining individual
% data matrices, or from a struct with out a 'version' field whose
% GEN matrix has fewer than 21 columns, then it is assumed to be a
% MATPOWER case file in version 1 format, and will be converted to
% version 2 format.
% MATPOWER
% Copyright (c) 1996-2015 by Power System Engineering Research Center (PSERC)
% by Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Autonoma de Manizales
% and Ray Zimmerman, PSERC Cornell
%
% $Id: loadcase.m 2644 2015-03-11 19:34:22Z ray $
%
% This file is part of MATPOWER.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See http://www.pserc.cornell.edu/matpower/ for more info.
info = 0;
if nargout < 3
return_as_struct = true;
else
return_as_struct = false;
end
if nargout >= 5
expect_gencost = true;
if nargout > 5
expect_areas = true;
else
expect_areas = false;
end
else
expect_gencost = false;
expect_areas = false;
end
%%----- read data into struct -----
if ischar(casefile)
[pathstr, fname, ext] = fileparts(casefile);
if isempty(ext)
if exist(fullfile(pathstr, [fname '.mat']), 'file') == 2
ext = '.mat';
elseif exist(fullfile(pathstr, [fname '.m']), 'file') == 2
ext = '.m';
else
info = 2;
end
end
%% attempt to read file
if info == 0
if strcmp(ext,'.mat') %% from MAT file
try
s = load(fullfile(pathstr, fname));
if isfield(s, 'mpc') %% it's a struct
s = s.mpc;
else %% individual data matrices
s.version = '1';
end
catch
info = 3;
end
elseif strcmp(ext,'.m') %% from M file
if ~isempty(pathstr)
cwd = cd; %% save working directory to string
cd(pathstr); %% cd to specified directory
end
try %% assume it returns a struct
s = feval(fname);
catch
info = 4;
end
if info == 0 && ~isstruct(s) %% if not try individual data matrices
clear s;
s.version = '1';
if expect_gencost
try
[s.baseMVA, s.bus, s.gen, s.branch, ...
s.areas, s.gencost] = feval(fname);
catch
info = 4;
end
else
if return_as_struct
try
[s.baseMVA, s.bus, s.gen, s.branch, ...
s.areas, s.gencost] = feval(fname);
catch
try
[s.baseMVA, s.bus, s.gen, s.branch] = feval(fname);
catch
info = 4;
end
end
else
try
[s.baseMVA, s.bus, s.gen, s.branch] = feval(fname);
catch
info = 4;
end
end
end
end
if info == 4 && exist(fullfile(pathstr, [fname '.m']), 'file') == 2
info = 5;
err5 = lasterr;
end
if ~isempty(pathstr) %% change working directory back to original
cd(cwd);
end
end
end
elseif isstruct(casefile)
s = casefile;
else
info = 1;
end
%%----- check contents of struct -----
if info == 0
%% check for required fields
if expect_areas && ~isfield(s,'areas')
s.areas = []; %% add empty missing areas if needed for output
end
if ~( isfield(s,'baseMVA') && isfield(s,'bus') && ...
isfield(s,'gen') && isfield(s,'branch') ) || ...
( expect_gencost && ~isfield(s, 'gencost') )
info = 5; %% missing some expected fields
err5 = 'missing data';
else
%% remove empty areas if not needed
if isfield(s, 'areas') && isempty(s.areas) && ~expect_areas
s = rmfield(s, 'areas');
end
%% all fields present, copy to mpc
mpc = s;
if ~isfield(mpc, 'version') %% hmm, struct with no 'version' field
if size(mpc.gen, 2) < 21 %% version 2 has 21 or 25 cols
mpc.version = '1';
else
mpc.version = '2';
end
end
if strcmp(mpc.version, '1')
% convert from version 1 to version 2
[mpc.gen, mpc.branch] = mpc_1to2(mpc.gen, mpc.branch);
mpc.version = '2';
end
end
end
%%----- define output variables -----
if return_as_struct
bus = info;
end
if info == 0 %% no errors
if return_as_struct
baseMVA = mpc;
else
baseMVA = mpc.baseMVA;
bus = mpc.bus;
gen = mpc.gen;
branch = mpc.branch;
if expect_gencost
if expect_areas
areas = mpc.areas;
gencost = mpc.gencost;
else
areas = mpc.gencost;
end
end
end
else %% we have a problem captain
if nargout == 2 || nargout == 7 %% return error code
if return_as_struct
baseMVA = struct([]);
else
baseMVA = []; bus = []; gen = []; branch = [];
areas = []; gencost = [];
end
else %% die on error
switch info
case 1,
error('loadcase: input arg should be a struct or a string containing a filename');
case 2,
error('loadcase: specified case not in MATLAB''s search path');
case 3,
error('loadcase: specified MAT file does not exist');
case 4,
error('loadcase: specified M file does not exist');
case 5,
error('loadcase: syntax error or undefined data matrix(ices) in the file\n%s', err5);
otherwise,
error('loadcase: unknown error');
end
end
end
function [gen, branch] = mpc_1to2(gen, branch)
%% define named indices into bus, gen, branch matrices
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;
%%----- gen -----
%% use the version 1 values for column names
if size(gen, 2) > APF
error('mpc_1to2: gen matrix appears to already be in version 2 format');
end
shift = MU_PMAX - PMIN - 1;
tmp = num2cell([MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN] - shift);
[MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN] = deal(tmp{:});
%% add extra columns to gen
tmp = zeros(size(gen, 1), shift);
if size(gen, 2) >= MU_QMIN
gen = [ gen(:, 1:PMIN) tmp gen(:, MU_PMAX:MU_QMIN) ];
else
gen = [ gen(:, 1:PMIN) tmp ];
end
%%----- branch -----
%% use the version 1 values for column names
shift = PF - BR_STATUS - 1;
tmp = num2cell([PF, QF, PT, QT, MU_SF, MU_ST] - shift);
[PF, QF, PT, QT, MU_SF, MU_ST] = deal(tmp{:});
%% add extra columns to branch
tmp = ones(size(branch, 1), 1) * [-360 360];
tmp2 = zeros(size(branch, 1), 2);
if size(branch, 2) >= MU_ST
branch = [ branch(:, 1:BR_STATUS) tmp branch(:, PF:MU_ST) tmp2 ];
elseif size(branch, 2) >= QT
branch = [ branch(:, 1:BR_STATUS) tmp branch(:, PF:QT) ];
else
branch = [ branch(:, 1:BR_STATUS) tmp ];
end
|
github
|
matheusmlopess-zz/Fuzzy-Logic-power-transmission-analysis-master
|
have_fcn.m
|
.m
|
Fuzzy-Logic-power-transmission-analysis-master/matpower5.1/have_fcn.m
| 23,477 |
utf_8
|
b233d7dc93c96513131e66f4ee959fbc
|
function rv = have_fcn(tag, rtype)
%HAVE_FCN Test for optional functionality / version info.
% TORF = HAVE_FCN(TAG)
% TORF = HAVE_FCN(TAG, TOGGLE)
% VER_STR = HAVE_FCN(TAG, 'vstr')
% VER_NUM = HAVE_FCN(TAG, 'vnum')
% DATE = HAVE_FCN(TAG, 'date')
% INFO = HAVE_FCN(TAG, 'all')
%
% Returns availability, version and release information for optional
% MATPOWER functionality. All information is cached, and the cached values
% returned on subsequent calls. If the functionality exists, an attempt is
% made to determine the release date and version number. The second
% argument defines which value is returned, as follows:
% <none> 1 = optional functionality is available, 0 = not available
% 'vstr' version number as a string (e.g. '3.11.4')
% 'vnum' version number as numeric value (e.g. 3.011004)
% 'date' release date as a string (e.g. '20-Jan-2015')
% 'all' struct with fields named 'av' (for 'availability'), 'vstr',
% 'vnum' and 'date', and values corresponding to the above,
% respectively.
%
% For functionality that is not available, all calls with a string-valued
% second argument will return an empty value.
%
% Alternatively, the optional functionality specified by TAG can be toggled
% OFF or ON by calling HAVE_FCN with a numeric second argument TOGGLE with
% one of the following values:
% 0 - turn OFF the optional functionality
% 1 - turn ON the optional functionality (if available)
% -1 - toggle the ON/OFF state of the optional functionality
%
% Possible values for input TAG and their meanings:
% bpmpd - BP, BPMPD interior point solver
% clp - CLP, LP/QP solver(http://www.coin-or.org/projects/Clp.xml)
% opti_clp - version of CLP distributed with OPTI Toolbox
% (http://www.i2c2.aut.ac.nz/Wiki/OPTI/)
% cplex - CPLEX, IBM ILOG CPLEX Optimizer
% fmincon - FMINCON, solver from Optimization Toolbox 2.x +
% fmincon_ipm - FMINCON with Interior Point solver, from Opt Tbx 4.x +
% glpk - GLPK, GNU Linear Programming Kit
% gurobi - GUROBI, Gurobi solver (http://www.gurobi.com/), 5.x +
% intlinprog - INTLINPROG, MILP solver from Optimization
% Toolbox 7.0 (R2014a)+
% ipopt - IPOPT, NLP solver
% (http://www.coin-or.org/projects/Ipopt.xml)
% linprog - LINPROG, LP solver from Optimization Toolbox 2.x +
% linprog_ds - LINPROG with dual-simplex solver
% from Optimization Toolbox 7.1 (R2014b) +
% knitro - KNITRO, NLP solver (http://www.ziena.com/)
% knitromatlab - KNITRO, version 9.0.0+
% ktrlink - KNITRO, version < 9.0.0 (requires Opt Tbx)
% matlab - code is running under Matlab, as opposed to Octave
% minopf - MINOPF, MINOPF, MINOS-based OPF solver
% mosek - MOSEK, LP/QP solver (http://www.mosek.com/)
% optimoptions - OPTIMOPTIONS, option setting funciton for Optim Tbx 6.3+
% pardiso - PARDISO, Parallel Sparse Direct and Linear Solver
% (http://www.pardiso-project.org)
% quadprog - QUADPROG, QP solver from Optimization Toolbox 2.x +
% quadprog_ls - QUADPROG with large-scale interior point convex solver
% from Optimization Toolbox 6.x +
% pdipmopf - PDIPMOPF, primal-dual interior point method OPF solver
% scpdipmopf - SCPDIPMOPF, step-controlled PDIPM OPF solver
% smartmarket - RUNMARKET and friends, for running an auction
% tralmopf - TRALMOPF, trust region based augmented Langrangian
% OPF solver
% octave - code is running under Octave, as opposed to MATLAB
% sdp_pf - SDP_PF applications of semi-definite programming
% relaxation of power flow equations
% yalmip - YALMIP SDP modeling platform
% sedumi - SeDuMi SDP solver
% sdpt3 - SDPT3 SDP solver
%
% Examples:
% if have_fcn('minopf')
% results = runopf(mpc, mpoption('opf.ac.solver', 'MINOPF'));
% end
%
% Optional functionality can also be toggled OFF and ON by calling HAVE_FCN
% with the following syntax,
% TORF = HAVE_FCN(TAG, TOGGLE)
% where TOGGLE takes a numeric value as follows:
% Private tags for internal use only:
% catchme - support for 'catch me' syntax in try/catch constructs
% evalc - support for evalc() function
% ipopt_auxdata - support for ipopt_auxdata(), required by 3.11 and later
% regexp_split - support for 'split' argument to regexp()
% MATPOWER
% Copyright (c) 2004-2015 by Power System Engineering Research Center (PSERC)
% by Ray Zimmerman, PSERC Cornell
%
% $Id: have_fcn.m 2662 2015-03-20 20:02:08Z ray $
%
% This file is part of MATPOWER.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See http://www.pserc.cornell.edu/matpower/ for more info.
if nargin > 1 && isnumeric(rtype)
toggle = 1;
on_off = rtype;
if on_off < 0
TorF = have_fcn(tag);
on_off = ~TorF;
end
else
toggle = 0;
end
persistent fcns;
if toggle %% change availability
if on_off %% turn on if available
fcns = rmfield(fcns, tag); %% delete field to force re-check
else %% turn off
if ~isfield(fcns, tag) %% not yet been checked
TorF = have_fcn(tag); %% cache result first
end
fcns.(tag).av = 0; %% then turn off
end
TorF = have_fcn(tag); %% return cached value
else %% detect availability
%% info not yet cached?
if ~isfield(fcns, tag)
%%----- determine installation status, version number, etc. -----
%% initialize default values
TorF = 0;
vstr = '';
rdate = '';
switch tag
%%----- public tags -----
case 'bpmpd'
TorF = exist('bp', 'file') == 3;
if TorF
v = bpver('all');
vstr = v.Version;
rdate = v.Date;
end
case 'clp'
tmp = have_fcn('opti_clp', 'all');
if tmp.av %% have opti_clp
TorF = tmp.av;
vstr = tmp.vstr;
rdate = tmp.date;
elseif exist('clp','file') == 2 && exist('mexclp','file') == 3
TorF = 1;
vstr = '';
end
case 'opti_clp'
TorF = exist('opti_clp', 'file') == 2 && exist('clp', 'file') == 3;
if TorF
str = evalc('clp');
pat = 'CLP: COIN-OR Linear Programming \[v([^\s,]+), Built ([^\]])+\]'; %% OPTI, Giorgetti/Currie
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
rdate = datestr(t{1}{2}, 'dd-mmm-yyyy');
end
end
case 'cplex'
if exist('cplexqp', 'file')
%% it's installed, but we need to check for MEX for this arch
p = which('cplexqp'); %% get the path
len = length(p) - length('cplexqp.p');
w = what(p(1:len)); %% look for mex files on the path
for k = 1:length(w.mex)
if regexp(w.mex{k}, 'cplexlink[^\.]*');
TorF = 1;
break;
end
end
end
if TorF
try
cplex = Cplex('null');
vstr = cplex.getVersion;
catch
TorF = 0;
end
end
case {'fmincon', 'fmincon_ipm', 'intlinprog', 'linprog', ...
'linprog_ds', 'optimoptions', 'quadprog', 'quadprog_ls'}
if license('test', 'optimization_toolbox')
v = ver('optim');
vstr = v.Version;
rdate = v.Date;
switch tag
case 'fmincon'
TorF = exist('fmincon', 'file') == 2 || ...
exist('fmincon', 'file') == 6;
case 'intlinprog'
TorF = exist('intlinprog', 'file') == 2;
case 'linprog'
TorF = exist('linprog', 'file') == 2;
case 'quadprog'
TorF = exist('quadprog', 'file') == 2;
otherwise
otver = vstr2num(vstr);
switch tag
case 'fmincon_ipm'
if otver >= 4 %% Opt Tbx 4.0+ (R208a+, Matlab 7.6+)
TorF = 1;
else
TorF = 0;
end
case 'linprog_ds'
if otver >= 7.001 %% Opt Tbx 7.1+ (R2014b+, Matlab 8.4+)
TorF = 1;
else
TorF = 0;
end
case 'optimoptions'
if otver >= 6.003 %% Opt Tbx 6.3+ (R2013a+, Matlab 8.1+)
TorF = 1;
else
TorF = 0;
end
case 'quadprog_ls'
if otver >= 6 %% Opt Tbx 6.0+ (R2011a+, Matlab 7.12+)
TorF = 1;
else
TorF = 0;
end
end
end
else
TorF = 0;
end
case 'glpk'
if exist('glpk','file') == 3 %% Windows OPTI install (no glpk.m)
TorF = 1;
str = evalc('glpk');
pat = 'GLPK: GNU Linear Programming Kit \[v([^\s,]+), Built ([^\]])+\]'; %% OPTI, Giorgetti/Currie
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
rdate = datestr(t{1}{2}, 'dd-mmm-yyyy');
end
elseif exist('glpk','file') == 2 %% others have glpk.m and ...
if exist('__glpk__','file') == 3 %% octave __glpk__ MEX
TorF = 1;
if have_fcn('evalc')
str = evalc('glpk(1, 1, 1, 1, 1, ''U'', ''C'', -1, struct(''msglev'', 3))');
pat = 'GLPK Simplex Optimizer, v([^\s,]+)';
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
end
end
elseif exist('glpkcc','file') == 3 %% Matlab glpkcc MEX
TorF = 1;
str = evalc('glpk');
pat = 'GLPK Matlab interface\. Version: ([^\s,]+)'; %% glpkccm, Giorgetti/Klitgord
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
end
end
end
case 'gurobi'
TorF = exist('gurobi', 'file') == 3;
if TorF
try
model = struct( ...
'A', sparse(1), ...
'rhs', 1, ...
'sense', '=', ...
'vtype', 'C', ...
'obj', 1, ...
'modelsense', 'min' ...
);
params = struct( ...
'outputflag', 0 ...
);
result = gurobi(model, params);
vstr = sprintf('%d.%d.%d', result.versioninfo.major, result.versioninfo.minor, result.versioninfo.technical);
catch % gurobiError
fprintf('Gurobi Error!\n');
% disp(gurobiError.message);
end
end
case 'ipopt'
TorF = exist('ipopt', 'file') == 3;
if TorF
str = evalc('qps_ipopt([],1,1,1,1,1,1,1,struct(''verbose'', 2))');
pat = 'Ipopt version ([^\s,]+)';
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
if vstr2num(vstr) >= 3.011 && ...
~exist('ipopt_auxdata', 'file')
TorF = 0;
warning('Improper installation of IPOPT. Version %s detected, but IPOPT_AUXDATA.M is missing.', vstr);
end
end
end
case 'knitro' %% any Knitro
tmp = have_fcn('knitromatlab', 'all');
if tmp.av
TorF = tmp.av;
vstr = tmp.vstr;
rdate = tmp.date;
else
tmp = have_fcn('ktrlink', 'all');
if tmp.av
TorF = tmp.av;
vstr = tmp.vstr;
rdate = tmp.date;
end
end
case {'knitromatlab', 'ktrlink'}
%% knitromatlab for Knitro 9.0 or greater
%% ktrlink for pre-Knitro 9.0, requires Optim Toolbox
TorF = exist(tag, 'file') == 2;
if TorF
try
str = evalc(['[x fval] = ' tag '(@(x)1,1);']);
end
TorF = exist('fval', 'var') && fval == 1;
if TorF
pat = 'KNITRO ([^\s]+)\n';
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
end
end
end
case 'matlab'
v = ver('matlab');
if ~isempty(v) && isfield(v, 'Version') && ~isempty(v.Version)
TorF = 1;
vstr = v.Version;
rdate = v.Date;
end
case 'minopf'
TorF = exist('minopf', 'file') == 3;
if TorF
v = minopfver('all');
vstr = v.Version;
rdate = v.Date;
end
case 'mosek'
TorF = exist('mosekopt', 'file') == 3;
if TorF
% MOSEK Version 6.0.0.93 (Build date: 2010-10-26 13:03:27)
% MOSEK Version 6.0.0.106 (Build date: 2011-3-17 10:46:54)
% MOSEK Version 7.0.0.134 (Build date: 2014-10-2 11:10:02)
pat = 'Version (\.*\d)+.*Build date: (\d+-\d+-\d+)';
[s,e,tE,m,t] = regexp(evalc('mosekopt'), pat);
if ~isempty(t)
vstr = t{1}{1};
rdate = datestr(t{1}{2}, 'dd-mmm-yyyy');
end
end
case 'smartmarket'
TorF = exist('runmarket', 'file') == 2;
if TorF
v = mpver('all');
vstr = v.Version;
rdate = v.Date;
end
case 'octave'
TorF = exist('OCTAVE_VERSION', 'builtin') == 5;
if TorF
v = ver('octave');
vstr = v.Version;
rdate = v.Date;
end
case 'pardiso'
TorF = exist('pardisoinit', 'file') == 3 && ...
exist('pardisoreorder', 'file') == 3 && ...
exist('pardisofactor', 'file') == 3 && ...
exist('pardisosolve', 'file') == 3 && ...
exist('pardisofree', 'file') == 3;
if TorF
try
A = sparse([1 2; 3 4]);
b = [1;1];
% Summary PARDISO 5.1.0: ( reorder to reorder )
pat = 'Summary PARDISO (\.*\d)+:';
info = pardisoinit(11, 0);
info = pardisoreorder(A, info, false);
% [s,e,tE,m,t] = regexp(evalc('info = pardisoreorder(A, info, true);'), pat);
% if ~isempty(t)
% vstr = t{1}{1};
% end
info = pardisofactor(A, info, false);
[x, info] = pardisosolve(A, b, info, false);
pardisofree(info);
if any(x ~= [-1; 1])
TorF = 0;
end
catch
TorF = 0;
end
end
case {'pdipmopf', 'scpdipmopf', 'tralmopf'}
if have_fcn('matlab')
v = ver('Matlab');
vn = vstr2num(v.Version);
%% requires >= MATLAB 6.5 (R13) (released 20-Jun-2002)
%% older versions do not have mxCreateDoubleScalar() function
%% (they have mxCreateScalarDouble() instead)
if vn >= 6.005
switch tag
case 'pdipmopf'
TorF = exist('pdipmopf', 'file') == 3;
case 'scpdipmopf'
TorF = exist('scpdipmopf', 'file') == 3;
case 'tralmopf'
%% requires >= MATLAB 7.3 (R2006b) (released 03-Aug-2006)
%% older versions do not include the needed form of chol()
if vn >= 7.003
TorF = exist('tralmopf', 'file') == 3;
else
TorF = 0;
end
end
else
TorF = 0;
end
if TorF
v = feval([tag 'ver'], 'all');
vstr = v.Version;
rdate = v.Date;
end
end
case 'sdp_pf'
TorF = have_fcn('yalmip') && exist('mpoption_info_sdp_pf', 'file') == 2;
if TorF
v = sdp_pf_ver('all');
vstr = v.Version;
rdate = v.Date;
end
case 'yalmip'
TorF = ~have_fcn('octave') && exist('yalmip','file') == 2;
%% YALMIP does not yet work with Octave, rdz 1/6/14
if TorF
str = evalc('yalmip;');
pat = 'Version\s+([^\s]+)\n';
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
rdate = t{1}{1};
vstr = datestr(rdate, 'yy.mm.dd');
end
end
case 'sdpt3'
TorF = exist('sdpt3','file') == 2;
if TorF
str = evalc('help sdpt3');
pat = 'version\s+([^\s]+).*Last Modified: ([^\n]+)\n';
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
rdate = datestr(t{1}{2}, 'dd-mmm-yyyy');
end
end
case 'sedumi'
TorF = exist('sedumi','file') == 2;
if TorF
str = evalc('x = sedumi([1 1], 1, [1;2])');
pat = 'SeDuMi\s+([^\s]+)';
[s,e,tE,m,t] = regexp(str, pat);
if ~isempty(t)
vstr = t{1}{1};
end
end
%%----- private tags -----
case 'catchme' %% not supported by Matlab <= 7.4 (R2007a), Octave <= 3.6
if have_fcn('octave')
if have_fcn('octave', 'vnum') <= 3.006
TorF = 0;
else
TorF = 1;
end
else
if have_fcn('matlab', 'vnum') <= 7.004
TorF = 0;
else
TorF = 1;
end
end
case 'evalc'
if have_fcn('octave')
TorF = 0;
else
TorF = 1;
end
case 'ipopt_auxdata'
if have_fcn('ipopt')
vn = have_fcn('ipopt', 'vnum');
if ~isempty(vn) && vn >= 3.011
TorF = 1;
end
end
case 'regexp_split' %% missing for Matlab < 7.3 & Octave < 3.8
if have_fcn('matlab') && have_fcn('matlab', 'vnum') >= 7.003
TorF = 1;
elseif have_fcn('octave', 'vnum') >= 3.008
TorF = 1;
end
%%----- unknown tag -----
otherwise
error('have_fcn: unknown functionality %s', tag);
end
%% assign values to cache
fcns.(tag).av = TorF;
fcns.(tag).vstr = vstr;
if isempty(vstr)
fcns.(tag).vnum = [];
else
fcns.(tag).vnum = vstr2num(vstr);
end
fcns.(tag).date = rdate;
end
end
%% extract desired values from cache
if nargin < 2 || toggle
rv = fcns.(tag).av;
else
switch lower(rtype)
case 'vstr'
rv = fcns.(tag).vstr;
case 'vnum'
rv = fcns.(tag).vnum;
case 'date'
rv = fcns.(tag).date;
case 'all'
rv = fcns.(tag);
end
end
function num = vstr2num(vstr)
% Converts version string to numerical value suitable for < or > comparisons
% E.g. '3.11.4' --> 3.011004
pat = '\.?(\d+)';
[s,e,tE,m,t] = regexp(vstr, pat);
b = 1;
num = 0;
for k = 1:length(t)
num = num + b * str2num(t{k}{1});
b = b / 1000;
end
|
github
|
matheusmlopess-zz/Fuzzy-Logic-power-transmission-analysis-master
|
mpoption.m
|
.m
|
Fuzzy-Logic-power-transmission-analysis-master/matpower5.1/mpoption.m
| 65,137 |
utf_8
|
da412795e04899d174df7909834e891c
|
function opt = mpoption(varargin)
%MPOPTION Used to set and retrieve a MATPOWER options struct.
%
% OPT = MPOPTION
% Returns the default options struct.
%
% OPT = MPOPTION(OVERRIDES)
% Returns the default options struct, with some fields overridden
% by values from OVERRIDES, which can be a struct or the name of
% a function that returns a struct.
%
% OPT = MPOPTION(NAME1, VALUE1, NAME2, VALUE2, ...)
% Same as previous, except override options are specified by NAME,
% VALUE pairs. This can be used to set any part of the options
% struct. The names can be individual fields or multi-level fields
% names with embedded periods. The values can be scalars or structs.
%
% For backward compatibility, the NAMES and VALUES may correspond
% to old-style MATPOWER option names (elements in the old-style
% options vector) as well.
%
% OPT = MPOPTION(OPT0)
% Converts an old-style options vector OPT0 into the corresponding
% options struct. If OPT0 is an options struct it does nothing.
%
% OPT = MPOPTION(OPT0, OVERRIDES)
% Applies overrides to an existing set of options, OPT0, which
% can be an old-style options vector or an options struct.
%
% OPT = MPOPTION(OPT0, NAME1, VALUE1, NAME2, VALUE2, ...)
% Same as above except it uses the old-style options vector OPT0
% as a base instead of the old default options vector.
%
% OPT_VECTOR = MPOPTION(OPT, [])
% Creates and returns an old-style options vector from an
% options struct OPT.
%
% Note: The use of old-style MATPOWER options vectors and their
% names and values has been deprecated and will be removed
% in a future version of MATPOWER. Until then, all uppercase
% option names are not permitted for new top-level options.
%
% Examples:
% mpopt = mpoption('pf.alg', 'FDXB', 'pf.tol', 1e-4);
% mpopt = mpoption(mpopt, 'opf.dc.solver', 'CPLEX', 'verbose', 2);
%
%The currently defined options are as follows:
%
% name default description [options]
%---------------------- --------- ----------------------------------
%Model options:
% model 'AC' AC vs. DC power flow model
% [ 'AC' - use nonlinear AC model & corresponding algorithms/options ]
% [ 'DC' - use linear DC model & corresponding algorithms/options ]
%
%Power Flow options:
% pf.alg 'NR' AC power flow algorithm
% [ 'NR' - Newton's method ]
% [ 'FDXB' - Fast-Decoupled (XB version) ]
% [ 'FDBX' - Fast-Decoupled (BX version) ]
% [ 'GS' - Gauss-Seidel ]
% pf.tol 1e-8 termination tolerance on per unit
% P & Q mismatch
% pf.nr.max_it 10 maximum number of iterations for
% Newton's method
% pf.fd.max_it 30 maximum number of iterations for
% fast decoupled method
% pf.gs.max_it 1000 maximum number of iterations for
% Gauss-Seidel method
% pf.enforce_q_lims 0 enforce gen reactive power limits at
% expense of |V|
% [ 0 - do NOT enforce limits ]
% [ 1 - enforce limits, simultaneous bus type conversion ]
% [ 2 - enforce limits, one-at-a-time bus type conversion ]
%
%Continuation Power Flow options:
% cpf.parameterization 3 choice of parameterization
% [ 1 - natural ]
% [ 2 - arc length ]
% [ 3 - pseudo arc length ]
% cpf.stop_at 'NOSE' determins stopping criterion
% [ 'NOSE' - stop when nose point is reached ]
% [ 'FULL' - trace full nose curve ]
% [ <lam_stop> - stop upon reaching specified target lambda value ]
% cpf.step 0.05 continuation power flow step size
% cpf.adapt_step 0 toggle adaptive step size feature
% [ 0 - adaptive step size disabled ]
% [ 1 - adaptive step size enabled ]
% cpf.error_tol 1e-3 tolerance for adaptive step control
% cpf.step_min 1e-4 minimum allowed step size
% cpf.step_max 0.2 maximum allowed step size
% cpf.plot.level 0 control plotting of noze curve
% [ 0 - do not plot nose curve ]
% [ 1 - plot when completed ]
% [ 2 - plot incrementally at each iteration ]
% [ 3 - same as 2, with 'pause' at each iteration ]
% cpf.plot.bus <empty> index of bus whose voltage is to be
% plotted
% cpf.user_callback <empty> string or cell array of strings
% with names of user callback functions
% see 'help cpf_default_callback'
% cpf.user_callback_args <empty> struct passed to user-defined
% callback functions
%
%Optimal Power Flow options:
% opf.ac.solver 'DEFAULT' AC optimal power flow solver
% [ 'DEFAULT' - choose solver based on availability in the following ]
% [ order: 'PDIPM', 'MIPS' ]
% [ 'MIPS' - MIPS, Matlab Interior Point Solver, primal/dual ]
% [ interior point method (pure Matlab) ]
% [ 'FMINCON' - MATLAB Optimization Toolbox, FMINCON ]
% [ 'IPOPT' - IPOPT, requires MEX interface to IPOPT solver ]
% [ available from: ]
% [ http://www.coin-or.org/projects/Ipopt.xml ]
% [ 'KNITRO' - KNITRO, requires MATLAB Optimization Toolbox and ]
% [ KNITRO libraries available from: http://www.ziena.com/]
% [ 'MINOPF' - MINOPF, MINOS-based solver, requires optional ]
% [ MEX-based MINOPF package, available from: ]
% [ http://www.pserc.cornell.edu/minopf/ ]
% [ 'PDIPM' - PDIPM, primal/dual interior point method, requires ]
% [ optional MEX-based TSPOPF package, available from: ]
% [ http://www.pserc.cornell.edu/tspopf/ ]
% [ 'SDPOPF' - SDPOPF, solver based on semidefinite relaxation of ]
% [ OPF problem, requires optional packages: ]
% [ SDP_PF, available in extras/sdp_pf ]
% [ YALMIP, available from: ]
% [ http://users.isy.liu.se/johanl/yalmip/ ]
% [ SDP solver such as SeDuMi, available from: ]
% [ http://sedumi.ie.lehigh.edu/ ]
% [ 'TRALM' - TRALM, trust region based augmented Langrangian ]
% [ method, requires TSPOPF (see 'PDIPM') ]
% opf.dc.solver 'DEFAULT' DC optimal power flow solver
% [ 'DEFAULT' - choose solver based on availability in the following ]
% [ order: 'CPLEX', 'GUROBI', 'MOSEK','BPMPD','OT', ]
% [ 'GLPK' (linear costs only), 'MIPS' ]
% [ 'MIPS' - MIPS, Matlab Interior Point Solver, primal/dual ]
% [ interior point method (pure Matlab) ]
% [ 'BPMPD' - BPMPD, requires optional MEX-based BPMPD_MEX package ]
% [ available from: http://www.pserc.cornell.edu/bpmpd/ ]
% [ 'CLP' - CLP, requires interface to COIN-OP LP solver ]
% [ available from:http://www.coin-or.org/projects/Clp.xml]
% [ 'CPLEX' - CPLEX, requires CPLEX solver available from: ]
% [ http://www.ibm.com/software/integration/ ... ]
% [ ... optimization/cplex-optimizer/ ]
% [ 'GLPK' - GLPK, requires interface to GLPK solver ]
% [ available from: http://www.gnu.org/software/glpk/ ]
% [ (GLPK does not work with quadratic cost functions) ]
% [ 'GUROBI' - GUROBI, requires Gurobi optimizer (v. 5+) ]
% [ available from: http://www.gurobi.com/ ]
% [ 'IPOPT' - IPOPT, requires MEX interface to IPOPT solver ]
% [ available from: ]
% [ http://www.coin-or.org/projects/Ipopt.xml ]
% [ 'MOSEK' - MOSEK, requires Matlab interface to MOSEK solver ]
% [ available from: http://www.mosek.com/ ]
% [ 'OT' - MATLAB Optimization Toolbox, QUADPROG, LINPROG ]
% opf.violation 5e-6 constraint violation tolerance
% opf.flow_lim 'S' quantity limited by branch flow
% constraints
% [ 'S' - apparent power flow (limit in MVA) ]
% [ 'P' - active power flow (limit in MW) ]
% [ 'I' - current magnitude (limit in MVA at 1 p.u. voltage) ]
% opf.ignore_angle_lim 0 angle diff limits for branches
% [ 0 - include angle difference limits, if specified ]
% [ 1 - ignore angle difference limits even if specified ]
% opf.init_from_mpc -1 specify whether to use current state
% in MATPOWER case to initialize OPF
% (currently supported only for Ipopt,
% Knitro and MIPS solvers)
% [ -1 - MATPOWER decides, based on solver/algorithm ]
% [ 0 - ignore current state when initializing OPF ]
% [ 1 - use current state to initialize OPF ]
% opf.return_raw_der 0 for AC OPF, return constraint and
% derivative info in results.raw
% (in fields g, dg, df, d2f) [ 0 or 1 ]
%
%Output options:
% verbose 1 amount of progress info printed
% [ 0 - print no progress info ]
% [ 1 - print a little progress info ]
% [ 2 - print a lot of progress info ]
% [ 3 - print all progress info ]
% out.all -1 controls pretty-printing of results
% [ -1 - individual flags control what prints ]
% [ 0 - do not print anything (overrides individual flags, ignored ]
% [ for files specified as FNAME arg to runpf(), runopf(), etc.)]
% [ 1 - print everything (overrides individual flags) ]
% out.sys_sum 1 print system summary [ 0 or 1 ]
% out.area_sum 0 print area summaries [ 0 or 1 ]
% out.bus 1 print bus detail [ 0 or 1 ]
% out.branch 1 print branch detail [ 0 or 1 ]
% out.gen 0 print generator detail [ 0 or 1 ]
% out.lim.all -1 controls constraint info output
% [ -1 - individual flags control what constraint info prints ]
% [ 0 - no constraint info (overrides individual flags) ]
% [ 1 - binding constraint info (overrides individual flags) ]
% [ 2 - all constraint info (overrides individual flags) ]
% out.lim.v 1 control voltage limit info
% [ 0 - do not print ]
% [ 1 - print binding constraints only ]
% [ 2 - print all constraints ]
% [ (same options for OUT_LINE_LIM, OUT_PG_LIM, OUT_QG_LIM) ]
% out.lim.line 1 control line flow limit info
% out.lim.pg 1 control gen active power limit info
% out.lim.qg 1 control gen reactive pwr limit info
% out.force 0 print results even if success
% flag = 0 [ 0 or 1 ]
% out.suppress_detail -1 suppress all output but system summary
% [ -1 - suppress details for large systems (> 500 buses) ]
% [ 0 - do not suppress any output specified by other flags ]
% [ 1 - suppress all output except system summary section ]
% [ (overrides individual flags, but not out.all = 1) ]
%
%Solver specific options:
% name default description [options]
% ----------------------- --------- ----------------------------------
% MIPS:
% mips.linsolver '' linear system solver
% [ '' or '\' build-in backslash \ operator (e.g. x = A \ b) ]
% [ 'PARDISO' PARDISO solver (if available) ]
% mips.feastol 0 feasibility (equality) tolerance
% (set to opf.violation by default)
% mips.gradtol 1e-6 gradient tolerance
% mips.comptol 1e-6 complementary condition
% (inequality) tolerance
% mips.costtol 1e-6 optimality tolerance
% mips.max_it 150 maximum number of iterations
% mips.step_control 0 enable step-size cntrl [ 0 or 1 ]
% mips.sc.red_it 20 maximum number of reductions per
% iteration with step control
% mips.xi 0.99995 constant used in alpha updates*
% mips.sigma 0.1 centering parameter*
% mips.z0 1 used to initialize slack variables*
% mips.alpha_min 1e-8 returns "Numerically Failed" if
% either alpha parameter becomes
% smaller than this value*
% mips.rho_min 0.95 lower bound on rho_t*
% mips.rho_max 1.05 upper bound on rho_t*
% mips.mu_threshold 1e-5 KT multipliers smaller than this
% value for non-binding constraints
% are forced to zero
% mips.max_stepsize 1e10 returns "Numerically Failed" if the
% 2-norm of the reduced Newton step
% exceeds this value*
% * See the corresponding Appendix in the manual for details.
%
% CPLEX:
% cplex.lpmethod 0 solution algorithm for LP problems
% [ 0 - automatic: let CPLEX choose ]
% [ 1 - primal simplex ]
% [ 2 - dual simplex ]
% [ 3 - network simplex ]
% [ 4 - barrier ]
% [ 5 - sifting ]
% [ 6 - concurrent (dual, barrier, and primal) ]
% cplex.qpmethod 0 solution algorithm for QP problems
% [ 0 - automatic: let CPLEX choose ]
% [ 1 - primal simplex optimizer ]
% [ 2 - dual simplex optimizer ]
% [ 3 - network optimizer ]
% [ 4 - barrier optimizer ]
% cplex.opts <empty> see CPLEX_OPTIONS for details
% cplex.opt_fname <empty> see CPLEX_OPTIONS for details
% cplex.opt 0 see CPLEX_OPTIONS for details
%
% FMINCON:
% fmincon.alg 4 algorithm used by fmincon() for OPF
% for Opt Toolbox 4 and later
% [ 1 - active-set (not suitable for large problems) ]
% [ 2 - interior-point, w/default 'bfgs' Hessian approx ]
% [ 3 - interior-point, w/ 'lbfgs' Hessian approx ]
% [ 4 - interior-point, w/exact user-supplied Hessian ]
% [ 5 - interior-point, w/Hessian via finite differences ]
% [ 6 - sqp (not suitable for large problems) ]
% fmincon.tol_x 1e-4 termination tol on x
% fmincon.tol_f 1e-4 termination tol on f
% fmincon.max_it 0 maximum number of iterations
% [ 0 => default ]
%
% GUROBI:
% gurobi.method 0 solution algorithm (Method)
% [ -1 - automatic, let Gurobi decide ]
% [ 0 - primal simplex ]
% [ 1 - dual simplex ]
% [ 2 - barrier ]
% [ 3 - concurrent (LP only) ]
% [ 4 - deterministic concurrent (LP only) ]
% gurobi.timelimit Inf maximum time allowed (TimeLimit)
% gurobi.threads 0 max number of threads (Threads)
% gurobi.opts <empty> see GUROBI_OPTIONS for details
% gurobi.opt_fname <empty> see GUROBI_OPTIONS for details
% gurobi.opt 0 see GUROBI_OPTIONS for details
%
% IPOPT:
% ipopt.opts <empty> see IPOPT_OPTIONS for details
% ipopt.opt_fname <empty> see IPOPT_OPTIONS for details
% ipopt.opt 0 see IPOPT_OPTIONS for details
%
% KNITRO:
% knitro.tol_x 1e-4 termination tol on x
% knitro.tol_f 1e-4 termination tol on f
% knitro.opt_fname <empty> name of user-supplied native
% KNITRO options file that overrides
% all other options
% knitro.opt 0 if knitro.opt_fname is empty and
% knitro.opt is a non-zero integer N
% then knitro.opt_fname is auto-
% generated as:
% 'knitro_user_options_N.txt'
%
% LINPROG:
% linprog <empty> LINPROG options passed to
% OPTIMOPTIONS or OPTIMSET.
% see LINPROG in the Optimization
% Toolbox for details
%
% MINOPF:
% minopf.feastol 0 (1e-3) primal feasibility tolerance
% (set to opf.violation by default)
% minopf.rowtol 0 (1e-3) row tolerance
% minopf.xtol 0 (1e-4) x tolerance
% minopf.majdamp 0 (0.5) major damping parameter
% minopf.mindamp 0 (2.0) minor damping parameter
% minopf.penalty 0 (1.0) penalty parameter
% minopf.major_it 0 (200) major iterations
% minopf.minor_it 0 (2500) minor iterations
% minopf.max_it 0 (2500) iterations limit
% minopf.verbosity -1 amount of progress info printed
% [ -1 - controlled by 'verbose' option ]
% [ 0 - print nothing ]
% [ 1 - print only termination status message ]
% [ 2 - print termination status and screen progress ]
% [ 3 - print screen progress, report file (usually fort.9) ]
% minopf.core 0 (1200*nb + 2*(nb+ng)^2) memory allocation
% minopf.supbasic_lim 0 (2*nb + 2*ng) superbasics limit
% minopf.mult_price 0 (30) multiple price
%
% MOSEK:
% mosek.lp_alg 0 solution algorithm for LP problems
% (MSK_IPAR_OPTIMIZER)
% for MOSEK 7.x ... (see MOSEK_SYMBCON for a "better way")
% [ 0 - automatic: let MOSEK choose ]
% [ 1 - interior point ]
% [ 3 - primal simplex ]
% [ 4 - dual simplex ]
% [ 5 - primal dual simplex ]
% [ 6 - automatic simplex (MOSEK chooses which simplex method) ]
% [ 7 - network primal simplex ]
% [ 10 - concurrent ]
% mosek.max_it 0 (400) interior point max iterations
% (MSK_IPAR_INTPNT_MAX_ITERATIONS)
% mosek.gap_tol 0 (1e-8) interior point relative gap tol
% (MSK_DPAR_INTPNT_TOL_REL_GAP)
% mosek.max_time 0 (-1) maximum time allowed
% (MSK_DPAR_OPTIMIZER_MAX_TIME)
% mosek.num_threads 0 (1) max number of threads
% (MSK_IPAR_INTPNT_NUM_THREADS)
% mosek.opts <empty> see MOSEK_OPTIONS for details
% mosek.opt_fname <empty> see MOSEK_OPTIONS for details
% mosek.opt 0 see MOSEK_OPTIONS for details
%
% QUADPROG:
% quadprog <empty> QUADPROG options passed to
% OPTIMOPTIONS or OPTIMSET.
% see QUADPROG in the Optimization
% Toolbox for details
%
% TSPOPF:
% pdipm.feastol 0 feasibility (equality) tolerance
% (set to opf.violation by default)
% pdipm.gradtol 1e-6 gradient tolerance
% pdipm.comptol 1e-6 complementary condition
% (inequality) tolerance
% pdipm.costtol 1e-6 optimality tolerance
% pdipm.max_it 150 maximum number of iterations
% pdipm.step_control 0 enable step-size cntrl [ 0 or 1 ]
% pdipm.sc.red_it 20 maximum number of reductions per
% iteration with step control
% pdipm.sc.smooth_ratio 0.04 piecewise linear curve smoothing
% ratio
%
% tralm.feastol 0 feasibility tolerance
% (set to opf.violation by default)
% tralm.primaltol 5e-4 primal variable tolerance
% tralm.dualtol 5e-4 dual variable tolerance
% tralm.costtol 1e-5 optimality tolerance
% tralm.major_it 40 maximum number of major iterations
% tralm.minor_it 40 maximum number of minor iterations
% tralm.smooth_ratio 0.04 piecewise linear curve smoothing
% ratio
% MATPOWER
% Copyright (c) 2013-2015 by Power System Engineering Research Center (PSERC)
% by Ray Zimmerman, PSERC Cornell
%
% $Id: mpoption.m 2660 2015-03-20 02:10:18Z ray $
%
% This file is part of MATPOWER.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See http://www.pserc.cornell.edu/matpower/ for more info.
%% some constants
N = 124; %% number of options in old-style vector
v = mpoption_version; %% version number of MATPOWER options struct
%% initialize flags and arg counter
have_opt0 = 0; %% existing options struct or vector provided?
have_old_style_ov = 0; %% override options using old-style names?
return_old_style = 0; %% return value as old-style vector?
k = 1;
if nargin > 0
opt0 = varargin{k};
if (isstruct(opt0) && isfield(opt0, 'v')) || ...
(isnumeric(opt0) && size(opt0, 1) == N && size(opt0, 2) == 1)
have_opt0 = 1;
k = k + 1;
end
end
%% create base options vector to which overrides are made
if have_opt0
if isstruct(opt0) %% it's already a valid options struct
if DEBUG, fprintf('OPT0 is a valid options struct\n'); end
if opt0.v < v
%% convert older version to current version
opt_d = mpoption_default();
if opt0.v == 1 %% convert version 1 to 2
if isfield(opt_d, 'linprog')
opt0.lingprog = opt_d.linprog;
end
if isfield(opt_d, 'quadprog')
opt0.quadprog = opt_d.quadprog;
end
end
if opt0.v <= 2 %% convert version 2 to 3
opt0.out.suppress_detail = opt_d.out.suppress_detail;
end
%if opt0.v <= 3 %% convert version 3 to 4
%% new mips options were all optional, no conversion needed
%end
if opt0.v <= 4 %% convert version 4 to 5
opt0.opf.init_from_mpc = opt_d.opf.init_from_mpc;
end
if opt0.v <= 5 %% convert version 5 to 6
if isfield(opt_d, 'clp')
opt0.clp = opt_d.clp;
end
end
if opt0.v <= 6 %% convert version 6 to 7
if isfield(opt_d, 'intlinprog')
opt0.intlinprog = opt_d.intlinprog;
end
end
if opt0.v <= 7 %% convert version 7 to 8
opt0.mips.linsolver = opt_d.mips.linsolver;
end
opt0.v = v;
end
opt = opt0;
else %% convert from old-style options vector
if DEBUG, fprintf('OPT0 is a old-style options vector\n'); end
opt = mpoption_v2s(opt0);
end
else %% use default options struct as base
if DEBUG, fprintf('no OPT0, starting with default options struct\n'); end
opt = mpoption_default();
end
%% do we have OVERRIDES or NAME/VALUE pairs
ov = [];
if nargin - k == 0 %% looking at last arg, must be OVERRIDES
if isstruct(varargin{k}) %% OVERRIDES provided as struct
if DEBUG, fprintf('OVERRIDES struct\n'); end
ov = varargin{k};
elseif ischar(varargin{k}) %% OVERRIDES provided as file/function name
if DEBUG, fprintf('OVERRIDES file/function name\n'); end
try
ov = feval(varargin{k});
catch
error('mpoption: Unable to load MATPOWER options from ''%s''', varargin{k});
end
if ~isstruct(ov)
error('mpoption: calling ''%s'' did not return a struct', varargin{k});
end
elseif isempty(varargin{k})
return_old_style = 1;
else
error('mpoption: OVERRIDES must be a struct or the name of a function that returns a struct');
end
elseif nargin - k > 0 && mod(nargin-k, 2) %% even number of remaining args
if DEBUG, fprintf('NAME/VALUE pairs override defaults\n'); end
%% process NAME/VALUE pairs
if (have_opt0 && isnumeric(opt0)) ... %% modifying an old-style options vector
|| strcmp(varargin{k}, upper(varargin{k}))
%% this code implies that top-level option fields
%% cannot be all uppercase
if have_opt0
have_old_style_ov = 1;
%% convert pairs to struct
while k < nargin
name = varargin{k};
val = varargin{k+1};
k = k + 2;
ov.(name) = val;
end
else
opt_v = mpoption_old(varargin{:}); %% create modified vector ...
opt = mpoption_v2s(opt_v); %% ... then convert
end
else %% modifying options struct
%% convert pairs to struct
while k < nargin
name = varargin{k};
val = varargin{k+1};
k = k + 2;
c = regexp(name, '([^\.]*)', 'tokens');
s = struct();
for i = 1:length(c)
s(i).type = '.';
s(i).subs = c{i}{1};
end
ov = subsasgn(ov, s, val);
end
end
elseif nargin == 0 || nargin == 1
if DEBUG, fprintf('no OVERRIDES, return default options struct or converted OPT0 vector\n'); end
else
error('mpoption: invalid calling syntax, see ''help mpoption'' to double-check the valid options');
end
%% apply overrides
if ~isempty(ov)
if have_old_style_ov
opt = apply_old_mpoption_overrides(opt, ov);
else
vf = nested_struct_copy(mpoption_default(), mpoption_info_mips('V'));
vf = nested_struct_copy(vf, mpoption_optional_fields());
ex = struct(...
'name', {...
'cpf.user_callback_args' ...
}, ...
'check', {...
0 ...
}, ...
'copy_mode', {...
'' ...
} ...
);
%% add exceptions for optional packages
opt_pkgs = mpoption_optional_pkgs();
n = length(ex);
for k = 1:length(opt_pkgs)
fname = ['mpoption_info_' opt_pkgs{k}];
if exist(fname, 'file') == 2
opt_ex = feval(fname, 'E');
nex = length(opt_ex);
if ~isempty(opt_ex)
for j = 1:nex
ex(n+j).name = opt_ex(j).name;
end
if isfield(opt_ex, 'check')
for j = 1:nex
ex(n+j).check = opt_ex(j).check;
end
end
if isfield(opt_ex, 'copy_mode')
for j = 1:nex
ex(n+j).copy_mode = opt_ex(j).copy_mode;
end
end
if isfield(opt_ex, 'valid_fields')
for j = 1:nex
ex(n+j).valid_fields = opt_ex(j).valid_fields;
end
end
n = n + nex;
end
end
end
nsc_opt = struct('check', 1, 'valid_fields', vf, 'exceptions', ex);
% if have_fcn('catchme')
% try
% opt = nested_struct_copy(opt, ov, nsc_opt);
% catch me
% str = strrep(me.message, 'field', 'option');
% str = strrep(str, 'nested_struct_copy', 'mpoption');
% error(str);
% end
% else
try
opt = nested_struct_copy(opt, ov, nsc_opt);
catch
me = lasterr;
str = strrep(me, 'field', 'option');
str = strrep(str, 'nested_struct_copy', 'mpoption');
error(str);
end
% end
end
end
if return_old_style
opt = mpoption_s2v(opt);
end
%%-------------------------------------------------------------------
function opt = apply_old_mpoption_overrides(opt0, ov)
%
% OPT0 is assumed to already have all of the fields and sub-fields found
% in the default options struct.
%% initialize output
opt = opt0;
errstr = 'mpoption: %g is not a valid value for the old-style ''%s'' option';
fields = fieldnames(ov);
for f = 1:length(fields)
ff = fields{f};
switch ff
case 'PF_ALG'
switch ov.(ff)
case 1
opt.pf.alg = 'NR'; %% Newton's method
case 2
opt.pf.alg = 'FDXB'; %% fast-decoupled (XB version)
case 3
opt.pf.alg = 'FDBX'; %% fast-decoupled (BX version)
case 4
opt.pf.alg = 'GS'; %% Gauss-Seidel
otherwise
error(errstr, ov.(ff), ff);
end
case 'PF_TOL'
opt.pf.tol = ov.(ff);
case 'PF_MAX_IT'
opt.pf.nr.max_it = ov.(ff);
case 'PF_MAX_IT_FD'
opt.pf.fd.max_it = ov.(ff);
case 'PF_MAX_IT_GS'
opt.pf.gs.max_it = ov.(ff);
case 'ENFORCE_Q_LIMS'
opt.pf.enforce_q_lims = ov.(ff);
case 'PF_DC'
switch ov.(ff)
case 0
opt.model = 'AC';
case 1
opt.model = 'DC';
otherwise
error(errstr, ov.(ff), ff);
end
case 'OPF_ALG'
switch ov.(ff)
case 0
opt.opf.ac.solver = 'DEFAULT';
case 500
opt.opf.ac.solver = 'MINOPF';
case 520
opt.opf.ac.solver = 'FMINCON';
case {540, 545}
opt.opf.ac.solver = 'PDIPM';
if ov.(ff) == 545
opt.pdipm.step_control = 1;
else
opt.pdipm.step_control = 0;
end
case 550
opt.opf.ac.solver = 'TRALM';
case {560, 565}
opt.opf.ac.solver = 'MIPS';
if ov.(ff) == 565
opt.mips.step_control = 1;
else
opt.mips.step_control = 0;
end
case 580
opt.opf.ac.solver = 'IPOPT';
case 600
opt.opf.ac.solver = 'KNITRO';
otherwise
error(errstr, ov.(ff), ff);
end
case 'OPF_VIOLATION'
opt.opf.violation = ov.(ff);
case 'CONSTR_TOL_X'
opt.fmincon.tol_x = ov.(ff);
opt.knitro.tol_x = ov.(ff);
case 'CONSTR_TOL_F'
opt.fmincon.tol_f = ov.(ff);
opt.knitro.tol_f = ov.(ff);
case 'CONSTR_MAX_IT'
opt.fmincon.max_it = ov.(ff);
case 'OPF_FLOW_LIM'
switch ov.(ff)
case 0
opt.opf.flow_lim = 'S'; %% apparent power (MVA)
case 1
opt.opf.flow_lim = 'P'; %% real power (MW)
case 2
opt.opf.flow_lim = 'I'; %% current magnitude (MVA @ 1 p.u. voltage)
otherwise
error(errstr, ov.(ff), ff);
end
case 'OPF_IGNORE_ANG_LIM'
opt.opf.ignore_angle_lim = ov.(ff);
case 'OPF_ALG_DC'
switch ov.(ff)
case 0
opt.opf.dc.solver = 'DEFAULT';
case 100
opt.opf.dc.solver = 'BPMPD';
case {200, 250}
opt.opf.dc.solver = 'MIPS';
if ov.(ff) == 250
opt.mips.step_control = 1;
else
opt.mips.step_control = 0;
end
case 300
opt.opf.dc.solver = 'OT'; %% QUADPROG, LINPROG
case 400
opt.opf.dc.solver = 'IPOPT';
case 500
opt.opf.dc.solver = 'CPLEX';
case 600
opt.opf.dc.solver = 'MOSEK';
case 700
opt.opf.dc.solver = 'GUROBI';
otherwise
error(errstr, ov.(ff), ff);
end
case 'VERBOSE'
opt.verbose = ov.(ff);
case 'OUT_ALL'
opt.out.all = ov.(ff);
case 'OUT_SYS_SUM'
opt.out.sys_sum = ov.(ff);
case 'OUT_AREA_SUM'
opt.out.area_sum = ov.(ff);
case 'OUT_BUS'
opt.out.bus = ov.(ff);
case 'OUT_BRANCH'
opt.out.branch = ov.(ff);
case 'OUT_GEN'
opt.out.gen = ov.(ff);
case 'OUT_ALL_LIM'
opt.out.lim.all = ov.(ff);
case 'OUT_V_LIM'
opt.out.lim.v = ov.(ff);
case 'OUT_LINE_LIM'
opt.out.lim.line = ov.(ff);
case 'OUT_PG_LIM'
opt.out.lim.pg = ov.(ff);
case 'OUT_QG_LIM'
opt.out.lim.qg = ov.(ff);
case 'OUT_FORCE'
opt.out.force = ov.(ff);
case 'RETURN_RAW_DER'
opt.opf.return_raw_der = ov.(ff);
case 'FMC_ALG'
opt.fmincon.alg = ov.(ff);
case 'KNITRO_OPT'
opt.knitro.opt = ov.(ff);
case 'IPOPT_OPT'
opt.ipopt.opt = ov.(ff);
case 'MNS_FEASTOL'
opt.minopf.feastol = ov.(ff);
case 'MNS_ROWTOL'
opt.minopf.rowtol = ov.(ff);
case 'MNS_XTOL'
opt.minopf.xtol = ov.(ff);
case 'MNS_MAJDAMP'
opt.minopf.majdamp = ov.(ff);
case 'MNS_MINDAMP'
opt.minopf.mindamp = ov.(ff);
case 'MNS_PENALTY_PARM'
opt.minopf.penalty = ov.(ff);
case 'MNS_MAJOR_IT'
opt.minopf.major_it = ov.(ff);
case 'MNS_MINOR_IT'
opt.minopf.minor_it = ov.(ff);
case 'MNS_MAX_IT'
opt.minopf.max_it = ov.(ff);
case 'MNS_VERBOSITY'
opt.minopf.verbosity = ov.(ff);
case 'MNS_CORE'
opt.minopf.core = ov.(ff);
case 'MNS_SUPBASIC_LIM'
opt.minopf.supbasic_lim = ov.(ff);
case 'MNS_MULT_PRICE'
opt.minopf.mult_price = ov.(ff);
case 'FORCE_PC_EQ_P0'
opt.sopf.force_Pc_eq_P0 = ov.(ff);
case 'PDIPM_FEASTOL'
opt.mips.feastol = ov.(ff);
opt.pdipm.feastol = ov.(ff);
case 'PDIPM_GRADTOL'
opt.mips.gradtol = ov.(ff);
opt.pdipm.gradtol = ov.(ff);
case 'PDIPM_COMPTOL'
opt.mips.comptol = ov.(ff);
opt.pdipm.comptol = ov.(ff);
case 'PDIPM_COSTTOL'
opt.mips.costtol = ov.(ff);
opt.pdipm.costtol = ov.(ff);
case 'PDIPM_MAX_IT'
opt.mips.max_it = ov.(ff);
opt.pdipm.max_it = ov.(ff);
case 'SCPDIPM_RED_IT'
opt.mips.sc.red_it = ov.(ff);
opt.pdipm.sc.red_it = ov.(ff);
case 'TRALM_FEASTOL'
opt.tralm.feastol = ov.(ff);
case 'TRALM_PRIMETOL'
opt.tralm.primaltol = ov.(ff);
case 'TRALM_DUALTOL'
opt.tralm.dualtol = ov.(ff);
case 'TRALM_COSTTOL'
opt.tralm.costtol = ov.(ff);
case 'TRALM_MAJOR_IT'
opt.tralm.major_it = ov.(ff);
case 'TRALM_MINOR_IT'
opt.tralm.minor_it = ov.(ff);
case 'SMOOTHING_RATIO'
opt.pdipm.sc.smooth_ratio = ov.(ff);
opt.tralm.smooth_ratio = ov.(ff);
case 'CPLEX_LPMETHOD'
opt.cplex.lpmethod = ov.(ff);
case 'CPLEX_QPMETHOD'
opt.cplex.qpmethod = ov.(ff);
case 'CPLEX_OPT'
opt.cplex.opt = ov.(ff);
case 'MOSEK_LP_ALG'
opt.mosek.lp_alg = ov.(ff);
case 'MOSEK_MAX_IT'
opt.mosek.max_it = ov.(ff);
case 'MOSEK_GAP_TOL'
opt.mosek.gap_tol = ov.(ff);
case 'MOSEK_MAX_TIME'
opt.mosek.max_time = ov.(ff);
case 'MOSEK_NUM_THREADS'
opt.mosek.num_threads = ov.(ff);
case 'MOSEK_OPT'
opt.mosek.opt = ov.(ff);
case 'GRB_METHOD'
opt.gurobi.method = ov.(ff);
case 'GRB_TIMELIMIT'
opt.gurobi.timelimit = ov.(ff);
case 'GRB_THREADS'
opt.gurobi.threads = ov.(ff);
case 'GRB_OPT'
opt.gurobi.opt = ov.(ff);
otherwise
error('mpoption: ''%s'' is not a valid old-style option name', ff);
end
end
% ov
%%-------------------------------------------------------------------
function opt_s = mpoption_v2s(opt_v)
if DEBUG, fprintf('mpoption_v2s()\n'); end
opt_s = mpoption_default();
errstr = 'mpoption: %g is not a valid value for the old-style ''%s'' option';
switch opt_v(1) %% PF_ALG
case 1
opt_s.pf.alg = 'NR'; %% Newton's method
case 2
opt_s.pf.alg = 'FDXB'; %% fast-decoupled (XB version)
case 3
opt_s.pf.alg = 'FDBX'; %% fast-decoupled (BX version)
case 4
opt_s.pf.alg = 'GS'; %% Gauss-Seidel
otherwise
error(errstr, opt_v(1), 'PF_ALG');
end
opt_s.pf.tol = opt_v(2); %% PF_TOL
opt_s.pf.nr.max_it = opt_v(3); %% PF_MAX_IT
opt_s.pf.fd.max_it = opt_v(4); %% PF_MAX_IT_FD
opt_s.pf.gs.max_it = opt_v(5); %% PF_MAX_IT_GS
opt_s.pf.enforce_q_lims = opt_v(6); %% ENFORCE_Q_LIMS
switch opt_v(10) %% PF_DC
case 0
opt_s.model = 'AC';
case 1
opt_s.model = 'DC';
otherwise
error(errstr, opt_v(10), 'PF_DC');
end
switch opt_v(11) %% OPF_ALG
case 0
opt_s.opf.ac.solver = 'DEFAULT';
case 500
opt_s.opf.ac.solver = 'MINOPF';
case 520
opt_s.opf.ac.solver = 'FMINCON';
case {540, 545}
opt_s.opf.ac.solver = 'PDIPM';
case 550
opt_s.opf.ac.solver = 'TRALM';
case {560, 565}
opt_s.opf.ac.solver = 'MIPS';
case 580
opt_s.opf.ac.solver = 'IPOPT';
case 600
opt_s.opf.ac.solver = 'KNITRO';
otherwise
error(errstr, opt_v(11), 'OPF_ALG');
end
opt_s.opf.violation = opt_v(16); %% OPF_VIOLATION
opt_s.fmincon.tol_x = opt_v(17); %% CONSTR_TOL_X
opt_s.fmincon.tol_f = opt_v(18); %% CONSTR_TOL_F
opt_s.fmincon.max_it = opt_v(19); %% CONSTR_MAX_IT
opt_s.knitro.tol_x = opt_v(17); %% CONSTR_TOL_X
opt_s.knitro.tol_f = opt_v(18); %% CONSTR_TOL_F
switch opt_v(24) %% OPF_FLOW_LIM
case 0
opt_s.opf.flow_lim = 'S'; %% apparent power (MVA)
case 1
opt_s.opf.flow_lim = 'P'; %% real power (MW)
case 2
opt_s.opf.flow_lim = 'I'; %% current magnitude (MVA @ 1 p.u. voltage)
otherwise
error(errstr, opt_v(10), 'PF_DC');
end
opt_s.opf.ignore_angle_lim = opt_v(25); %% OPF_IGNORE_ANG_LIM
switch opt_v(26) %% OPF_ALG_DC
case 0
opt_s.opf.dc.solver = 'DEFAULT';
case 100
opt_s.opf.dc.solver = 'BPMPD';
case {200, 250}
opt_s.opf.dc.solver = 'MIPS';
case 300
opt_s.opf.dc.solver = 'OT'; %% QUADPROG, LINPROG
case 400
opt_s.opf.dc.solver = 'IPOPT';
case 500
opt_s.opf.dc.solver = 'CPLEX';
case 600
opt_s.opf.dc.solver = 'MOSEK';
case 700
opt_s.opf.dc.solver = 'GUROBI';
otherwise
error(errstr, opt_v(26), 'OPF_ALG_DC');
end
opt_s.verbose = opt_v(31); %% VERBOSE
opt_s.out.all = opt_v(32); %% OUT_ALL
opt_s.out.sys_sum = opt_v(33); %% OUT_SYS_SUM
opt_s.out.area_sum = opt_v(34); %% OUT_AREA_SUM
opt_s.out.bus = opt_v(35); %% OUT_BUS
opt_s.out.branch = opt_v(36); %% OUT_BRANCH
opt_s.out.gen = opt_v(37); %% OUT_GEN
opt_s.out.lim.all = opt_v(38); %% OUT_ALL_LIM
opt_s.out.lim.v = opt_v(39); %% OUT_V_LIM
opt_s.out.lim.line = opt_v(40); %% OUT_LINE_LIM
opt_s.out.lim.pg = opt_v(41); %% OUT_PG_LIM
opt_s.out.lim.qg = opt_v(42); %% OUT_QG_LIM
opt_s.out.force = opt_v(44); %% OUT_FORCE
opt_s.opf.return_raw_der = opt_v(52); %% RETURN_RAW_DER
opt_s.fmincon.alg = opt_v(55); %% FMC_ALG
opt_s.knitro.opt = opt_v(58); %% KNITRO_OPT
opt_s.ipopt.opt = opt_v(60); %% IPOPT_OPT
opt_s.minopf.feastol = opt_v(61); %% MNS_FEASTOL
opt_s.minopf.rowtol = opt_v(62); %% MNS_ROWTOL
opt_s.minopf.xtol = opt_v(63); %% MNS_XTOL
opt_s.minopf.majdamp = opt_v(64); %% MNS_MAJDAMP
opt_s.minopf.mindamp = opt_v(65); %% MNS_MINDAMP
opt_s.minopf.penalty = opt_v(66); %% MNS_PENALTY_PARM
opt_s.minopf.major_it = opt_v(67); %% MNS_MAJOR_IT
opt_s.minopf.minor_it = opt_v(68); %% MNS_MINOR_IT
opt_s.minopf.max_it = opt_v(69); %% MNS_MAX_IT
opt_s.minopf.verbosity = opt_v(70); %% MNS_VERBOSITY
opt_s.minopf.core = opt_v(71); %% MNS_CORE
opt_s.minopf.supbasic_lim = opt_v(72); %% MNS_SUPBASIC_LIM
opt_s.minopf.mult_price = opt_v(73); %% MNS_MULT_PRICE
opt_s.sopf.force_Pc_eq_P0 = opt_v(80); %% FORCE_PC_EQ_P0, for c3sopf
if (opt_v(11) == 565 && opt_v(10) == 0) || (opt_v(26) == 250 && opt_v(10) == 1)
opt_s.mips.step_control = 1;
end
opt_s.mips.feastol = opt_v(81); %% PDIPM_FEASTOL
opt_s.mips.gradtol = opt_v(82); %% PDIPM_GRADTOL
opt_s.mips.comptol = opt_v(83); %% PDIPM_COMPTOL
opt_s.mips.costtol = opt_v(84); %% PDIPM_COSTTOL
opt_s.mips.max_it = opt_v(85); %% PDIPM_MAX_IT
opt_s.mips.sc.red_it = opt_v(86); %% SCPDIPM_RED_IT
opt_s.pdipm.feastol = opt_v(81); %% PDIPM_FEASTOL
opt_s.pdipm.gradtol = opt_v(82); %% PDIPM_GRADTOL
opt_s.pdipm.comptol = opt_v(83); %% PDIPM_COMPTOL
opt_s.pdipm.costtol = opt_v(84); %% PDIPM_COSTTOL
opt_s.pdipm.max_it = opt_v(85); %% PDIPM_MAX_IT
opt_s.pdipm.sc.red_it = opt_v(86); %% SCPDIPM_RED_IT
opt_s.pdipm.sc.smooth_ratio = opt_v(93); %% SMOOTHING_RATIO
if opt_v(11) == 545 && opt_v(10) == 0
opt_s.pdipm.step_control = 1;
end
opt_s.tralm.feastol = opt_v(87); %% TRALM_FEASTOL
opt_s.tralm.primaltol = opt_v(88); %% TRALM_PRIMETOL
opt_s.tralm.dualtol = opt_v(89); %% TRALM_DUALTOL
opt_s.tralm.costtol = opt_v(90); %% TRALM_COSTTOL
opt_s.tralm.major_it = opt_v(91); %% TRALM_MAJOR_IT
opt_s.tralm.minor_it = opt_v(92); %% TRALM_MINOR_IT
opt_s.tralm.smooth_ratio = opt_v(93); %% SMOOTHING_RATIO
opt_s.cplex.lpmethod = opt_v(95); %% CPLEX_LPMETHOD
opt_s.cplex.qpmethod = opt_v(96); %% CPLEX_QPMETHOD
opt_s.cplex.opt = opt_v(97); %% CPLEX_OPT
opt_s.mosek.lp_alg = opt_v(111); %% MOSEK_LP_ALG
opt_s.mosek.max_it = opt_v(112); %% MOSEK_MAX_IT
opt_s.mosek.gap_tol = opt_v(113); %% MOSEK_GAP_TOL
opt_s.mosek.max_time = opt_v(114); %% MOSEK_MAX_TIME
opt_s.mosek.num_threads = opt_v(115); %% MOSEK_NUM_THREADS
opt_s.mosek.opt = opt_v(116); %% MOSEK_OPT
opt_s.gurobi.method = opt_v(121); %% GRB_METHOD
opt_s.gurobi.timelimit = opt_v(122); %% GRB_TIMELIMIT
opt_s.gurobi.threads = opt_v(123); %% GRB_THREADS
opt_s.gurobi.opt = opt_v(124); %% GRB_OPT
%%-------------------------------------------------------------------
function opt_v = mpoption_s2v(opt_s)
if DEBUG, fprintf('mpoption_s2v()\n'); end
%% PF_ALG
old = mpoption_old;
switch upper(opt_s.pf.alg)
case 'NR'
PF_ALG = 1;
case 'FDXB'
PF_ALG = 2;
case 'FDBX'
PF_ALG = 3;
case 'GS'
PF_ALG = 4;
end
%% PF_DC
if strcmp(upper(opt_s.model), 'DC')
PF_DC = 1;
else
PF_DC = 0;
end
%% OPF_ALG
switch upper(opt_s.opf.ac.solver)
case 'DEFAULT'
OPF_ALG = 0;
case 'MINOPF'
OPF_ALG = 500;
case 'FMINCON'
OPF_ALG = 520;
case 'PDIPM'
if isfield(opt_s, 'pdipm') && opt_s.pdipm.step_control
OPF_ALG = 545;
else
OPF_ALG = 540;
end
case 'TRALM'
OPF_ALG = 550;
case 'MIPS'
if opt_s.mips.step_control
OPF_ALG = 565;
else
OPF_ALG = 560;
end
case 'IPOPT'
OPF_ALG = 580;
case 'KNITRO'
OPF_ALG = 600;
end
%% FMINCON, Knitro tol_x, tol_f, max_it
if strcmp(upper(opt_s.opf.ac.solver), 'KNITRO') && isfield(opt_s, 'knitro')
CONSTR_TOL_X = opt_s.knitro.tol_x;
CONSTR_TOL_F = opt_s.knitro.tol_f;
elseif isfield(opt_s, 'fmincon')
CONSTR_TOL_X = opt_s.fmincon.tol_x;
CONSTR_TOL_F = opt_s.fmincon.tol_f;
else
CONSTR_TOL_X = old(17);
CONSTR_TOL_F = old(18);
end
if isfield(opt_s, 'fmincon')
CONSTR_MAX_IT = opt_s.fmincon.max_it;
FMC_ALG = opt_s.fmincon.alg;
else
CONSTR_MAX_IT = old(19);
FMC_ALG = old(55);
end
%% OPF_FLOW_LIM
switch upper(opt_s.opf.flow_lim)
case 'S'
OPF_FLOW_LIM = 0;
case 'P'
OPF_FLOW_LIM = 1;
case 'I'
OPF_FLOW_LIM = 2;
end
%% OPF_ALG_DC
switch upper(opt_s.opf.dc.solver)
case 'DEFAULT'
OPF_ALG_DC = 0;
case 'BPMPD'
OPF_ALG_DC = 100;
case 'MIPS'
if opt_s.mips.step_control
OPF_ALG_DC = 250;
else
OPF_ALG_DC = 200;
end
case 'OT'
OPF_ALG_DC = 300;
case 'IPOPT'
OPF_ALG_DC = 400;
case 'CPLEX'
OPF_ALG_DC = 500;
case 'MOSEK'
OPF_ALG_DC = 600;
case 'GUROBI'
OPF_ALG_DC = 700;
end
%% KNITRO_OPT
if isfield(opt_s, 'knitro')
KNITRO_OPT = opt_s.knitro.opt;
else
KNITRO_OPT = old(58);
end
%% IPOPT_OPT
if isfield(opt_s, 'ipopt')
IPOPT_OPT = opt_s.ipopt.opt;
else
IPOPT_OPT = old(58);
end
%% MINOPF options
if isfield(opt_s, 'minopf')
MINOPF_OPTS = [
opt_s.minopf.feastol; %% 61 - MNS_FEASTOL
opt_s.minopf.rowtol; %% 62 - MNS_ROWTOL
opt_s.minopf.xtol; %% 63 - MNS_XTOL
opt_s.minopf.majdamp; %% 64 - MNS_MAJDAMP
opt_s.minopf.mindamp; %% 65 - MNS_MINDAMP
opt_s.minopf.penalty; %% 66 - MNS_PENALTY_PARM
opt_s.minopf.major_it; %% 67 - MNS_MAJOR_IT
opt_s.minopf.minor_it; %% 68 - MNS_MINOR_IT
opt_s.minopf.max_it; %% 69 - MNS_MAX_IT
opt_s.minopf.verbosity; %% 70 - MNS_VERBOSITY
opt_s.minopf.core; %% 71 - MNS_CORE
opt_s.minopf.supbasic_lim; %% 72 - MNS_SUPBASIC_LIM
opt_s.minopf.mult_price;%% 73 - MNS_MULT_PRICE
];
else
MINOPF_OPTS = old(61:73);
end
%% FORCE_PC_EQ_P0
if isfield(opt_s, 'sopf') && isfield(opt_s.sopf, 'force_Pc_eq_P0')
FORCE_PC_EQ_P0 = opt_s.sopf.force_Pc_eq_P0;
else
FORCE_PC_EQ_P0 = 0;
end
%% PDIPM options
if isfield(opt_s, 'pdipm')
PDIPM_OPTS = [
opt_s.pdipm.feastol; %% 81 - PDIPM_FEASTOL
opt_s.pdipm.gradtol; %% 82 - PDIPM_GRADTOL
opt_s.pdipm.comptol; %% 83 - PDIPM_COMPTOL
opt_s.pdipm.costtol; %% 84 - PDIPM_COSTTOL
opt_s.pdipm.max_it; %% 85 - PDIPM_MAX_IT
opt_s.pdipm.sc.red_it; %% 86 - SCPDIPM_RED_IT
];
else
PDIPM_OPTS = old(81:86);
end
%% TRALM options
if isfield(opt_s, 'tralm')
TRALM_OPTS = [
opt_s.tralm.feastol; %% 87 - TRALM_FEASTOL
opt_s.tralm.primaltol; %% 88 - TRALM_PRIMETOL
opt_s.tralm.dualtol; %% 89 - TRALM_DUALTOL
opt_s.tralm.costtol; %% 90 - TRALM_COSTTOL
opt_s.tralm.major_it; %% 91 - TRALM_MAJOR_IT
opt_s.tralm.minor_it; %% 92 - TRALM_MINOR_IT
];
else
TRALM_OPTS = old(87:92);
end
%% SMOOTHING_RATIO
if strcmp(upper(opt_s.opf.ac.solver), 'TRALM') && isfield(opt_s, 'tralm')
SMOOTHING_RATIO = opt_s.tralm.smooth_ratio;
elseif isfield(opt_s, 'pdipm')
SMOOTHING_RATIO = opt_s.pdipm.sc.smooth_ratio;
else
SMOOTHING_RATIO = old(93);
end
%% CPLEX options
if isfield(opt_s, 'cplex')
CPLEX_OPTS = [
opt_s.cplex.lpmethod; %% 95 - CPLEX_LPMETHOD
opt_s.cplex.qpmethod; %% 96 - CPLEX_QPMETHOD
opt_s.cplex.opt; %% 97 - CPLEX_OPT
];
else
CPLEX_OPTS = old(95:97);
end
%% MOSEK options
if isfield(opt_s, 'mosek')
MOSEK_OPTS = [
opt_s.mosek.lp_alg; %% 111 - MOSEK_LP_ALG
opt_s.mosek.max_it; %% 112 - MOSEK_MAX_IT
opt_s.mosek.gap_tol; %% 113 - MOSEK_GAP_TOL
opt_s.mosek.max_time; %% 114 - MOSEK_MAX_TIME
opt_s.mosek.num_threads;%% 115 - MOSEK_NUM_THREADS
opt_s.mosek.opt; %% 116 - MOSEK_OPT
];
else
MOSEK_OPTS = old(111:116);
end
%% Gurobi options
if isfield(opt_s, 'gurobi')
GUROBI_OPTS = [
opt_s.gurobi.method; %% 121 - GRB_METHOD
opt_s.gurobi.timelimit; %% 122 - GRB_TIMELIMIT
opt_s.gurobi.threads; %% 123 - GRB_THREADS
opt_s.gurobi.opt; %% 124 - GRB_OPT
];
else
GUROBI_OPTS = old(121:124);
end
opt_v = [
%% power flow options
PF_ALG; %% 1 - PF_ALG
opt_s.pf.tol; %% 2 - PF_TOL
opt_s.pf.nr.max_it; %% 3 - PF_MAX_IT
opt_s.pf.fd.max_it; %% 4 - PF_MAX_IT_FD
opt_s.pf.gs.max_it; %% 5 - PF_MAX_IT_GS
opt_s.pf.enforce_q_lims;%% 6 - ENFORCE_Q_LIMS
0; %% 7 - RESERVED7
0; %% 8 - RESERVED8
0; %% 9 - RESERVED9
PF_DC; %% 10 - PF_DC
%% OPF options
OPF_ALG; %% 11 - OPF_ALG
0; %% 12 - RESERVED12 (was OPF_ALG_POLY = 100)
0; %% 13 - RESERVED13 (was OPF_ALG_PWL = 200)
0; %% 14 - RESERVED14 (was OPF_POLY2PWL_PTS = 10)
0; %% 15 - OPF_NEQ (removed)
opt_s.opf.violation; %% 16 - OPF_VIOLATION
CONSTR_TOL_X; %% 17 - CONSTR_TOL_X
CONSTR_TOL_F; %% 18 - CONSTR_TOL_F
CONSTR_MAX_IT; %% 19 - CONSTR_MAX_IT
old(20); %% 20 - LPC_TOL_GRAD (removed)
old(21); %% 21 - LPC_TOL_X (removed)
old(22); %% 22 - LPC_MAX_IT (removed)
old(23); %% 23 - LPC_MAX_RESTART (removed)
OPF_FLOW_LIM; %% 24 - OPF_FLOW_LIM
opt_s.opf.ignore_angle_lim; %% 25 - OPF_IGNORE_ANG_LIM
OPF_ALG_DC; %% 26 - OPF_ALG_DC
0; %% 27 - RESERVED27
0; %% 28 - RESERVED28
0; %% 29 - RESERVED29
0; %% 30 - RESERVED30
%% output options
opt_s.verbose; %% 31 - VERBOSE
opt_s.out.all; %% 32 - OUT_ALL
opt_s.out.sys_sum; %% 33 - OUT_SYS_SUM
opt_s.out.area_sum; %% 34 - OUT_AREA_SUM
opt_s.out.bus; %% 35 - OUT_BUS
opt_s.out.branch; %% 36 - OUT_BRANCH
opt_s.out.gen; %% 37 - OUT_GEN
opt_s.out.lim.all; %% 38 - OUT_ALL_LIM
opt_s.out.lim.v; %% 39 - OUT_V_LIM
opt_s.out.lim.line; %% 40 - OUT_LINE_LIM
opt_s.out.lim.pg; %% 41 - OUT_PG_LIM
opt_s.out.lim.qg; %% 42 - OUT_QG_LIM
0; %% 43 - RESERVED43 (was OUT_RAW)
opt_s.out.force; %% 44 - OUT_FORCE
0; %% 45 - RESERVED45
0; %% 46 - RESERVED46
0; %% 47 - RESERVED47
0; %% 48 - RESERVED48
0; %% 49 - RESERVED49
0; %% 50 - RESERVED50
%% other options
old(51); %% 51 - SPARSE_QP (removed)
opt_s.opf.return_raw_der; %% 52 - RETURN_RAW_DER
0; %% 53 - RESERVED53
0; %% 54 - RESERVED54
FMC_ALG; %% 55 - FMC_ALG
0; %% 56 - RESERVED56
0; %% 57 - RESERVED57
KNITRO_OPT; %% 58 - KNITRO_OPT
0; %% 59 - RESERVED59
IPOPT_OPT; %% 60 - IPOPT_OPT
%% MINOPF options
MINOPF_OPTS; %% 61-73 - MNS_FEASTOL-MNS_MULT_PRICE
0; %% 74 - RESERVED74
0; %% 75 - RESERVED75
0; %% 76 - RESERVED76
0; %% 77 - RESERVED77
0; %% 78 - RESERVED78
0; %% 79 - RESERVED79
FORCE_PC_EQ_P0; %% 80 - FORCE_PC_EQ_P0, for c3sopf
%% MIPS, PDIPM, SC-PDIPM, and TRALM options
PDIPM_OPTS; %% 81-86 - PDIPM_FEASTOL-SCPDIPM_RED_IT
TRALM_OPTS; %% 87-92 - TRALM_FEASTOL-TRALM_MINOR_IT
SMOOTHING_RATIO; %% 93 - SMOOTHING_RATIO
0; %% 94 - RESERVED94
%% CPLEX options
CPLEX_OPTS; %% 95-97 - CPLEX_LPMETHOD-CPLEX_OPT
0; %% 98 - RESERVED98
0; %% 99 - RESERVED99
0; %% 100 - RESERVED100
0; %% 101 - RESERVED101
0; %% 102 - RESERVED102
0; %% 103 - RESERVED103
0; %% 104 - RESERVED104
0; %% 105 - RESERVED105
0; %% 106 - RESERVED106
0; %% 107 - RESERVED107
0; %% 108 - RESERVED108
0; %% 109 - RESERVED109
0; %% 110 - RESERVED110
%% MOSEK options
MOSEK_OPTS; %% 111-116 - MOSEK_LP_ALG-MOSEK_OPT
0; %% 117 - RESERVED117
0; %% 118 - RESERVED118
0; %% 119 - RESERVED119
0; %% 120 - RESERVED120
%% Gurobi options
GUROBI_OPTS; %% 121-124 - GRB_METHOD-GRB_OPT
];
%%-------------------------------------------------------------------
function opt = mpoption_default()
if DEBUG, fprintf('mpoption_default()\n'); end
opt = struct(...
'v', mpoption_version, ... %% version
'model', 'AC', ...
'pf', struct(...
'alg', 'NR', ...
'tol', 1e-8, ...
'nr', struct(...
'max_it', 10 ), ...
'fd', struct(...
'max_it', 30 ), ...
'gs', struct(...
'max_it', 1000 ), ...
'enforce_q_lims', 0 ), ...
'cpf', struct(...
'parameterization', 3, ...
'stop_at', 'NOSE', ... %% 'NOSE', <lam val>, 'FULL'
'step', 0.05, ...
'adapt_step', 0, ...
'error_tol', 1e-3, ...
'step_min', 1e-4, ...
'step_max', 0.2, ...
'plot', struct(...
'level', 0, ...
'bus', [] ), ...
'user_callback', '', ...
'user_callback_args', struct() ), ...
'opf', struct(...
'ac', struct(...
'solver', 'DEFAULT' ), ...
'dc', struct(...
'solver', 'DEFAULT' ), ...
'violation', 5e-6, ...
'flow_lim', 'S', ...
'ignore_angle_lim', 0, ...
'init_from_mpc', -1, ...
'return_raw_der', 0 ), ...
'verbose', 1, ...
'out', struct(...
'all', -1, ...
'sys_sum', 1, ...
'area_sum', 0, ...
'bus', 1, ...
'branch', 1, ...
'gen', 0, ...
'lim', struct(...
'all', -1, ...
'v', 1, ...
'line', 1, ...
'pg', 1, ...
'qg', 1 ), ...
'force', 0, ...
'suppress_detail', -1 ), ...
'mips', struct(... %% see mpoption_info_mips() for optional fields
'step_control', 0, ...
'linsolver', '', ...
'feastol', 0, ...
'gradtol', 1e-6, ...
'comptol', 1e-6, ...
'costtol', 1e-6, ...
'max_it', 150, ...
'sc', struct(...
'red_it', 20 )) ...
);
opt_pkgs = mpoption_optional_pkgs();
for k = 1:length(opt_pkgs)
fname = ['mpoption_info_' opt_pkgs{k}];
if exist(fname, 'file') == 2
opt = nested_struct_copy(opt, feval(fname, 'D'));
end
end
%%-------------------------------------------------------------------
function opt = mpoption_optional_fields()
if DEBUG, fprintf('mpoption_optional_fields()\n'); end
opt_pkgs = mpoption_optional_pkgs();
opt = struct;
for k = 1:length(opt_pkgs)
fname = ['mpoption_info_' opt_pkgs{k}];
if exist(fname, 'file') == 2
opt = nested_struct_copy(opt, feval(fname, 'V'));
end
end
%% globals
%%-------------------------------------------------------------------
function v = mpoption_version
v = 8; %% version number of MATPOWER options struct
%% (must be incremented every time structure is updated)
%% v1 - first version based on struct (MATPOWER 5.0b1)
%% v2 - added 'linprog' and 'quadprog' fields
%% v3 - (forgot to increment v) added 'out.suppress_detail'
%% field
%% v4 - (forgot to increment v) MIPS 1.1, added optional
%% fields to 'mips' options: xi, sigma, z0, alpha_min,
%% rho_min, rho_max, mu_threshold and max_stepsize
%% v5 - (forgot to increment v) added 'opf.init_from_mpc'
%% field (MATPOWER 5.0)
%% v6 - added 'clp' field
%% v7 - added 'intlinprog' field
%% v8 - MIPS 1.2, added 'linsolver' field to
%% 'mips' options
%%-------------------------------------------------------------------
function db_level = DEBUG
db_level = 0;
%%-------------------------------------------------------------------
function pkgs = mpoption_optional_pkgs()
pkgs = {...
'clp', 'cplex', 'fmincon', 'gurobi', 'glpk', 'intlinprog', 'ipopt', ...
'knitro', 'linprog', 'minopf', 'mosek', 'quadprog', 'sdp_pf', 'sopf', ...
'tspopf', 'yalmip' ...
};
|
github
|
jay-mahadeokar/deeplab-public-ver2-master
|
classification_demo.m
|
.m
|
deeplab-public-ver2-master/matlab/demo/classification_demo.m
| 5,412 |
utf_8
|
8f46deabe6cde287c4759f3bc8b7f819
|
function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to you Matlab search PATH to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github
|
jay-mahadeokar/deeplab-public-ver2-master
|
MyVOCevalseg.m
|
.m
|
deeplab-public-ver2-master/matlab/my_script/MyVOCevalseg.m
| 4,625 |
utf_8
|
128c24319d520c2576168d1cf17e068f
|
%VOCEVALSEG Evaluates a set of segmentation results.
% VOCEVALSEG(VOCopts,ID); prints out the per class and overall
% segmentation accuracies. Accuracies are given using the intersection/union
% metric:
% true positives / (true positives + false positives + false negatives)
%
% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class
% percentage ACCURACIES, the average accuracy AVACC and the confusion
% matrix CONF.
%
% [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns
% the unnormalised confusion matrix, which contains raw pixel counts.
function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id)
% image test set
[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');
% number of labels = number of classes plus one for the background
num = VOCopts.nclasses+1;
confcounts = zeros(num);
count=0;
num_missing_img = 0;
tic;
for i=1:length(gtids)
% display progress
if toc>1
fprintf('test confusion: %d/%d\n',i,length(gtids));
drawnow;
tic;
end
imname = gtids{i};
% ground truth label file
gtfile = sprintf(VOCopts.seg.clsimgpath,imname);
[gtim,map] = imread(gtfile);
gtim = double(gtim);
% results file
resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);
try
[resim,map] = imread(resfile);
catch err
num_missing_img = num_missing_img + 1;
%fprintf(1, 'Fail to read %s\n', resfile);
continue;
end
resim = double(resim);
% Check validity of results image
maxlabel = max(resim(:));
if (maxlabel>VOCopts.nclasses),
error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);
end
szgtim = size(gtim); szresim = size(resim);
if any(szgtim~=szresim)
error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));
end
%pixel locations to include in computation
locs = gtim<255;
% joint histogram
sumim = 1+gtim+resim*num;
hs = histc(sumim(locs),1:num*num);
count = count + numel(find(locs));
confcounts(:) = confcounts(:) + hs(:);
end
if (num_missing_img > 0)
fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img);
end
% confusion matrix - first index is true label, second is inferred label
%conf = zeros(num);
conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]);
rawcounts = confcounts;
% Pixel Accuracy
overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));
fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc);
% Class Accuracy
class_acc = zeros(1, num);
class_count = 0;
fprintf('Accuracy for each class (pixel accuracy)\n');
for i = 1 : num
denom = sum(confcounts(i, :));
if (denom == 0)
denom = 1;
end
class_acc(i) = 100 * confcounts(i, i) / denom;
if i == 1
clname = 'background';
else
clname = VOCopts.classes{i-1};
end
if ~strcmp(clname, 'void')
class_count = class_count + 1;
fprintf(' %14s: %6.3f%%\n', clname, class_acc(i));
end
end
fprintf('-------------------------\n');
avg_class_acc = sum(class_acc) / class_count;
fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc);
% Pixel IOU
accuracies = zeros(VOCopts.nclasses,1);
fprintf('Accuracy for each class (intersection/union measure)\n');
real_class_count = 0;
for j=1:num
gtj=sum(confcounts(j,:));
resj=sum(confcounts(:,j));
gtjresj=confcounts(j,j);
% The accuracy is: true positive / (true positive + false positive + false negative)
% which is equivalent to the following percentage:
denom = (gtj+resj-gtjresj);
if denom == 0
denom = 1;
end
accuracies(j)=100*gtjresj/denom;
clname = 'background';
if (j>1), clname = VOCopts.classes{j-1};end;
if ~strcmp(clname, 'void')
real_class_count = real_class_count + 1;
else
if denom ~= 1
fprintf(1, 'WARNING: this void class has denom = %d\n', denom);
end
end
if ~strcmp(clname, 'void')
fprintf(' %14s: %6.3f%%\n',clname,accuracies(j));
end
end
%accuracies = accuracies(1:end);
%avacc = mean(accuracies);
avacc = sum(accuracies) / real_class_count;
fprintf('-------------------------\n');
fprintf('Average accuracy: %6.3f%%\n',avacc);
|
github
|
jay-mahadeokar/deeplab-public-ver2-master
|
MyVOCevalsegBoundary.m
|
.m
|
deeplab-public-ver2-master/matlab/my_script/MyVOCevalsegBoundary.m
| 4,415 |
utf_8
|
1b648714e61bafba7c08a8ce5824b105
|
%VOCEVALSEG Evaluates a set of segmentation results.
% VOCEVALSEG(VOCopts,ID); prints out the per class and overall
% segmentation accuracies. Accuracies are given using the intersection/union
% metric:
% true positives / (true positives + false positives + false negatives)
%
% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class
% percentage ACCURACIES, the average accuracy AVACC and the confusion
% matrix CONF.
%
% [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns
% the unnormalised confusion matrix, which contains raw pixel counts.
function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w)
% get structural element
st_w = 2*w + 1;
se = strel('square', st_w);
% image test set
fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset);
fid = fopen(fn, 'r');
gtids = textscan(fid, '%s');
gtids = gtids{1};
fclose(fid);
%[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');
% number of labels = number of classes plus one for the background
num = VOCopts.nclasses+1;
confcounts = zeros(num);
count=0;
tic;
for i=1:length(gtids)
% display progress
if toc>1
fprintf('test confusion: %d/%d\n',i,length(gtids));
drawnow;
tic;
end
imname = gtids{i};
% ground truth label file
gtfile = sprintf(VOCopts.seg.clsimgpath,imname);
[gtim,map] = imread(gtfile);
gtim = double(gtim);
% results file
resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);
try
[resim,map] = imread(resfile);
catch err
fprintf(1, 'Fail to read %s\n', resfile);
continue;
end
resim = double(resim);
% Check validity of results image
maxlabel = max(resim(:));
if (maxlabel>VOCopts.nclasses),
error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);
end
szgtim = size(gtim); szresim = size(resim);
if any(szgtim~=szresim)
error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));
end
% dilate gt
binary_gt = gtim == 255;
dilate_gt = imdilate(binary_gt, se);
target_gt = dilate_gt & (gtim~=255);
%pixel locations to include in computation
locs = target_gt;
%locs = gtim<255;
% joint histogram
sumim = 1+gtim+resim*num;
hs = histc(sumim(locs),1:num*num);
count = count + numel(find(locs));
confcounts(:) = confcounts(:) + hs(:);
end
% confusion matrix - first index is true label, second is inferred label
%conf = zeros(num);
conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]);
rawcounts = confcounts;
% Pixel Accuracy
overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));
fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc);
% Class Accuracy
class_acc = zeros(1, num);
class_count = 0;
fprintf('Accuracy for each class (pixel accuracy)\n');
for i = 1 : num
denom = sum(confcounts(i, :));
if (denom == 0)
denom = 1;
else
class_count = class_count + 1;
end
class_acc(i) = 100 * confcounts(i, i) / denom;
if i == 1
clname = 'background';
else
clname = VOCopts.classes{i-1};
end
fprintf(' %14s: %6.3f%%\n', clname, class_acc(i));
end
fprintf('-------------------------\n');
avg_class_acc = sum(class_acc) / class_count;
fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc);
% Pixel IOU
accuracies = zeros(VOCopts.nclasses,1);
fprintf('Accuracy for each class (intersection/union measure)\n');
for j=1:num
gtj=sum(confcounts(j,:));
resj=sum(confcounts(:,j));
gtjresj=confcounts(j,j);
% The accuracy is: true positive / (true positive + false positive + false negative)
% which is equivalent to the following percentage:
accuracies(j)=100*gtjresj/(gtj+resj-gtjresj);
clname = 'background';
if (j>1), clname = VOCopts.classes{j-1};end;
fprintf(' %14s: %6.3f%%\n',clname,accuracies(j));
end
accuracies = accuracies(1:end);
avacc = mean(accuracies);
fprintf('-------------------------\n');
fprintf('Average accuracy: %6.3f%%\n',avacc);
|
github
|
happyharrycn/unsupervised_edges-master
|
computeColor.m
|
.m
|
unsupervised_edges-master/flow_utils/computeColor.m
| 3,139 |
utf_8
|
4344a6f1decdd6631805bd81be0b4442
|
function img = computeColor(u,v)
% computeColor color codes flow field U, V
% According to the c++ source code of Daniel Scharstein
% Contact: [email protected]
% Author: Deqing Sun, Department of Computer Science, Brown University
% Contact: [email protected]
% $Date: 2007-10-31 21:20:30 (Wed, 31 Oct 2006) $
% Copyright 2007, Deqing Sun.
%
% All Rights Reserved
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for any purpose other than its incorporation into a
% commercial product is hereby granted without fee, provided that the
% above copyright notice appear in all copies and that both that
% copyright notice and this permission notice appear in supporting
% documentation, and that the name of the author and Brown University not be used in
% advertising or publicity pertaining to distribution of the software
% without specific, written prior permission.
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
% INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY
% PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR OR BROWN UNIVERSITY BE LIABLE FOR
% ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
nanIdx = isnan(u) | isnan(v);
u(nanIdx) = 0;
v(nanIdx) = 0;
colorwheel = makeColorwheel();
ncols = size(colorwheel, 1);
rad = sqrt(u.^2+v.^2);
a = atan2(-v, -u)/pi;
fk = (a+1) /2 * (ncols-1) + 1; % -1~1 maped to 1~ncols
k0 = floor(fk); % 1, 2, ..., ncols
k1 = k0+1;
k1(k1==ncols+1) = 1;
f = fk - k0;
for i = 1:size(colorwheel,2)
tmp = colorwheel(:,i);
col0 = tmp(k0)/255;
col1 = tmp(k1)/255;
col = (1-f).*col0 + f.*col1;
idx = rad <= 1;
col(idx) = 1-rad(idx).*(1-col(idx)); % increase saturation with radius
col(~idx) = col(~idx)*0.75; % out of range
img(:,:, i) = uint8(floor(255*col.*(1-nanIdx)));
end;
%%
function colorwheel = makeColorwheel()
% color encoding scheme
% adapted from the color circle idea described at
% http://members.shaw.ca/quadibloc/other/colint.htm
RY = 15;
YG = 6;
GC = 4;
CB = 11;
BM = 13;
MR = 6;
ncols = RY + YG + GC + CB + BM + MR;
colorwheel = zeros(ncols, 3); % r g b
col = 0;
%RY
colorwheel(1:RY, 1) = 255;
colorwheel(1:RY, 2) = floor(255*(0:RY-1)/RY)';
col = col+RY;
%YG
colorwheel(col+(1:YG), 1) = 255 - floor(255*(0:YG-1)/YG)';
colorwheel(col+(1:YG), 2) = 255;
col = col+YG;
%GC
colorwheel(col+(1:GC), 2) = 255;
colorwheel(col+(1:GC), 3) = floor(255*(0:GC-1)/GC)';
col = col+GC;
%CB
colorwheel(col+(1:CB), 2) = 255 - floor(255*(0:CB-1)/CB)';
colorwheel(col+(1:CB), 3) = 255;
col = col+CB;
%BM
colorwheel(col+(1:BM), 3) = 255;
colorwheel(col+(1:BM), 1) = floor(255*(0:BM-1)/BM)';
col = col+BM;
%MR
colorwheel(col+(1:MR), 3) = 255 - floor(255*(0:MR-1)/MR)';
colorwheel(col+(1:MR), 1) = 255;
|
github
|
happyharrycn/unsupervised_edges-master
|
distinguishable_colors.m
|
.m
|
unsupervised_edges-master/flow_utils/distinguishable_colors.m
| 5,753 |
utf_8
|
57960cf5d13cead2f1e291d1288bccb2
|
function colors = distinguishable_colors(n_colors,bg,func)
% DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct
%
% When plotting a set of lines, you may want to distinguish them by color.
% By default, Matlab chooses a small set of colors and cycles among them,
% and so if you have more than a few lines there will be confusion about
% which line is which. To fix this problem, one would want to be able to
% pick a much larger set of distinct colors, where the number of colors
% equals or exceeds the number of lines you want to plot. Because our
% ability to distinguish among colors has limits, one should choose these
% colors to be "maximally perceptually distinguishable."
%
% This function generates a set of colors which are distinguishable
% by reference to the "Lab" color space, which more closely matches
% human color perception than RGB. Given an initial large list of possible
% colors, it iteratively chooses the entry in the list that is farthest (in
% Lab space) from all previously-chosen entries. While this "greedy"
% algorithm does not yield a global maximum, it is simple and efficient.
% Moreover, the sequence of colors is consistent no matter how many you
% request, which facilitates the users' ability to learn the color order
% and avoids major changes in the appearance of plots when adding or
% removing lines.
%
% Syntax:
% colors = distinguishable_colors(n_colors)
% Specify the number of colors you want as a scalar, n_colors. This will
% generate an n_colors-by-3 matrix, each row representing an RGB
% color triple. If you don't precisely know how many you will need in
% advance, there is no harm (other than execution time) in specifying
% slightly more than you think you will need.
%
% colors = distinguishable_colors(n_colors,bg)
% This syntax allows you to specify the background color, to make sure that
% your colors are also distinguishable from the background. Default value
% is white. bg may be specified as an RGB triple or as one of the standard
% "ColorSpec" strings. You can even specify multiple colors:
% bg = {'w','k'}
% or
% bg = [1 1 1; 0 0 0]
% will only produce colors that are distinguishable from both white and
% black.
%
% colors = distinguishable_colors(n_colors,bg,rgb2labfunc)
% By default, distinguishable_colors uses the image processing toolbox's
% color conversion functions makecform and applycform. Alternatively, you
% can supply your own color conversion function.
%
% Example:
% c = distinguishable_colors(25);
% figure
% image(reshape(c,[1 size(c)]))
%
% Example using the file exchange's 'colorspace':
% func = @(x) colorspace('RGB->Lab',x);
% c = distinguishable_colors(25,'w',func);
% Copyright 2010-2011 by Timothy E. Holy
% Parse the inputs
if (nargin < 2)
bg = [1 1 1]; % default white background
else
if iscell(bg)
% User specified a list of colors as a cell aray
bgc = bg;
for i = 1:length(bgc)
bgc{i} = parsecolor(bgc{i});
end
bg = cat(1,bgc{:});
else
% User specified a numeric array of colors (n-by-3)
bg = parsecolor(bg);
end
end
% Generate a sizable number of RGB triples. This represents our space of
% possible choices. By starting in RGB space, we ensure that all of the
% colors can be generated by the monitor.
n_grid = 30; % number of grid divisions along each axis in RGB space
x = linspace(0,1,n_grid);
[R,G,B] = ndgrid(x,x,x);
rgb = [R(:) G(:) B(:)];
if (n_colors > size(rgb,1)/3)
error('You can''t readily distinguish that many colors');
end
% Convert to Lab color space, which more closely represents human
% perception
if (nargin > 2)
lab = func(rgb);
bglab = func(bg);
else
C = makecform('srgb2lab');
lab = applycform(rgb,C);
bglab = applycform(bg,C);
end
% If the user specified multiple background colors, compute distances
% from the candidate colors to the background colors
mindist2 = inf(size(rgb,1),1);
for i = 1:size(bglab,1)-1
dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg
dist2 = sum(dX.^2,2); % square distance
mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color
end
% Iteratively pick the color that maximizes the distance to the nearest
% already-picked color
colors = zeros(n_colors,3);
lastlab = bglab(end,:); % initialize by making the "previous" color equal to background
for i = 1:n_colors
dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list
dist2 = sum(dX.^2,2); % square distance
mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color
[~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors
colors(i,:) = rgb(index,:); % save for output
lastlab = lab(index,:); % prepare for next iteration
end
end
function c = parsecolor(s)
if ischar(s)
c = colorstr2rgb(s);
elseif isnumeric(s) && size(s,2) == 3
c = s;
else
error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.');
end
end
function c = colorstr2rgb(c)
% Convert a color string to an RGB value.
% This is cribbed from Matlab's whitebg function.
% Why don't they make this a stand-alone function?
rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0];
cspec = 'rgbwcmyk';
k = find(cspec==c(1));
if isempty(k)
error('MATLAB:InvalidColorString','Unknown color string.');
end
if k~=3 || length(c)==1,
c = rgbspec(k,:);
elseif length(c)>2,
if strcmpi(c(1:3),'bla')
c = [0 0 0];
elseif strcmpi(c(1:3),'blu')
c = [0 0 1];
else
error('MATLAB:UnknownColorString', 'Unknown color string.');
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.